REST in Java for Payment Gateway Integration

Posted on Posted in Custom Programming, Java

In case you are in need of code snippet that needs to access REST APIs securely (e.g. payment gateway integration), here is a sample client code in Java using Apache HttpComponents.

		// set the connection pool manager
		PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
		cm.setMaxTotal(200);
		cm.setDefaultMaxPerRoute(50);
		
		CloseableHttpClient httpClient = 
			      HttpClients.custom()
			                 .setConnectionManager(cm)
			                 .build();
			 
	    HttpPost httpPost = new HttpPost("https://subdomain.paymentgateway.com/payments");
	    httpPost.setHeader("Accept", "*/*");
	    httpPost.setHeader("Content-type", "application/json");
	    String authToken = Base64Utils.encodeToString("username:password".getBytes());
	    httpPost.setHeader("Authorization", "Basic "+authToken);

	    StringEntity entity = new StringEntity("{\n  \"paymentTokenId\": \""+paymentTokenId+"\",\n  \"totalAmount\": {\n    \"amount\": 100,\n    \"currency\": \"PHP\"\n  },\n  }\n  }\n}");
	    httpPost.setEntity(entity);
		
		HttpResponse response = httpClient.execute(httpPost);
		
		_log.info(response.toString());
		_log.info(response.getEntity());	 
		
		httpClient.close();

You will notice that header for Authorization is set and credentials are encoded in Base64. This is a standard http authentication mechanism.

As a troubleshooting tip, you may want to use existing REST client to test the service. Tools like Postman or browser plugins like RESTClient are useful to test if the service is properly responding to requests.

Warning: Apache HttpComponents is currently under heavy development with lots of code changes and refactoring, and we observed that some newer versions are not working properly. So, you will have to explore different versions and different method calls to see which one actually works. Also, documentation and forum discussions are fragmented because many methods are deprecated in minor version upgrades. The code above uses version 4.3.6.



Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.