Skip to main content

Cashfree’s integrity standards

Before proceeding with the SDK integration, please ensure that your application complies with Cashfree’s Integrity. Applications that don’t meet the required integrity standards may be restricted from using production services.For further guidance, refer to the Cashfree Integrity.

Setting up SDK

The React Native SDK is hosted on npm. You can get the latest sdk 2.2.5 here.
Our React Native SDK supports Android SDK version 19 and above and iOS minimum deployment target of 10.3 and above.
Navigate to your project and run the following command:
npm install react-native-cashfree-pg-sdk
iOS
Add this to your application’s info.plist file.
<key>LSApplicationQueriesSchemes</key>
<array>
  <string>phonepe</string>
  <string>tez</string>
  <string>paytmmp</string>
  <string>bhim</string>
  <string>amazonpay</string>
  <string>credpay</string>
</array>
cd ios
pod install --repo-update

Step 1: Creating an order

The first step in the integration is to create an Order. You can add an endpoint to your server which creates this order and integrate this server endpoint with your frontend.
Order creation must happen from your backend (as this API uses your secret key). Please do not call this directly from your mobile application.
Here’s a sample request for creating an order using your desired backend language. Cashfree offers backend SDKs to simplify the integration process. You can find the SDKs here.
import { Cashfree, CFEnvironment } from "cashfree-pg";

const cashfree = new Cashfree(
	CFEnvironment.PRODUCTION,
	"{Client ID}",
	"{Client Secret Key}"
);

function createOrder() {
	var request = {
		order_amount: "1",
		order_currency: "INR",
		customer_details: {
			customer_id: "node_sdk_test",
			customer_name: "",
			customer_email: "example@gmail.com",
			customer_phone: "9999999999",
		},
		order_meta: {
			return_url:
				"https://test.cashfree.com/pgappsdemos/return.php?order_id=order_123",
		},
		order_note: "",
	};

	cashfree
		.PGCreateOrder(request)
		.then((response) => {
			var a = response.data;
			console.log(a);
		})
		.catch((error) => {
			console.error("Error setting up order request:", error.response.data);
		});
}
After successfully creating an order, you will receive a unique order_id and payment_session_id that you need for subsequent steps. You can view all the complete api request and response for /orders here.

Step 2: Opening the payment page

Once the order is created, the next step is to open the payment page so the customer can make the payment. The React Native SDK offer below payment flow:
In this flow, SDK provides a webview based checkout implementation to facilitate a quick integration with our payment gateway. Your customers can fill in the necessary details in the web page and complete the payment. This mode also handles all the business logic and UI Components to make the payment smooth and easy to use.
This flow is for merchants who wants to quickly provide UPI Intent functionality using cashfree’s mobile SDK. In this flow, SDK provides a pre-built native Android screen to facilitate a quick integration with our payment gateway. Your customers will see a list of UPI apps installed in their phone which they can select to initiate payment. This mode handles all the business logic and UI Components to make the payment smooth and easy to use. The SDK allows the merchant to customize the UI in terms of color coding, fonts.
To complete the payment, we can follow the following steps:
  1. Create a CFSession object.
  2. Set payment callback.
  3. Initiate the payment

Create a session

This object contains essential information about the order, including the payment session ID (payment_session_id) and order ID (order_id) obtained from Step 1. It also specifies the environment (sandbox or production).
import {
  CFEnvironment,
  CFSession,
} from 'cashfree-pg-api-contract';

try {
      const session = new CFSession(
        'payment_session_id',
        'order_id',
        CFEnvironment.SANDBOX
      );
}
catch (e: any) {
      console.log(e.message);
}

Set payment callback

The SDK exposes an interface CFCallback to receive callbacks from the SDK once the payment flow ends.
onVerify(orderID: string)
onError(error: CFErrorResponse, orderID: string)
Make sure to set the callback at componentDidMount and remove the callback at componentWillUnmount as this also handles the activity restart cases and prevents memory leaks.
Always call setCallback before calling doPayment method of SDK
import {
  CFErrorResponse,
  CFPaymentGatewayService,
} from 'react-native-cashfree-pg-sdk';

export default class App extends Component {
  constructor() {
    super();
  }

  componentDidMount() {
    console.log('MOUNTED');
    CFPaymentGatewayService.setCallback({
      onVerify(orderID: string): void {
        this.changeResponseText('orderId is :' + orderID);
      },
      onError(error: CFErrorResponse, orderID: string): void {
        this.changeResponseText(
          'exception is : ' + JSON.stringify(error) + '\norderId is :' + orderID
        );
      },
    });
  }

  componentWillUnmount() {
    console.log('UNMOUNTED');
    CFPaymentGatewayService.removeCallback();
  }
}

Initiate the payment

This object combines all the configurations into a single checkout configuration. Finally, call doWebPayment() to open the Cashfree checkout screen. This will present the user with the payment options and handle the payment process.
async _startWebCheckout() {
    try {
        const session = new CFSession(
            'payment_session_id',
            'order_Id',
            CFEnvironment.SANDBOX
        );
        console.log('Session', JSON.stringify(session));

        CFPaymentGatewayService.doWebPayment(JSON.stringify(session));

    } catch (e: any) {
        console.log(e.message);
    }
}
This flow is for merchants who wants to quickly provide UPI functionality using cashfree’s mobile SDK without handling other modes like Cards or Net banking.
try {
    // Setting theme is optional
    const theme = new CFThemeBuilder()
        .setNavigationBarBackgroundColor('#E64A19') // ios
        .setNavigationBarTextColor('#FFFFFF') // ios
        .setButtonBackgroundColor('#FFC107') // ios
        .setButtonTextColor('#FFFFFF') // ios
        .setPrimaryTextColor('#212121')
        .setSecondaryTextColor('#757575') // ios
        .build();
        
    const upiPayment = new CFUPIIntentCheckoutPayment(
        session,
        theme
    );
	CFPaymentGatewayService.doUPIPayment(upiPayment);
} catch (e: any) {
    console.log(e.message);
}

Sample Code

import * as React from 'react';
import { Component } from 'react';

import {
 CFErrorResponse,
 CFPaymentGatewayService,
} from 'react-native-cashfree-pg-api';
import {
 CFDropCheckoutPayment,
 CFEnvironment,
 CFPaymentComponentBuilder,
 CFPaymentModes,
 CFSession,
 CFThemeBuilder,
} from 'cashfree-pg-api-contract';

export default class App extends Component {

 constructor() {
   super();
 }

 componentDidMount() {
   console.log('MOUNTED');
   CFPaymentGatewayService.setCallback({
     onVerify(orderID: string): void {
       this.changeResponseText('orderId is :' + orderID);
     },
     onError(error: CFErrorResponse, orderID: string): void {
       this.changeResponseText(
         'exception is : ' + JSON.stringify(error) + '\norderId is :' + orderID
       );
     },
   });
 }

 componentWillUnmount() {
   console.log('UNMOUNTED');
   CFPaymentGatewayService.removeCallback();
 }

 async _startWebCheckout() {
   try {
     const session = new CFSession(
       'payment_session_id',
       'order_Id',
       CFEnvironment.SANDBOX
     );
     console.log('Session', JSON.stringify(session));
     CFPaymentGatewayService.doWebPayment(JSON.stringify(session));
   } catch (e: any) {
     console.log(e.message);
   }
 }
}
import * as React from 'react';
import { Component } from 'react';

import {
  CFErrorResponse,
  CFPaymentGatewayService,
} from 'react-native-cashfree-pg-api';

import {
  CFEnvironment,
  CFPaymentComponentBuilder,
  CFSession,
  CFThemeBuilder,
} from 'cashfree-pg-api-contract';

export default class App extends Component {

  constructor() {
    super();
  }

  componentDidMount() {
    console.log('MOUNTED');
    CFPaymentGatewayService.setCallback({
      onVerify(orderID: string): void {
        this.changeResponseText('orderId is :' + orderID);
      },
      onError(error: CFErrorResponse, orderID: string): void {
        this.changeResponseText(
          'exception is : ' + JSON.stringify(error) + '\norderId is :' + orderID
        );
      },
    });
  }

  componentWillUnmount() {
    console.log('UNMOUNTED');
    CFPaymentGatewayService.removeCallback();
  }

  async _startCheckout() {
    try {
      const session = new CFSession(
        'payment_session_id',
        'order_id',
        CFEnvironment.SANDBOX
      );
      const theme = new CFThemeBuilder()
        .setNavigationBarBackgroundColor('#E64A19')// ios
        .setNavigationBarTextColor('#FFFFFF')// ios
        .setButtonBackgroundColor('#FFC107')// ios
        .setButtonTextColor('#FFFFFF')// ios
        .setPrimaryTextColor('#212121')
        .setSecondaryTextColor('#757575')// ios
        .build();
      const upiPayment = new CFUPIIntentCheckoutPayment(
        session,
        theme
      );
      CFPaymentGatewayService.doUPIPayment(upiPayment);
    } catch (e: any) {
      console.log(e.message);
    }
  }
}
Github Sample Sample UPI Test apk

Step 4: Confirming the payment

Once the payment is completed, you need to confirm whether the payment was successful by checking the order status. After payment user will be redirected back to your component.
You must always verify payment status from your backend. Before delivering the goods or services, please ensure you call check the order status from your backend. Ensure you check the order status from your server endpoint.
export default class App extends Component {
  ...
  componentDidMount() {

    CFPaymentGatewayService.setCallback({
      //verify order status from backend
      onVerify(orderID: string): void {
        this.changeResponseText('orderId is :' + orderID);
      },

      onError(error: CFErrorResponse, orderID: string): void {
        this.changeResponseText(
          'exception is : ' + JSON.stringify(error) + '\norderId is :' + orderID
        );
      },
    });
  }
}
To verify an order you can call our /pg/orders endpoint from your backend. You can also use our SDK to achieve the same.
version := "2023-08-01"
response, httpResponse, err := cashfree.PGFetchOrder(&version, "<order_id>", nil, nil, nil)
if err != nil {
	fmt.Println(err.Error())
} else {
	fmt.Println(httpResponse.StatusCode)
	fmt.Println(response)
}

Testing

You should now have a working checkout button that redirects your customer to Cashfree Checkout.
  1. Click the checkout button.
  2. You’re redirected to the Cashfree Checkout payment page.
If your integration isn’t working:

Error codes

To confirm the error returned in your application, you can view the error codes that are exposed by the SDK.
ERROR CODESMESSAGE
MISSING_CALLBACKThe callback is missing in the request.
ORDER_ID_MISSINGThe “order_id” is missing in the request.
SESSION_OBJECT_MISSINGThe “session” is missing in the request
PAYMENT_OBJECT_MISSINGThe “payment” is missing in the request
ENVIRONMENT_MISSINGThe “environment” is missing in the request.
ORDER_TOKEN_MISSINGThe “order_token” is missing in the request.

Other options

If you are facing trouble while making a payment, you can take a look at the SDK debug logs to try and identify the issue. To enable SDK logging add the following to your values.xml file.<integer name="cashfree_pg_logging_level">3</integer>Following are the Logging levels.
  • VERBOSE = 2
  • DEBUG = 3
  • INFO = 4
  • WARN = 5
  • ERROR = 6
  • ASSERT = 7
If you want to disable quick checkout flow in Drop Payment flow you can add the following to your values.xml file.<bool name="cf_quick_checkout_enabled">false</bool>
From our Reacr SDK version 2.0.1 onwards, you can subscribe to the analytics events generated from our Drop checkout payment flow and push it to the analytics platform of your choice directly from your application.If you want to enable this feature in Drop Payment flow you can add the following line to your values.xml file.<bool name="cashfree_custom_analytics_subscriber_enabled">true</bool>
javascript
CFPaymentGatewayService.setEventSubscriber({
            onReceivedEvent(eventName, map) {
                console.log('Event recieved on screen: ' +
                    eventName +
                    ' map: ' +
                    JSON.stringify(map));
            },
});

componentWillUnmount() {
        CFPaymentGatewayService.removeEventSubscriber();
}
This SDK is compatible with expo framework. Expo Sample

💻 Quick dev-to-dev talk

You clearly care about building better payment experiences for your clients, here’s a quick tip: Earn additional income doing exactly what you’re doing now!Join the Cashfree Affiliate Partner Program and get rewarded every time your clients use Cashfree.What’s in it for you?
  • Earn up to 0.25% commission on every transaction
  • Be more than a dev - be the trusted fintech partner for your clients
  • Get a dedicated partner manager, your go-to expert
What’s in it for your clients?
  • Instant activation, go live in minutes.
  • Industry-best success rate across all payment modes.
  • Effortlessly accept international payments in 140+ currencies
Ready to push to prod? 👉 Become a Partner now