RazorPay integration with Node.js
RazorPay integration with Node.js

RazorPay integration with Node.js

Spread the love

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 & its integration with the Node.js application.

Razorpay payment flow
Razorpay payment flow
Rasorpay integration with Node.js | Order creation 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.

RazorPay Dashboard
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.

Razorpay API key generation
API key generation

Step 2. Node.js setup & Razorpay Integration

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")
   },
};
const 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.

Razorpay Webhook setup
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. To learn how to connect international payment gateway Stripe read here. To learn more about Razorpay API mocking click here.

13 Comments

  1. birgitsimmons

    Hello there, just became aware of your blog through Google, and found that it is really informative.

    I will appreciate it if you continue this in the future.
    Lots of people will be benefited from your writing. Cheers!

  2. lillian

    I like the helpful information you supply to your articles.
    I’ll bookmark your weblog and check once more right here frequently.

    I’m rather certain I will learn many new stuff right right here!

    Best of luck for the next!

  3. allthingshoe

    Hey there! Someone in my Facebook group shared this site with us so I came to check it out.
    I’m definitely enjoying the information. I’m bookmarking and will be tweeting this to my followers! Outstanding blog.

  4. katrinacorin

    Have you ever considered including a little bit more than just your articles? I mean, what you say is valuable and all.
    Nevertheless think about if you added some great visuals or video clips to give your posts more, “pop”! Your content is excellent but with pics and clips, this website could definitely be one of the greatest in its field. Awesome blog!

  5. Pingback: Mock Razorpay API using Jest - Payment Gateway | Noob2Geek

  6. Pingback: Stripe integration With Node.js | Noob2Geek

Leave a Reply

Your email address will not be published.