In this video we are going to integration paytm payment gateway in our website step by step . This video is very simple video of integrating paytm payment . Receive Payment on Website | Simplest way of Integration Paytm Payment Integration in Hindi

 

 

Integrating Razor pay: https://www.youtube.com/watch?v=-Ke6JYqTM_s

 

First of all  signup on paytm dashboard website and get your key details.

 

Add these dependency in pom.xml

  <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20180130</version>
        </dependency>

<dependency>
            <groupId>com.paytm.pg</groupId>
            <artifactId>paytm-checksum</artifactId>
            <version>1.2.1</version>
</dependency>

 

AppConfig.java

package com.paytm.integration.config;

public class AppConfig {
    public static final String MID="RHLBnF070397707073";
    public static final String MKEY="BXWmXtYo858BTG";
    public static final String WEBSITE="WEBSTAGING";
}

PageController.java

package com.paytm.integration.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class PageController {

    @RequestMapping("/")
    public String homePage() {
        System.out.println("Request for home page");
        return "home";
    }
  @RequestMapping("/about")
    public String aboutPage() {
        System.out.println("Request for about page");
        return "about";
    }


}

PaymentController.java

package com.paytm.integration.controllers;

import com.paytm.integration.config.AppConfig;
import com.paytm.pg.merchant.PaytmChecksum;
import org.json.JSONObject;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.net.URL;
import java.util.Map;
import java.util.Random;

@RestController
@RequestMapping("/payment")
public class PaymentController {


    Random random = new Random();


    @PostMapping("/start")
    public Map<String, Object> startPayment(
            @RequestBody Map<String, Object> data
    ) {


        String orderId = "ORDER" + random.nextInt(10000000);

        //param created
        JSONObject paytmParams = new JSONObject();


        //body information
        JSONObject body = new JSONObject();
        body.put("requestType", "Payment");
        body.put("mid", AppConfig.MID);
        body.put("websiteName", AppConfig.WEBSITE);
        body.put("orderId", orderId);
        body.put("callbackUrl", "http://localhost:8081/payment-success");

        JSONObject txnAmount = new JSONObject();
        txnAmount.put("value", data.get("amount"));
        txnAmount.put("currency", "INR");

        JSONObject userInfo = new JSONObject();
        userInfo.put("custId", "CUST_001");


        body.put("txnAmount", txnAmount);
        body.put("userInfo", userInfo);

        String responseData = "";
        ResponseEntity<Map> response = null;

        try {

            String checksum = PaytmChecksum.generateSignature(body.toString(), AppConfig.MKEY);

            JSONObject head = new JSONObject();
            head.put("signature", checksum);

            paytmParams.put("body", body);
            paytmParams.put("head", head);

            String post_data = paytmParams.toString();

            /* for Staging */
            URL url = new URL("https://securegw-stage.paytm.in/theia/api/v1/initiateTransaction?mid=" + AppConfig.MID + "&orderId=" + orderId + "");

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(paytmParams.toMap(), headers);

            //calling api
            RestTemplate restTemplate = new RestTemplate();
            response = restTemplate.postForEntity(url.toString(), httpEntity, Map.class);

            System.out.println(response);


        } catch (Exception e) {
            e.printStackTrace();
        }

        Map body1 = response.getBody();
        body1.put("orderId", orderId);
        body1.put("amount", txnAmount.get("value"));
        return body1;
    }

    public void capturePayment(){
        //get the data from client

        //verify the payment

        //database mein bhi update kar do ki payment ho chuka hai...


        //allow user to access the service
    }

}

Home.html

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bootstrap demo</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
          integrity="sha384-iYQeCzEYFbKjA/T2uDLTpkwGzCiq6soy8tYaI1GyVh/UjpbCx/TYkiZhlZB6+fzT" crossorigin="anonymous">
    <style>
        body {
            background: #e2e2e2;
        }
    </style>
</head>
<body>


<div class="container">
    <div class="row m-5">
        <div class="col-md-6 offset-md-3">
            <div class="card border-0 shadow">
                <div class="card-body">
                    <h3>Donate to Free Education</h3>

                    <div class="m-2">
                        <label for="user_name">Your name</label>
                        <input id="user_name" type="text" class="form-control">
                    </div>
                    <div class="m-2">
                        <label for="user_phone">Your phone</label>
                        <input id="user_phone" type="text" class="form-control">
                    </div>
                    <div class="m-2">
                        <label for="user_amount">Amount</label>
                        <input id="user_amount" type="text" class="form-control">
                    </div>
                    <div class="container text-center">
                        <button class="btn btn-primary btn-sm" onclick="startPayment()">Proceed to pay</button>
                    </div>

                </div>
            </div>
        </div>
    </div>
</div>


<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-u1OknCvxWvY5kfmNBILK2hRnQC3Pr17a+RTT6rIHI7NnikvbZlHgTPOOmMi466C8"
        crossorigin="anonymous"></script>

<script>


    function initiateClientModule(data) {

        const script = document.createElement("script");
        script.src = ` https://securegw-stage.paytm.in/merchantpgpui/checkoutjs/merchants/RHLB07039627707073.js`;
        script.crossOrigin = `anonymous`;
        script.onload = () => {

            var config = {
                "root": "",
                "flow": "DEFAULT",
                "data": {
                    "orderId": data.orderId, /* update order id */
                    "token": data.body.txnToken, /* update token value */
                    "tokenType": "TXN_TOKEN",
                    "amount": data.amount/* update amount */
                },

                "merchant": {

                    mid: "RHLBnF070327707073",
                    redirect: false
                },

                "handler": {
                    "notifyMerchant": function (eventName, data) {
                        console.log("notifyMerchant handler function called");
                        console.log("eventName => ", eventName);
                        console.log("data => ", data);
                    },
                    "transactionStatus": function (data) {
                        console.log("transaction completed")
                        console.log(data)

                        if (data.STATUS = "TXN_FAILURE") {
                            alert(data.RESPMSG)
                        } else if (data.STATUS == 'TXN_SUCCESS') {
                            alert(data.RESPMSG)

                            //capture api with data : call kar lo
                        } else {
                            alert("Something wend wrong while payment contact to admin!!")
                        }

                        window.Paytm.CheckoutJS.close();


                    }


                }
            };


            if (window.Paytm && window.Paytm.CheckoutJS) {
                window.Paytm.CheckoutJS.onLoad(function excecuteAfterCompleteLoad() {
                    // initialze configuration using init method
                    window.Paytm.CheckoutJS.init(config).then(function onSuccess() {
                        // after successfully updating configuration, invoke JS Checkout
                        window.Paytm.CheckoutJS.invoke();
                    }).catch(function onError(error) {
                        console.log("error => ", error);
                    });
                });
            }

        }

        document.body.appendChild(script);


    }

    //start payment function
    async function startPayment() {
        //call api to start payment
        const amount = document.querySelector("#user_amount").value

        const baseUrl = "http://localhost:8081"

        const response = await fetch(`${baseUrl}/payment/start`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({'amount': amount})
        })


        response.json().then(data => {
            //order is generated successfully
            console.log(data)


            initiateClientModule(data)


        }).catch(error => {
            console.log(error)
            alert("error in initiating payment")
        })


    }
</script>
</body>
</html>

 

Note: I used spring boot for backend and simple javascript for backend . These technologies is of my choice you can you any technology if you got the concept.