Introduction

Are you stuck with a requirement to integrate a payment gateway into your project? Are you looking for a simple and easy-to-follow tutorial? If yes, this tutorial on Integrating the Paytm payment gateway using ReactJS is for you! In this step-by-step guide, we will walk you through the process of implementing a payment gateway in seven easy steps. Let’s get started!

Tutorial Goal: Integrate Paytm Payment Gateway using ReactJS

In this tutorial, we will build a small demo application with a button labeled “Pay Now.” When you click the button, a modal will be displayed with the Paytm checkout options. SvayambhuTech has ensured that the library we use allows you to customize the modal and add various payment methods, as per your requirement.

Steps to Integrate Paytm Payment Gateway using ReactJS

1. Create a New Paytm Developer Account

To begin, you’ll need to create a new secret key by registering a Paytm developer account.

  • Go to Paytm Developer, log in if you are an existing user, or create a new account.
  • After logging in, go to the Dashboard and collect the Test API Keys for testing purposes.

2. Collect the API Keys

Once you’ve logged into your Paytm Developer account, you can access the Test API Details directly from the Dashboard. You can use these test API keys to integrate Paytm.

3. Create a ReactJS Application

Use the following command to create a new ReactJS application:

create-react-app <app-name>

This will generate a new project with the default folder structure.

4. Adding Paytm Library to index.html

You need to link the Paytm library to your project by adding the script tag in the public/index.html file. Use the following snippet:

<script src="https://securegw-stage.paytm.in/merchantpgpui/checkoutjs/merchants/<mid>.js"></script>

5. Logic & UI: Paytm Payment Integration

Now, let’s set up the main logic for the Paytm payment integration using ReactJS.

  • Create a new file called PaytmButton.js inside the /paytm-button folder. This file will handle all the logic related to the Paytm payment integration.
  • The user interface will feature a “Pay Now” button that, when clicked, triggers the Paytm checkout modal.

6. Initialize Paytm: Token Generation & Configuration

Inside the PaytmButton.js file, we need to create an initializePaytm() function, which will handle the initialization and token generation steps. The function will be triggered when the page loads using useEffect:

useEffect(() => {
   initializePaytm();
}, []);

const initializePaytm = () => {
   let orderId = "Order_" + new Date().getTime();
   let mid = ""; // Merchant ID
   let mkey = ""; // Merchant Key

   let paytmParams = {
     body: {
       requestType: "Payment",
       mid: mid,
       websiteName: "WEBSTAGING",
       orderId: orderId,
       callbackUrl: "https://merchant.com/callback",
       txnAmount: { value: 100, currency: "INR" },
       userInfo: { custId: "1001" },
     }
   };

   PaytmChecksum.generateSignature(
     JSON.stringify(paytmParams.body),
     mkey
   ).then(function (checksum) {
     paytmParams.head = { signature: checksum };
     let post_data = JSON.stringify(paytmParams);

     let options = {
       hostname: "securegw.paytm.in",
       port: 443,
       path: `/theia/api/v1/initiateTransaction?mid=${mid}&orderId=${orderId}`,
       method: "POST",
       headers: {
         "Content-Type": "application/json",
         "Content-Length": post_data.length,
       },
     };

     let response = "";
     let post_req = https.request(options, function (post_res) {
       post_res.on("data", function (chunk) {
         response += chunk;
       });
       post_res.on("end", function () {
         setPaymentData({
           ...paymentData,
           token: JSON.parse(response).body.txnToken,
           order: orderId,
           mid: mid,
           amount: 100,
         });
       });
     });

     post_req.write(post_data);
     post_req.end();
   });
};

7. Handling the Payment: Displaying Paytm Modal

Once the token is generated, we need to create a makePayment() function that will be triggered when the user clicks on the “Pay Now” button. This function will use the generated token and display the Paytm checkout modal.

const makePayment = () => {
  var config = {
    "root": "",
    "style": {
      "bodyBackgroundColor": "#fafafb",
      "themeBackgroundColor": "#0FB8C9",
      "themeColor": "#ffffff",
      "headerBackgroundColor": "#284055",
      "headerColor": "#ffffff",
    },
    "data": {
      "orderId": paymentData.order,
      "token": paymentData.token,
      "tokenType": "TXN_TOKEN",
      "amount": paymentData.amount,
    },
    "website": "WEBSTAGING",
    "flow": "DEFAULT",
    "merchant": {
      "mid": paymentData.mid,
      "redirect": false
    },
    "handler": {
      "transactionStatus": function(transactionStatus) {
        console.log(transactionStatus);
      },
      "notifyMerchant": function(eventName, data) {
        console.log("Payment closed");
      }
    }
  };

  if (window.Paytm && window.Paytm.CheckoutJS) {
    window.Paytm.CheckoutJS.init(config).then(function () {
      window.Paytm.CheckoutJS.invoke();
    }).catch(function (error) {
      console.log("Error => ", error);
    });
  }
};

8. Triggering Payment on Button Click

Finally, in the App.js file, we will trigger the makePayment() function when the user clicks the “Pay Now” button:

return (
   <div>
     {loading ? (
       <img src="https://c.tenor.com/I6kN-6X7nhAAAAAj/loading-buffering.gif" />
     ) : (
       <button onClick={makePayment}>Pay Now</button>
     )}
   </div>
 );

Import PaytmButton in App.js

Once we’ve set up everything, we can import the PaytmButton component into App.js:

import "./App.css";
import { PaytmButton } from "./paytm-button/paytmButton";

function App() {
 return (
   <div>
     <PaytmButton />
   </div>
 );
}

export default App;

9. Run the Server

Now that the Paytm integration is complete, run your server using the following command:

npm start

Visit http://localhost:3000/ to test the demo app.

Conclusion

I hope this tutorial has helped you understand how to integrate the Paytm payment gateway using ReactJS. Feel free to clone the repository and test the code for yourself. We value your feedback and suggestions, so don’t hesitate to reach out.

SvayambhuTech is dedicated to providing top-notch ReactJS development services, from ideation to final delivery. If you’re looking for ReactJS experts, reach out to us today!