DEV Community

Ajmal Hasan
Ajmal Hasan

Posted on

React Native Payment Gateway - Razorpay

React Native Razorpay

It is a library or package that allows developers to integrate the Razorpay payment gateway into their React Native applications. Razorpay is a popular payment gateway in India that enables businesses to accept online payments via various methods such as credit cards, debit cards, net banking, UPI, and digital wallets.


Prerequisites

1) Create a Razorpay Account.

Note:
For Live Mode - Complete KYC, Pan Detail, Phone number, Email, Bank Details and Application requirements like app/web link etc. will be asked. For Test Mode some of above mentioned can be ignored. We will be working on Test Mode.

After registration Dashboard will appear:

Image description

2) Generate API Keys in Test Mode. To go live with the integration and start accepting real payments, generate Live Mode API Keys and replace them in the integration.

Generate Api Key:

Image description

The secret key will be displayed only once and you won’t be able to find it again, so make a copy of it now. The Test API Key and the Secret key must be kept safe.

Image description

3) Know about the Razorpay Payment Flow.

Image description


Install Razorpay React Native SDK

//using npm
npm install react-native-razorpay --save && cd ios && pod install
Enter fullscreen mode Exit fullscreen mode
// using yarn
yarn add react-native-razorpay && cd ios && pod install
Enter fullscreen mode Exit fullscreen mode

Code

The Razorpay has integrated the checkout function for react-native, which means it will lead to the calling of payment API, what this does is accepts payment from any user directly transferring the money without any details.
With orders API, Razorpay enables you to create Orders that can be linked to payments. That means so that whatever payment arrives in your wallet is described with what has the payment related to. For example, suppose you have to show a product you wish to sell.

So first, you will have to create an order by calling orders API on your server-side, i.e. Node.JS or something else with request parameters like the amount, self-generated receipt number, and optional notes on who the user is. then after receiving the order_id, you will pass onto the mobile application and start the checkout functionality provided by react-native-razorpay.

Here is the example using react-native-razorpay.

On server-side - node.js:

const Razorpay = require("razorpay");
//...

let rzp = new Razorpay({
  key_id: "", // your `KEY_ID`
  key_secret: "" // your `KEY_SECRET`
});

//Inside Create Order Function

rzp.orders
  .create({
    amount: price * 100,
    currency: "INR",
    receipt: "", // Add receipt string
    payment_capture: 1, // auto capture payment config
    notes: { username, planId: id }
    // custom notes, you can use this in received response as key-value pair
  })
  .then(data => { // created order response
    let sendToApplicationResponse = { // Creating the response send to mobile app
      username,
      orderId: data.id,
      receipt: data.receipt
    };
    return sendToApplicationResponse;
  })
Enter fullscreen mode Exit fullscreen mode

On react-native application-side:

import {Button, Image, StyleSheet, Text, View} from 'react-native';
import React from 'react';
import RazorpayCheckout from 'react-native-razorpay';
import {RAZORPAY_KEY} from './constants';

const imgURL =
  'https://m.media-amazon.com/images/I/61L5QgPvgqL._AC_UF1000,1000_QL80_.jpg';

const App = () => {
  const onPressBuy = () => {
    //Order Api: Call POST api with body like (username, id, price etc) to create an Order and use order_id in below options object
    // const response = await .....

    let options = {
      description: 'Credits towards consultation',
      image: imgURL, //require('../../images.png')
      currency: 'INR', //In USD - only card option will exist rest(like wallet, UPI, EMI etc) will hide
      key: RAZORPAY_KEY,
      amount: '5000',
      name: 'Acme Corp',
      order_id: '', //Replace this with an order_id(response.data.orderId) created using Orders API.
      prefill: {
        email: 'hasan@example.com',
        contact: '9191919191',
        name: 'Hasan',
      }, //if prefill is not provided then on razorpay screen it has to be manually entered.
      theme: {color: '#53a20e'},
    };
    RazorpayCheckout.open(options)
      .then(data => {
        // handle success
        alert(`Success: ${data.razorpay_payment_id}`);
      })
      .catch(error => {
        // handle failure
        alert(`Error: ${error.code} | ${error.description}`);
      });
  };
  return (
    <View style={styles.container}>
      <Image
        source={{
          uri: imgURL,
        }}
        style={{width: 200, height: 100}}
        resizeMode="contain"
      />
      <Text>PRICE: 125000/-</Text>
      <Button title="Buy" color={'darkblue'} onPress={onPressBuy} />
    </View>
  );
};

export default App;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'lightblue',
    justifyContent: 'center',
    alignItems: 'center',
  },
});
Enter fullscreen mode Exit fullscreen mode

Image description

Test Card Details

Based on the success/failure response, further functionality can be implemented.

Top comments (0)