Payments simplified with Razorpay & React Native
It’s a developer’s nightmare when it comes to processing payments. Nothing different with me. But let’s bust that myth.
I was stunned at the simplicity level of integrating Razorpay SDK that I couldn’t resist writing an article about it.
Let’s get started.
The following content is a more simplified version of the already simplified article in Razorpay Docs.
NOTE: Activate your Razorpay account before moving ahead.
Step 1: Install Razorpay React Native SDK
$ npm install react-native-razorpay — save
If you’re using RN version ≥ 0.60, feel free to skip to step 2
Import Razorpay Package in MainApplication.java
import com.razorpay.rn.RazorpayPackage;
…
List<ReactPackage> packages = new PackageList(this).getPackages();
// Packages that cannot be autolinked yet can be added manually here, for example:
packages.add(new RazorpayPackage());
…
Add Razorpay SDK in Settings Gradle File
include ‘:react-native-razorpay’
project(‘:react-native-razorpay’).projectDir = new File(rootProject.projectDir, ‘../node_modules/react-native-razorpay/android’)
Add Dependency in App Build Gradle File
implementation project(‘:react-native-razorpay’)
Run your app
npx react-native run-android
Once the app build’s just fine, proceed.
Step 2: Installing other npm packages
npm i axios
npm i buffer
Step 3: Creating an order
Import the required packages.
import axios from ‘axios’;
import { Buffer } from ‘buffer’
Then on your onPress execute the below code. Use the test key & password generated in your Razorpay Dashboard.
const token = Buffer.from(`${razorpay_key}:${razorpay_passowrd}`, ‘utf8’).toString(‘base64’)
axios.post(‘https://api.razorpay.com/v1/orders',
{ “amount”: 100, //Min Rs. 1 in paise
“currency”: “INR” },
{ headers: {
‘content-type’: ‘application/json’,
‘Authorization’: `Basic ${token}`}})
.then(response => {
console.log(response)
this.razorpayCheckout(response.id)})
.catch(error => {
console.log(error)});;
Step 4: Razorpay Checkout
Create a function razorpayCheckout and execute it when the orders API returns a success callback.
razorpayCheckout = (order_id) => {
const { total, userData, diesalQt, petrolQt } = this.state
var options = {
currency: ‘INR’,
key: razorpay_key,
amount: 100,
name: ‘My Brand Name’,
order_id: order_id,
theme: { color: ‘#2e1c2e’ }
}
RazorpayCheckout.open(options)
.then((data) => {
console.log(data)})
.catch((error) => {
alert(`Sorry! Your transaction has failed please try again. Reason ${error.description}`);
console.log(error)});}
Well, that’s pretty much it. Lastly, you’ll need to make provisions on your server to validate the signature returned by Razorpay.
That’s a story for another day.
Cheers ✌️