React Native SDK

Use our library to integrate the Cashfree Payment Gateway directly into your app using Cashfree SDK for React Native. Cashfree SDK has been designed to offload the complexity of handling and integrating payments in your app.

The Cashfree SDK is available as an npm package. Instructions on importing the package is also provided.

https://www.npmjs.com/package/cashfreereactnativepg

We provide two types of integration with the reactNativeSDK

  1. Checkout - Customer does payment in Cashfree’s web payment page inside a Webview in your app.

  2. Seamless Pro - Customer does payment in your App directly and the request is sent to cashfree backend. A Webview is launched for the Two-factor/Authorization process.

Library Version

Due to breaking changes in React Native 0.6 we have two versions of our plugin.

React Native Version

Cashfree Plugin Version

>= 0.6

3.x.x

< 0.6

2.x.x

See all the available versions below: https://www.npmjs.com/package/cashfreereactnativepg

Step 1: Setup

cd /path-to-project-directory

npm install cashfreereactnativepg

Step 2: Generate token

You will need to generate a token and pass it to SDK while initiating payments for security reasons. For generating token you need to use our token generation API. Please ensure that this API is called only from your backend as it uses secretKey which should never be sent to frontend.

For production/live usage set the endpoint will be: https://api.cashfree.com/api/v2/cftoken/order

For testing the endpoint will be: 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 a token will received.

Request Description

For production/live usage set the endpoint will be: https://api.cashfree.com/api/v2/cftoken/order

For testing the endpoint will be: https://test.cashfree.com/api/v2/cftoken/order

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

Request Example

curl -XPOST -H 'Content-Type: application/json' -H 'x-client-id: 275432e3853bd165afbf5272' -H 'x-client-secret: 2279c0ffb9550ad0f9e0652741c8d06a49409517' -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” attribute is the token that needs to be used to secure your request.

Checkout

Add the component.

import { CashfreePG } from 'cashfreereactnativepg';

render() {
return (
<View style=>
<CashfreePG
appId="YOUR_APP_ID"
orderId="YOUR_ORDER_ID"
orderAmount = "100"
orderCurrency = "INR"
orderNote = "This is an order note"
source = "reactsdk"
customerName = "John"
customerEmail = "abc@email.com"
customerPhone = "1234561234"
notifyUrl = "YOUR_NOTIFY_URL"
paymentModes = ""
env = "test" //blank for prod
tokenData = "TOKENDATA"
callback = {(eventData)=>{
/*
callback function that will be executed once the transaction has been completed
*/
}}
/>
</View>
);
}

The value for parameter source MUST be "reactsdk".

Seamless

In seamless payment flow, the customer enters all details on merchant's checkout view itself (Cashfree is whitelabled in this scenario). To use seamless, import the component as before. The integration steps for Seamless mode are almost same as the Checkout flow except the input params passed will have extra parameters according to the payment mode selected.

Card

For card payment pass the following parameters:

{
card_number= "4111111111111111"
card_holder= "Test"
card_cvv= "123"
card_expiryMonth="07"
card_expiryYear="2023"
paymentOption="card"
//pass the below parameter to save card details in the vault
card_save=1
}

Saved Card

For using cards saved in the vault pass the following parameters:

{
card_id= //card_id
card_cvv= "123"
paymentOption="savedCard"
}

Net Banking

For net banking pass the following parameters:

{
paymentOption="nb"
paymentCode=//bank code
}

You can get a list of bank codes here.

Wallets

For wallets pass the following parameters:

{
paymentOption="wallet"
paymentCode=//wallet code
}

You can get a list of wallet codes here.

UPI

For UPI pass the following parameters:

{
paymentOption="upi"
upi_vpa=//VPA of client
upiMode=//to be used for google pay only, upiMode has to be gpay
}

Request Parameters

Parameter

Required

Description

appId

Yes

Your app id

orderId

Yes

Order/Invoice Id

orderAmount

Yes

Bill amount of the order

orderCurrency

No

Currency for the order. INR if left empty. See the Currency Codes list. Contact care@gocashfree.com to enable new currencies.

orderNote

No

A help text to make customers know more about the order

customerName

Yes

Name of the customer

customerPhone

Yes

Phone number of customer

customerEmail

Yes

Email id of the customer

notifyUrl

No

Notification URL for server-server communication. Useful when user’s connection drops while.

paymentModes

No

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

Response Parameters

These parameters are returned to the function you implement, contains a stringified obj with the details of the transaction. Always verify the signature in the response as described in the response verification section.

Parameter

Description

orderId

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

orderAmount

Amount of the order. Ex: 256.00

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 customer 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

signature

signature generated to verify the authenticity of the transaction as explained here.

Webhook Notification

Do not go live without integrating webhook notification.

We send a notification from our backend to your backend whenever an order payment is processed successfully to your notifyUrl. This is useful in cases such as when the user internet connection breaks after payment. This will allow you to reconcile all the successful orders on your end. The notification will be sent to notifyUrl which is specified at order creation. The parameters sent in notification are described here.

To specify notifyUrl just add it alongside other parameters (orderId, orderAmount etc.).

Please make a note of the following:

  • Notification can take upto one minute to hit your server after payment.

  • Notifications are sent only in the case of successful payments. Failed or pending payments wont lead to a notification being sent.

  • There might be cases where we send the same notification two or more times. It is recommended to rely on the first notification for reconciliation and silently ignore any subsequent notifications.

  • Don't forget to verify the incoming signature on the webhook as described in the response verification section.

Response Verification

Verify the response signature to check the authenticity of transaction response. Do not go live without signature verification.

In every response we add a digital signature to establish the authenticity of the message. We require you to verify this received signature at your end. This will verify if the response has not been tampered with.

This verification has to be done on your backend server as it will involve secretKey which should never be exposed on the clientside. Please use the appropriate code example from below depending on your backend language.

CURL
PYTHON
JAVA
CSHARP
CURL
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())
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);
}
}
}

Running your App

The CashFree SDK has been tested with React Native version 0.56.0

Test Credentials

Please find test data here.

Example Project

You can test Cashfree SDK for React Native by cloning the example react native project from its Github repo link.