React Native SDK Version 2.0.0

The Cashfree React SDK is available here.

Integration Steps

To integrate Cashfree SDK with your ReactNative application.

  1. Initiate Payment - Invoke a payment API from the Cashfree SDK with the token generated when the customer initiates payment for an order from your application. Cashfree SDK displays appropriate screens to the customer for the payment.

  2. Receive and handle response - Cashfree SDK returns a response after the payment flow is complete.

  3. Verify response - We recommend you to verify the payment response using webhooks and by checking the signature value returned in the payment response.

Step 1: Create an account with Cashfree and get the API Keys.

  1. Go to Cashfree website and create an account. Click here for detailed steps on how to create and activate your account.

  2. Login to your Merchant Dashboard using the same credentials.

  3. Click Payment Gateway section View Dashboard click Credentials. For security purposes, you need to enter your password for verification

  4. Copy the app ID and the secret key. These values are required to create the order token from your server. Order tokens are used to authenticate the API calls made from Cashfree React Native SDK.

Step 2: Integrate the Cashfree React SDK in your application

To integrate the SDK, follow the steps below:

Step 2a: Add Dependency

cd your-project-folder
npm install react-native-pg-react-native-sdk --save

Click here to know more.

Step 2b: Add permissions (Android)

The Cashfree PG SDK requires that you add the INTERNET permission in your Android Manifest file.

<manifest ...>
<uses-permission android:name="android.permission.INTERNET" />
<application ...>
  • Add android.useAndroidX=true in gradle.properties file.

  • Make sure the gradle build tools version is 4.1.1 or greater and gradle wrapper version is 6.5 or greater.

Step 2c: Set up the SDK (iOS)

Run the command in the terminal.

cd your-project-folder
cd ios && pod install && cd ..

Import the framework using the following steps.

1. Open the ios project in xcode.

2. Open react native project in Finder and go to the path node_modules/react-native-pg-react-native-sdk/ios

3. Drag and drop the CFSDK.xcframework in the xcode project framework section.

4. Select all the build targets and click Finish. (Clear the option Copy items if needed).

5. Open Build Target > General settings.

6. In the framework section click the embed for CFSDK.xcframework and select Embed and Sign.

Step 3: Generate Token (From Backend)

The cftoken is used to authenticate the payment requests made from SDK. It has to be generated for every payment attempt made for an order. Pass this token to the SDK while initiating the payment for that order. To generate a cftoken you need to use our token generation API.

Ensure that this API is called only from your backend as it uses a secret key. This API should never be called from the App.

Request Description

Production - set the URL tohttps://api.cashfree.com/api/v2/cftoken/order

Testing - set the URL to https://test.cashfree.com/api/v2/cftoken/order

You need to send orderId, orderCurrency and orderAmount as a JSON object to the API endpoint and in response, you will receive a token. See the description of the request below.

curl -XPOST -H 'Content-Type: application/json'
-H 'x-client-id: <YOUR_APP_ID>'
-H 'x-client-secret: <YOUR_SECRET_KEY>'
-d '{
"orderId": "<ORDER_ID>",
"orderAmount":<ORDER_AMOUNT>,
"orderCurrency": "<ORDER_CURRENCY>"
}' '<TEST_OR_PROD_API_URL>’'

Request Example: Replace YOUR_APP_ID and YOUR_SECRET_KEY with actual values.

curl -XPOST -H 'Content-Type: application/json' -H 'x-client-id: YOUR_APP_ID' -H 'x-client-secret: YOUR_SECRET_KEY' -d '{
"orderId": "Order0001",
"orderAmount":1,
"orderCurrency":"INR"
}' 'https://test.cashfree.com/api/v2/cftoken/order'

Response Example

{
"status": "OK",
"message": "Token generated",
"cftoken": "v79JCN4MzUIJiOicGbhJCLiQ1VKJiOiAXe0Jye.s79BTM0AjNwUDN1EjOiAHelJCLiIlTJJiOik3YuVmcyV3QyVGZy9mIsEjOiQnb19WbBJXZkJ3biwiIxADMwIXZkJ3TiojIklkclRmcvJye.K3NKICVS5DcEzXm2VQUO_ZagtWMIKKXzYOqPZ4x0r2P_N3-PRu2mowm-8UXoyqAgsG"
}

The "cftoken" is used to authenticate your payment request.

Step 4: Initiate Payment

To initiate payments, your application passes the order info and the cftoken to the SDK. The relevant payment screen is displayed to the customer where they can enter required information and make the payment. React Native SDK verifies the payment after it is complete and sends a response to the application. The application handles the response appropriately.

The order details passed during the token generation and the payment initiation should match. Else, you will get an `Invalid order details` error.

Wrong appId and token will result in `Unable to authenticate merchant` error. The token generated for payment is valid for 5 minutes within which the payment has to be initiated. Else, you will get an `Invalid token` error.

Step 5: Receive and Handle Response

When you invoke the SDK function, it returns a callback as response.

RNPgReactNativeSDK.startPaymentWEB(params,ENV,(result) => {
var obj = JSON.parse(result, function (key, value) {
})});

Step 6: Verify Response

We recommend you to verify the payment response using webhooks. You can also verify the response by checking the signature in the payment response.

Sample Application

Click here to view the sample application.

Web Checkout

Web Checkout is the standard flow for Cashfree React Native SDK. In this flow, the SDK loads a webview which will render the payment page. The customer can fill the required payment details here and complete the payment. The Web Checkout can be used in two ways:-

  1. Web Checkout with Cashfree UI: Customer selects the payment mode and enters the payment details within the Cashfree's web payment page to complete the payment

  2. Seamless Web Checkout: Customer selects the payment mode and enters payment details in your application. These details are then passed on to the Cashfree SDK. Webview is launched only for scenarios like the two-factor authentication.

Web checkout supports payment through Google pay, Amazon pay, PhonePe and UPI payment modes.

For both modes, you need to invoke the startPaymentWEB() method. However, there are a few additional parameters you need to pass for seamless integration.

Use the code below to import the library:import RNPgReactNativeSDK from 'react-native-pg-react-native-sdk'

Web Checkout Using Cashfree UI

Web checkout uses webview to process payment hence the name. For both Web Checkout and Seamless Web Checkout you need to invoke the startPaymentWEB() method. However, there are a few extra parameters you need to pass for seamless integration method.

startPaymentWEB

startPaymentWEB(Map<String, String> inputs,ENV,Callback)

Initiates the payment in a webview. The customer will be taken to the payment page on the Cashfree server where they have the option to pay through any payment option that is activated on their account. Once the payment is done the webview will close and the response will be delivered in the responseData as a callback as JsonString.

Parameters:

  • params: A map of all the relevant parameters described in the Request Params section below.

  • ENV: Environment of the project setup (TEST or PROD)

  • Callback: A callback to receive a response

Seamless Web Checkout

When you have a requirement for a customised payment flow, you can use the seamless integration. You can implement the payment page as per your requirement and then use our SDK to authorise the payment. Once the payment details are collected the OTP or the two-factor authentication page will open in a webview. After the payment is confirmed the webview closes and you will receive a response.

We recommend that you do Web Checkout using Cashfree UI integration unless you are certain that you require a customised payment flow.

The following sections describe the additional parameters for each of the payment methods:

Credit/Debit Card

Add the following parameters to the params map before invoking startPaymentWEB() method to initiate a seamless card transaction.

var map = {
... // required params
"paymentOption": "card",
"card_number": “4434260000000008”, // Replace Card number
"card_expiryMonth": "05", // Card Expiry Month in MM
"card_expiryYear": "2021", // Card Expiry Year in YYYY
"card_holder": "John Doe", // Card Holder name
"card_cvv": "123" // Card CVV
}

Net Banking

Add the following parameters to the params map before invoking startPaymentWEB() method to initiate a seamless net banking transaction. All valid bank codes are available here.

var map = {
... // required params
"paymentOption": "nb",
"paymentCode": "3333" // Put correct bank code here
}

Wallet

Add the following parameters to the params map before invoking startPaymentWEB() method to initiate a seamless wallet transaction. All valid wallet codes are available here.

var map = {
... // required params
"paymentOption": "wallet",
"paymentCode": "4001" // Put correct wallet code here
}

UPI

Add the following parameters to the params map before invoking startPaymentWEB() method to initiate a seamless UPI transaction

var map = {
... // required params
"paymentOption": "upi",
"upi_vpa": "[email protected]" // Put correct upi vpa here
}

Paypal

Add the following parameter to the params map before invoking startPaymentWEB() method to initiate a seamless Paypal transaction.

var map = {
... // required params
"paymentOption": "paypal"
}

Sample Code

var env = “TEST”
var map = {
"orderId": orderId,
"orderAmount": "1",
"appId": apiKey,
"tokenData": cfToken,
"orderCurrency": "INR",
"orderNote": "asdasdasd",
"notifyUrl": "https://test.gocashfree.com/notify",
"customerName": "Cashfree User",
"verifyExpiry": "100",
"customerPhone": "9999999999",
"customerEmail": "[email protected]"
}
RNPgReactNativeSDK.startPaymentWEB(map, env, (result) =>
{
console.log(result);
var obj = JSON.parse(result, function (key, value)
{
console.log(key + "::" + value);
// Do something with the result
})
});

UPI Intent

When the startPaymentUPI method is invoked the customer is shown a list of all the installed UPI applications on their phone. After the customer selects their preferred application, the payment confirmation page will open in the application. After payment completion, the response is delivered through a callback as JsonString.

Steps to integrate to accept payments through UPI:

1. Use the code below to import library:

import RNPgReactNativeSDK from 'react-native-pg-react-native-sdk'

2. Open the iOS application using XCode or any text editor and add the following code to info.plist file.

<key>LSApplicationCategoryType</key>
<string></string>
<key>LSApplicationQueriesSchemes</key>
<array>
<string>phonepe</string>
<string>tez</string>
<string>paytm</string>
</array>

3. Use the following method to initiate a UPI payment.

startPaymentUPI (params, ENV, Callback)

  • Params: A map of all the relevant parameters described in the Request Parameters section.

  • ENV: Environment of the project setup (TEST or PROD)

  • Callback: A callback to receive a response.

Create a new order ID every time you invoke the UPI payment flow since UPI intent flow can be initiated once per order ID.

Sample Code

Var env = “TEST”
var map = {
"orderId": orderId,
"orderAmount": "1",
"appId": apiKey,
"tokenData": cfToken,
"orderCurrency": "INR",
"orderNote": "asdasdasd",
"notifyUrl": "https://test.gocashfree.com/notify",
"customerName": "Cashfree User",
"verifyExpiry": "100",
"customerPhone": "9999999999",
"customerEmail": "[email protected]"
}
RNPgReactNativeSDK.startPaymentUPI(map, env, (result) =>
{
console.log(result);
var obj = JSON.parse(result, function (key, value)
{
console.log(key + "::" + value);
// Do something with the result
})
});

Verify Response

It is recommended to verify the payment response from the SDK using one of the following methods.

Webhook Notifications

We send a notification from Cashfree backend to your backend whenever a payment is successful for an order. This is useful for users in cases when the internet connection is not stable after payment. This will allow you to reconcile all the successful orders at your end. The notification will be sent to notifyUrl which is specified during order creation. The parameters sent in the notification are described here.

To specify notifyUrl, add it with other parameters (orderId, orderAmount etc.) as shown below:

var map = {
... // required params
"notifyUrl": "https://example.com/path/to/notify/url/"
}

Notifications are usually instant but rarely can take a minute to hit your server. Make sure that your url supports https. Notifications are sent only in the case of successful payments. Sometimes you may receive the same notification two or more times. It is recommended to ensure that your implementation of the webhook is idempotent. Ensure that you verify the signature in the webhook response.

Verify Signature

Verify the signature value in the payment response to check the authenticity of the transaction response. In every response, we add a digital signature to establish the authenticity of the message. We require you to verify the received signature at your end. This will verify if the response has tampered. This verification has to be done on your server as it involves secretKey which should not be exposed on the client-side.

PHP
PYTHON
JAVA
CSHARP
PHP
<?php
$orderId = $_POST["orderId"];
$orderAmount = $_POST["orderAmount"];
$referenceId = $_POST["referenceId"];
$txStatus = $_POST["txStatus"];
$paymentMode = $_POST["paymentMode"];
$txMsg = $_POST["txMsg"];
$txTime = $_POST["txTime"];
$signature = $_POST["signature"];
$data = $orderId.$orderAmount.$referenceId.$txStatus.$paymentMode.$txMsg.$txTime;
$hash_hmac = hash_hmac('sha256', $data, $secretkey, true) ;
$computedSignature = base64_encode($hash_hmac);
if ($signature == $computedSignature) {
// Proceed
} else {
// Reject this call
}
?>
PYTHON
import hashlib
import hmac
import base64
@app.route('/notify_url/', methods=["POST"])
def notify_url_process():
postData = {
"orderId" : request.form['orderId'],
"orderAmount" : request.form['orderAmount'],
"referenceId" : request.form['referenceId'],
"txStatus" : request.form['txStatus'],
"paymentMode" : request.form['paymentMode'],
"txMsg" : request.form['txMsg'],
"txTime" : request.form['txTime'],
}
signatureData = postData["orderId"] + postData["orderAmount"] + postData["referenceId"] + postData["txStatus"] + postData["paymentMode"] + postData["txMsg"] + postData["txTime"]
message = bytes(signatureData).encode('utf-8')
#get secret key from your config
secret = bytes(secretKey).encode('utf-8')
signature = base64.b64encode(hmac.new(secret,
message,digestmod=hashlib.sha256).digest())
JAVA
LinkedHashMap<String, String> postData = new LinkedHashMap<String, String>();
postData.put("orderId", ORDERID);
postData.put("orderAmount", ORDERAMOUNT);
postData.put("referenceId", REFERENCE_ID);
postData.put("txStatus", TXN_STATUS);
postData.put("paymentMode", PAYMENT_MODE);
postData.put("txMsg", TX_MSG);
postData.put("txTime", TX_TIME);
String data = "";
Set<String> keys = postData.keySet();
for (String key : keys) {
data = data + postData.get(key);
}
String secretKey = "" // Get secret key from config;
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key_spec = new
SecretKeySpec(secretKey.getBytes(),"HmacSHA256");
sha256_HMAC.init(secret_key_spec);
String signature = Base64.getEncoder().encodeToString(sha256_HMAC.doFinal(data.getBytes()));
CSHARP
using System;
using System.Security.Cryptography;
using System.Collections.Generic;
namespace Rextester {
public class Program {
private string CreateToken(string message, string secret){
secret = secret ?? "";
var encoding = new System.Text.ASCIIEncoding();
byte[] keyByte = encoding.GetBytes(secret);
byte[] messageBytes = encoding.GetBytes(message);
using (var hmacsha256 = new HMACSHA256(keyByte))
{
byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
return Convert.ToBase64String(hashmessage);
}
}
public static void Main(string[] args) {
string secret = "<your_secret_key>";
string data = "";
data = data + "FEX101";
data = data + "10.00";
data = data + "19992";
data = data + "SUCCESS";
data = data + "pg";
data = data + "payment done";
data = data + "2018-02-02 17:29:12";
Program n = new Program();
string signature = n.CreateToken(data, secret);
Console.WriteLine(signature);
}
}
}

Request and Response Parameters

Request Parameters

Parameter

Required

Description

appId

Yes

Your app id

orderId

Yes

Order/Invoice Id

orderAmount

Yes

Bill amount of the order

orderNote

No

A help text to make customers know more about the order

orderCurrency

Yes

Currency code of the order. Default is INR.

customerName

No

Name of the customer

customerPhone

Yes

Phone number of customer

customerEmail

Yes

Email id of the customer

tokenData

Yes

Token generated from step 4

notifyUrl

No

Notification URL for server-server communication. Useful when a user's connection drops after completing payment.

paymentModes

No

Allowed payment modes for this order. Available values: cc, dc, nb, paypal, upi, wallet. Leave it blank if you want to display all modes.

Response parameters

These parameters are sent as extras to response callback. They contain the details of the transaction.

Parameter

Description

orderId

Order id for which transaction has been processed. Ex: GZ-212

orderAmount

Amount of the order. Ex: 256.00

paymentMode

Payment mode of the transaction.

referenceId

Cashfree generated unique transaction Id. Ex: 140388038803

txStatus

Payment status for that order. Values can be: SUCCESS, FLAGGED, PENDING, FAILED, CANCELLED.

paymentMode

Payment mode used by customers to make the payment. Ex: DEBIT_CARD, MobiKwik, etc

txMsg

Message related to the transaction. Will have the reason, if payment failed

txTime

Time of the transaction

type

Fixed value : CashFreeResponse. To identify the response is from Cashfree SDK.

signature

Response signature, more here.

  • There can be scenarios where the SDK is not able to verify the payment within a short period of time. The status of such orders will be PENDING.

  • If the Webview closes immediately after it is opened then it could be because of some issues with the input that is passed to the SDK. Check the inputs passed and if you still need further help reach out to us at [email protected].

  • If you are getting INCOMPLETE as the transaction status please reach out to your account manager or [email protected] To know more about the transaction statuses, click here.

Checklist

Checklist to Go Live

  • Ensure you are triggering https://api.cashfree.com/api/v2/cftoken/orderendpoint for generating token.

  • Pass the Production appId/secretKey in the x-client-id and x-client-secret of the token request API. Obtain these appId/secretKey here in the Production section.

  • When calling startPaymentWEB() ensure that the stage parameter is PROD.

  • When calling startPaymentWEB() the params map is sent to your appId. Ensure it is the correct production appId.

Checklist to Test the Integration

  • Ensure you are triggering https://test.cashfree.com/api/v2/cftoken/orderendpoint for generating Token.

  • Pass the Test appId/secretKey in the x-client-id and x-client-secret of the token request API. Get the appId/secretKey here in the Sandbox section.

  • When calling startPaymentWEB() ensure that the stage parameter is TEST.

  • When calling startPaymentWEB() the params map is sent to your appId. Ensure it is the correct test appId.

FAQs

1. How do I upgrade the gradle version?

  1. Go to the react native project folder in your computer.

  2. Open android/build.gradle file. Change classpath("com.android.tools.build:gradle:x.y.z") to classpath("com.android.tools.build:gradle:4.1.1") or higher.

  3. Open android/gradle/wrapper/gradle-wrapper.properties. Change "distributionUrl=https://services.gradle.org/distributions/gradle-a.b-all.zip" to "distributionUrl=https://services.gradle.org/distributions/gradle-6.5-all.zip" or higher.

  4. Build the android project.

2. iOS application is not building after npm dependency upgrade. How do I resolve it?

  1. Remove the CFSDK.xcframework from iOS project (without deleting the file).

  2. Follow the integration steps available here.

3. Build Error is displayed in android. How do I resolve it?

Execution failed for task ':app:mergeDebugAssets'. - Could not resolve all files for configuration ':app:debugRuntimeClasspath'. > - Could not find any matches for com.cashfree.pg:android-sdk:1.6.+ as no versions of com.cashfree.pg:android-sdk are available.”

If you see the above error,

  1. Go to the React Native project folder.

  2. Open android/build.gradle file, and add maven { url 'https://maven.cashfree.com/release' } in allprojects > repositories.

allprojects {
repositories {
....
maven { url 'https://maven.cashfree.com/release' }
}
}