RazorPay integration with Node.js

Shraddha Paghdar
JavaScript in Plain English
3 min readApr 11, 2021

--

Razorpay is a popular payment gateway in India used in e-commerce websites or any paid service. With few steps, you can start collecting money from your customers using this service.

Today’s post will cover account creation on Razorpay & integration with the node.js application.

Razorpay payment flow
Order creation to Payment received via webhook flow

Step 1. RazorPay Account Setup

Go to https://dashboard.razorpay.com/signup and enter your email address & necessary information.

Dashboard of RazorPay

By default, it creates a test environment for you to play around with all the options. You can activate your account by filling in the KYC form in the “My Account -> Profile ->Account Activation” section.

Now go to “Settings -> API keys” to generate API keys for node connection. Download the keys & store them somewhere safe.

API key generation

Step 2. Node.js setup

Install the Razorpay package using npm.

npm i --save razorpay

Now let’s create the index.js file and Instantiate the Razorpay instance with key_id & key_secret we downloaded as API keys.

const rzp = new Razorpay({
key_id: "YOUR_KEY_ID",
key_secret: "YOUR_KEY_SECRET",
})

Create the order and send the order id back for checkout.

const rzpOrder = await rzp.orders.create({
amount: amount * 100, // rzp format with paise
currency: 'INR',
receipt: "receipt#1" //Receipt no that corresponds to this Order,
payment_capture: true,
notes: {
orderType: "Pre"
} //Key-value pair used to store additional information
})
// To create recurring subscription
const subscriptionObject = {
plan_id: PLAN_ID,
total_count: 60,
quantity: 1,
customer_notify: 1,
notes,
}
const subscription = await rzp.subscriptions.create(subscriptionObject)

Pass the order Id to generate checkout object

<button id=”rzp-button1">Pay</button>
<script src=”https://checkout.razorpay.com/v1/checkout.js"></script> <script>
var options =
{
“key”: “YOUR_KEY_ID”, // Enter the Key ID generated from the Dashboard
"name": "Test Company",
"order_id": "rzpOrder.id", // For one time payment
"subscription_id" : "subscription.id" // For recurring subscription
"prefill": {
"name": "Test User",
"email": "test.user@example.com",
"contact": "9999999999"
},
"theme": {
"color": "#3399cc"
},
// This handler function will handle the success payment
"handler": function (response) {
alert(response.razorpay_payment_id);
alert("Payment Successfull")
},
};
var rzp1 = new Razorpay(options);document.getElementById('rzp-button1').onclick = function (e) {
rzp1.open();
e.preventDefault();
}
rzp1.on('payment.failed', function (response)
{
alert(response.error.code);
alert(response.error.description);
alert(response.error.source);
alert(response.error.step);
alert(response.error.reason);
alert(response.error.metadata.order_id);
alert(response.error.metadata.payment_id);
}
</script

If everything is correct, the user will be redirected to the Razorpay checkout page.

You can capture the payment automatically or using the capture method. Webhooks allows you to get the response back from the Razorpay server.

You can subscribe to a certain event from the Razorpay webhook, and store the data in your DB.

You can set up webhooks from your Dashboard for live mode and test mode separately.

Webhook setup

Now you have to verify the webhook event sent by Razorpay for authenticity.

const requestedBody = JSON.stringify(req.body)const receivedSignature = req.headers['x-razorpay-signature']const expectedSignature = crypto.createHmac('sha256', RAZORPAY_WEBHOOK_SECRET).update(requestedBody).digest('hex')if (receivedSignature === expectedSignature) { 
// Store in your DB
} else {
res.status(501).send('received but unverified resp')
}

Conclusion

And that’s it. You are all ready to start your online payment business. For more info please visit the official documentation of RazorPay integration.

Thanks for reading. Originally published at https://noob2geek.in on 12 April 2021.

More content at plainenglish.io

--

--

Javascript Full-stack developer with a passion for building highly scalable and performant apps.