Seamless Transactions: Mastering Paytm Integration with Typescript and React


Integrating online payment gateways into web applications has become a crucial aspect of modern web development. One of the popular payment gateways in India is Paytm, which offers a seamless and secure payment experience for customers. In this blog post, we'll walk through the steps to integrate Paytm into your web application using JavaScript.







Step 1: Sign Up for Paytm Merchant Account


Before you can start integrating Paytm into your application, you'll need to sign up for a Paytm merchant account. Visit the Paytm website, navigate to the "Merchant Sign Up" section, and follow the instructions to create your account. During the sign-up process, you'll be asked to provide your business details, KYC documents, and other necessary information.

Step 2: Obtain Paytm Merchant Keys


Once your Paytm merchant account is approved, you'll receive your merchant keys, which include the Merchant ID, Merchant Key, and Website. These keys are crucial for authenticating your payment requests and ensuring secure transactions.

Step 3: Set Up the Payment Environment


Paytm provides two environments for integration: the Test environment and the Production environment. We recommend starting with the Test environment to ensure everything is working correctly before moving to the Production environment.

Step 4: Create the Payment Request


To initiate a payment request, you'll need to create a JavaScript object containing the necessary parameters, such as the order amount, customer details, and callback URLs. Here's an example:






const initialize = () => {

  let orderId = "YOUR_ORDER_ID";

  // Credentials
  let mid = "YOUR_Merchant_ID"; // Merchant ID
  let mkey = "YOUR_Merhcant_Key"; // Merhcant Key
  var paytmParams = {
      body: {},
      head: {},
  };

  paytmParams.body = {
      requestType: "Payment",
      mid: mid,
      websiteName: "YOUR_WEBSITE_NAME",
      orderId: orderId,
      callbackUrl: "CALLBACK_URL",
      txnAmount: {
          value: "TXN_AMOUNT",
          currency: "INR",
      },
      userInfo: {
          custId: "CUSTOMER_ID",
      },
  };

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

      var post_data = JSON.stringify(paytmParams);

      var 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,
          },
      };

      var response = "";
      var post_req = https.request(options, function(post_res: any) {
          post_res.on("data", function(chunk: any) {
              response += chunk;
          });
          post_res.on("end", function() {
              // res.json({data: JSON.parse(response), orderId: orderId, mid: mid, amount: amount});
              makePayment(
                  orderId,
                  JSON.parse(response).body.txnToken,
                  TXN_AMOUNT
              );
          });
      });

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


To ensure the integrity of the payment request, Paytm requires a checksum value to be generated and included in the request. You can generate the checksum using the provided JavaScript SDK or by making a server-side request to Paytm's checksum generation endpoint.


Step 6: Make Payment






const makePayment = (orderId: any, token: any, amount: any) => {
  setLoading(true);
  var config = {
      root: "",
      style: {
          bodyBackgroundColor: "#fafafb",
          bodyColor: "",
          themeBackgroundColor: "#0FB8C9",
          themeColor: "#ffffff",
          headerBackgroundColor: "#284055",
          headerColor: "#ffffff",
          errorColor: "",
          successColor: "",
          card: {
              padding: "",
              backgroundColor: "",
          },
      },
      data: {
          orderId: orderId,
          token: token,
          tokenType: "TXN_TOKEN",
          amount: amount /* update amount */ ,
      },
      payMode: {
          labels: {},
          filter: {
              exclude: [],
          },
          order: ["CC", "DC", "NB", "UPI", "PPBL", "PPI", "BALANCE"],
      },
      website: "YOUR_WEBSITE_NAME",
      flow: "DEFAULT",
      merchant: {
          mid: "YOUR_Merchant_ID",
          redirect: false,
      },
      handler: {
          transactionStatus: async function transactionStatus(
              paymentStatus: any
          ) {
              if (paymentStatus.STATUS === "TXN_SUCCESS") {
                  //Payment Success
              } else {
                  //Payment Failed
              }

              setLoading(false);
          },
          notifyMerchant: function notifyMerchant(eventName: any, data: any) {

          },
      },
  };

  if (window.Paytm && window.Paytm.CheckoutJS) {
      // initialze configuration using init method
      window.Paytm.CheckoutJS.init(config)
          .then(function onSuccess() {
              // after successfully update configuration invoke checkoutjs
              window.Paytm.CheckoutJS.invoke();
          })
          .catch(function onError(error: any) {
              console.log("Error => ", error);
          });
  }
};




After the user completes the payment process, Paytm will send a response back to your application's callback URL. You'll need to handle this response, verify the transaction details, and update your application's order status accordingly.


Once you've thoroughly tested your integration in the Test environment and ensured everything is working correctly, you can switch to the Production environment by updating the environment parameter in your payment object.


Conclusion


Integrating Paytm into your web application using JavaScript can seem daunting at first, but by following these steps, you can streamline the process and provide a seamless payment experience for your customers. Remember to thoroughly test your integration, handle errors gracefully, and always prioritize security when dealing with sensitive payment data.

Happy Coding 😐


Previous Post Next Post

Contact Form