Paytm payment gateway integration in spring boot

 Paytm payment gateway integration in spring boot

Paytm payment gateway in spring boot using REST APIs.
We will use the swagger for testing our APIs.
Github Url: https://github.com/247tuts/PaytmPaymentGateway.git

Project Structure

projectStructure

PaytmChecksum Jar file

You will get the PaymentChecksum.jar from the code which is available on Github and we already provide the path of paytmchecksum.jar file in our pom.xml file.

Pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.4.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.paytm</groupId>
	<artifactId>PaytmPaymentGateway</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>PaytmPaymentGateway</name>
	<description>Paytm Payment Integration</description>
	<properties>
		<java.version>1.8</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<!-- Swagger Integration -->
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger2</artifactId>
			<version>2.9.2</version>
		</dependency>
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger-ui</artifactId>
			<version>2.9.2</version>
		</dependency>
		<!-- Thymeleaf -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
		<dependency>
			<groupId>com.paytm</groupId>
			<artifactId>paytm</artifactId>
			<version>1.0</version>
			<scope>system</scope>
			<systemPath>${project.basedir}/src/main/resources/PaytmChecksum.jar</systemPath>
<!-- For Linux Users
<systemPath>/home/ubuntu/iconnect-backend/PaytmChecksum.jar</systemPath> !-->
		</dependency>
		<dependency>
			<groupId>org.json</groupId>
			<artifactId>json</artifactId>
			<version>20190722</version>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<configuration>
				    <includeSystemScope>true</includeSystemScope>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

Now its time for the superhero entry PaymentController.
So let’s get Started

PaymentController

In this controller we have two methods one is payment and the other one is checkPaymentStatus. First, we will discuss the payment method. The payment method is responsible for initializing the transaction and remembers one thing this method returns the String in HTML format and if you want to test then just copy the response and paste into the notepad file with .html and open that file in browser it will automatically redirect you to the Paytm page. Let’s dive into it.

	public String payment(@RequestParam String transactionId,@RequestParam String amount)throws Throwable {
		/* initialize a TreeMap object */
		TreeMap<String, String> paytmParams = new TreeMap<String, String>();
		/*
		 * Find your MID in your Paytm Dashboard at
		 * https://dashboard.paytm.com/next/apikeys
		 */
		paytmParams.put("MID",env.getProperty("merchantId"));
		/*
		 * Find your WEBSITE in your Paytm Dashboard at
		 * https://dashboard.paytm.com/next/apikeys
		 */
		paytmParams.put("WEBSITE",env.getProperty("website"));
		/*
		 * Find your INDUSTRY_TYPE_ID in your Paytm Dashboard at
		 * https://dashboard.paytm.com/next/apikeys
		 */
		paytmParams.put("INDUSTRY_TYPE_ID",env.getProperty("industryTypeId"));
		/* WEB for website and WAP for Mobile-websites or App */
		paytmParams.put("CHANNEL_ID",env.getProperty("channelId"));
		/* Enter your unique order id */
		paytmParams.put("ORDER_ID",transactionId);
		/* unique id that belongs to your customer */
		paytmParams.put("CUST_ID", "123456");
		/* customer's mobile number */
		//paytmParams.put("MOBILE_NO",mobileNo);
		/* customer's email */
		//paytmParams.put("EMAIL",email);
		/**
		 * Amount in INR that is payble by customer this should be numeric with
		 * optionally having two decimal points
		 */
		paytmParams.put("TXN_AMOUNT", amount);
		/* on completion of transaction, we will send you the response on this URL */
		paytmParams.put("CALLBACK_URL",env.getProperty("callbackUrl"));
		/**
		 * Generate checksum for parameters we have You can get Checksum JAR from
		 * https://developer.paytm.com/docs/checksum/ Find your Merchant Key in your
		 * Paytm Dashboard at https://dashboard.paytm.com/next/apikeys
		 */
		String checksum = CheckSumServiceHelper.getCheckSumServiceHelper().genrateCheckSum(env.getProperty("merchantKey"),
				paytmParams);
		/* for Staging */
		String url = "https://securegw-stage.paytm.in/order/process";
		/* for Production */
		// String url = "https://securegw.paytm.in/order/process";
		/* Prepare HTML Form and Submit to Paytm */
		StringBuilder outputHtml = new StringBuilder();
		outputHtml.append("<html>");
		outputHtml.append("<head>");
		outputHtml.append("<title>Merchant Checkout Page</title>");
		outputHtml.append("</head>");
		outputHtml.append("<body>");
		outputHtml.append("<center><h1>Please do not refresh this page...</h1></center>");
		outputHtml.append("<form method='post' action='" + url + "' name='paytm_form'>");
		for (Map.Entry<String, String> entry : paytmParams.entrySet()) {
			outputHtml.append("<input type='hidden' name='" + entry.getKey() + "' value='" + entry.getValue() + "'>");
		}
		outputHtml.append("<input type='hidden' name='CHECKSUMHASH' value='" + checksum + "'>");
		outputHtml.append("</form>");
		outputHtml.append("<script type='text/javascript'>");
		outputHtml.append("document.paytm_form.submit();");
		outputHtml.append("</script>");
		outputHtml.append("</body>");
		outputHtml.append("</html>");
		return outputHtml.toString();
	}

checkPaymentStatus method will check the status of the Transaction.

.public Map<String,String> checkPaymentStatus(HttpServletRequest request) throws Throwable{
		Map<String, String[]> mapData = request.getParameterMap();
		TreeMap<String, String> parameters = new TreeMap<String, String>();
		mapData.forEach((key, val) -> parameters.put(key, val[0]));
		TreeMap<String, String> paytmParams = new TreeMap<String, String>();
		paytmParams.put("MID",env.getProperty("merchantId"));
		paytmParams.put("ORDERID",parameters.get("ORDERID"));
		/*
		* Generate checksum by parameters we have
		* You can get Checksum JAR from https://developer.paytm.com/docs/checksum/
		* Find your Merchant Key in your Paytm Dashboard at https://dashboard.paytm.com/next/apikeys
		*/
		String checksum = CheckSumServiceHelper.getCheckSumServiceHelper().genrateCheckSum(env.getProperty("merchantKey"),
				paytmParams);
		paytmParams.put("CHECKSUMHASH", checksum);
		JSONObject obj = new JSONObject(paytmParams);
		String post_data = obj.toString();
		Map<String,String> response=new HashMap<String, String>();
		/* for Staging */
		URL url = new URL("https://securegw-stage.paytm.in/order/status");
		/* for Production */
		// URL url = new URL("https://securegw.paytm.in/order/status");
		try {
		    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		    connection.setRequestMethod("POST");
		    connection.setRequestProperty("Content-Type", "application/json");
		    connection.setDoOutput(true);
		    DataOutputStream requestWriter = new DataOutputStream(connection.getOutputStream());
		    requestWriter.writeBytes(post_data);
		    requestWriter.close();
		    String responseData = "";
		    InputStream is = connection.getInputStream();
		    BufferedReader responseReader = new BufferedReader(new InputStreamReader(is));
		    Map<String,String> map=new HashMap<String, String>();
		    if ((responseData = responseReader.readLine()) != null) {
		    	System.out.println("resonse :"+responseData);
		    }
		    String result="";
			if (map.containsKey("RESPCODE")) {
				if (map.get("RESPCODE").equals("01")) {
					result = "Success";
				} else {
					result = "Failed";
				}
			} else {
				result = "Checksum mismatched";
			}
			responseReader.close();
			response.put("status",result);
		    return response;
		} catch (Exception exception) {
		    exception.printStackTrace();
		}
		return response;
	}

Tree

Related post

9 Comments

  • When some one searches for his vital thing, thus he/she wants to be available that in detail, thus that thing is maintained over here. Wanda Laurent Heriberto

  • Pretty! This has been an incredibly wonderful post. Thanks for supplying this information. Anneliese Connie Teriann

  • Its not my first time to pay a visit this web site, i am browsing this website dailly and take good facts from here daily. Dorise Darnall March

  • Wow, great article post. Really thank you! Awesome. Samara Curr Robina

  • Appreciate the recommendation. Let me try it out.

  • Greate article. Keep writing such kind of info
    on your page. Im really impressed by your site.
    Hey there, You’ve performed an incredible job. I will definitely digg it and for my part recommend to my friends.
    I’m sure they’ll be benefited from this website.

  • Good article. I will be facing some of these issues as well.. Jacqueline Aldwin Gerlac

  • Hi there. I found your blog via Google while searching for a related matter, your web site came up. It seems to be great. I have bookmarked it in my google bookmarks to come back then. Giorgia Gail Woodrow

  • You ought to be a part of a contest for one of the best blogs on the web. I will highly recommend this website! Brynn Aldo Wendye

Leave a Reply

Your email address will not be published. Required fields are marked *