Hi! In this blog, we will see how to integrate paytm payment gateway in React-Native. Mobile wallets have become immensely popular in recent years, and paytm is highly trusted among online customers. Many people use it every day for doing online recharges, DTH & other bill payments. It reduces the risk of exposing customer’s banking credentials and credit card details to hackers. Therefore, Paytm is a good solution for online payments on your Website and Mobile Apps.
Before we begin integrating paytm gateway into our React-Native app, create an account on paytm as a merchant.
Install the following libraries in your React-Native app
npm install paytm_allinone_react-native — save
npx react-native link
In the project level, build.gradle file add the following line in the repositories section
allprojects {
repositories {
... maven {
url "https://artifactory.paytm.in/libs-release-local" }
}
}
Next in the app level build.gradle file add the following dependencies
implementation "com.squareup.okhttp3:okhttp:4.2.1"
implementation "com.squareup.okhttp3:logging-interceptor:4.2.1"
implementation "com.squareup.okhttp3:okhttp-urlconnection:4.2.1"
After all of this is done, some other things need to be done, which are not mentioned in the official documentation of PayTm. First of all, install core node-js module crypto as mentioned in this article in your react native app.
Once the crypto module is installed and React-Native-Randombytes is installed, go to the paytmchecksum folder located inside the node_modules folder. Make the following changes to paytmchecksum.js file.
//import crypto module from root directory
const crypto = require('./../../crypto')
//Import randombytes dependency
import { randomBytes } from 'react-native-randombytes'
Make sure your generateRandomString function located in paytmchecksum.js looks like this:
static generateRandomString(length) {
return new Promise(function (resolve, reject) {
randomBytes((length * 3.0) / 4.0, function (err, buf){ if (!err) {
var salt = buf.toString("base64");
resolve(salt);
}
else {
console.log("error occurred in generateRandomString: " + err);
reject(err); }
});
});
}
Once all these things are done, we can actually start writing code for making payments. We will use the fetch module instead of the HTTPS module to make requests. To make any transaction, we first need to generate a transaction token.
//method to get txn token
import PaytmChecksum from 'paytmchecksum'
const merchantId ="Your merchant Id"
const data = {orderId:"01",txnAmount:"1",customerId:"001"}
export function getTxnToken(data){
var paytmParams = {};
paytmParams.body = {
"requestType" : "Payment",
"mid" : merchantId,
"websiteName" : "WEBSTAGING",
"orderId" : data.orderId+"",
"callbackUrl" : "https://merchant.com/callback",
"txnAmount" : {
"value" : data.txnAmount,
"currency" : "INR",
},
"userInfo" : {
"custId" : data.customerId,
},
//You can enable any other modes if you want
"enablePaymentMode":[
{"mode" : "UPI",channel: ["UPI","UPIPUSH"]}, {"mode":"DEBIT_CARD",channel:["RUPAY"]}
]
};
PaytmChecksum.generateSignature(JSON.stringify(paytmParams.body), "L&qCdepjSHKzEX0l").then(function(checksum){
paytmParams.head = {
"signature" : checksum
};
var post_data = JSON.stringify(paytmParams);
var options = {
/* for Staging */
hostname: 'securegw-stage.paytm.in',
/* for Production */
// hostname: 'securegw.paytm.in',
port: 443,
path: '/theia/api/v1/initiateTransaction?'+ 'mid='+merchantId+'&orderId='+data.orderId+'',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': post_data.length
},
body:post_data
};
fetch('https://securegw-stage.paytm.in/theia/api/v1/initiateTransaction?mid='+merchantId+'='+data.orderId+'',options)
.then((response)=>{
response.json()
.then((txnToken)=>{
//here call the method to start transaction.
startTransaction({orderId:"01",txnToken:txnToken,amount:"1"});
})
.catch((error)=>{
//Handle the error
console.log(error);
})
})
})
}
Once we have the method to generate a transaction token, we can write a method to start a transaction.
import AllInOneSDKManager from 'paytm_allinone_react-native';
const data = {orderId:'01',txnToken:"",amount:"01"}
export function startTransaction(data){
AllInOneSDKManager.startTransaction( data.orderId,merchantId,data.txnToken,data.amount,"https://merchant.com/callback",true,false)
.then((txnDetails)=>{
//txn is successful
//Verify the txnDetails call fetchTxnStatus method
fetchTxnStatus({orderId:"01"})
}).catch((error)=>{
//handle the error
console.log(error);
})
}
Once the transaction is successful, we have to fetch transaction status from paytm servers and then show the payment confirmation message to the user. Here’s how to fetch transaction status.
//function to fetch transaction status of a transaction
export function fetchTxnStatus(data){
var paytmParams = {};
paytmParams.body = {
"mid" : "your merchant Id",
"orderId" : data.orderId+'',
};
PaytmChecksum.generateSignature(JSON.stringify(paytmParams.body), "your_merchant_key").then(function(checksum){
paytmParams.head = {
"signature" : checksum
};
var post_data = JSON.stringify(paytmParams);
var options = {
hostname: 'securegw-stage.paytm.in',
/* for Production */
// hostname: 'securegw.paytm.in',
port: 443,
path: '/v3/order/status',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': post_data.length
},
body:post_data
};
fetch("https://securegw-stage.paytm.in/v3/order/status",options)
.then((response)=>{
response.json().then((txnStatus)=>{
if(txnStatus.body.resultInfo.resultCode=="01"){
//show that the transaction was successful
//You can call a function to confirm the payment
console.log("Transaction Successful");
}else{
//show that there was some problem with transaction
//txnStatus.body.resultInfo.resultCode=="400" means pending
//complete list of responses and their meanings
}
})
.catch((error)=>{
//handle error
console.log(error);
})
})
});
}
That’s all, folks! Now you can start receiving payments.
References
https://developer.paytm.com/docs/all-in-one-sdk/hybrid-apps/react-native/
https://developer.paytm.com/docs/api/initiate-transaction-api/?ref=payments
https://javascript.plainenglish.io/using-core-node-js-modules-in-react-native-apps-e6002a33b6ff
https://developer.paytm.com/docs/api/v3/transaction-status-api/?ref=payments