React Native Payment Gateway - Razorpay
Tags: reactnative, android, ios, javascript
Published: 2023-06-25 19:02:53

# <u>**[React Native Razorpay](https://razorpay.com/docs/payments/payment-gateway/react-native-integration/standard/)**</u>

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](https://easy.razorpay.com/onboarding?source=website).

> 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xfi6vabg9xzfqiixn008.png)

2) [Generate API Keys](https://razorpay.com/docs/api/authentication/#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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iar5no5wnprthd9uba8o.png)

> 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e57sl10i9x1zkkv0l96q.png)

3) Know about the [Razorpay Payment Flow](https://razorpay.com/docs/payments/payment-gateway/how-it-works/).

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/816gdd3hqr0pqi44phgc.jpg)

---

## Install Razorpay React Native SDK

```
//using npm
npm install react-native-razorpay --save && cd ios && pod install
```

```
// using yarn
yarn add react-native-razorpay && cd ios && pod install
```


## Code

The Razorpay has integrated the checkout function for react-native, which means it will lead to the calling of [payment API](https://razorpay.com/docs/api/payments/#payment-entity), what this does is accepts payment from any user directly transferring the money without any details. 
With [orders API](https://razorpay.com/docs/api/orders/#order-entity), 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;
  })
```

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',
  },
});
```


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/in5g7lt47fw1hmt72lwr.jpg)

[Test Card Details](https://razorpay.com/docs/payments/payments/test-card-details?search-string=card%20de)

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