Inteliny
DevelopmentLevel: Intermediate25mVerified Production Blueprint

How to Integrate Razorpay Payment Gateway in MERN Stack

Learn to integrate Razorpay payment gateway in a MERN stack application for secure transactions

Inteliny Engineering

Principal Architect

Overview & Architecture Scope

This guide is designed for developers looking to integrate Razorpay payment gateway into their MERN stack applications. Razorpay is a popular payment solution in India that supports various payment methods. To follow this guide, you should have a basic understanding of React, Node.js, Express, and MongoDB. By the end of this guide, you will have successfully integrated Razorpay into your MERN application, enabling secure and efficient transactions. The integration process involves several steps, including setting up a Razorpay account, creating orders, handling payment verification, and implementing webhooks for payment updates. This comprehensive guide covers all these aspects and provides code examples for better understanding.

Prerequisites & System Requirements

Ensure your development workstation or staging server fulfills the following prerequisites before initiating commands:

Node.js v18.0+ runtime environment
MongoDB v6.0+ database cluster
Active AWS or Cloudflare account with DNS access
Linux Ubuntu 22.04 LTS server instance
Basic knowledge of CLI bash & Git workflow

Target System Architecture Diagram

Browser
NGINX
Node / Express
MongoDB / Redis

Interactive Execution Checklist

0/7 Completed

Step-by-Step Implementation Guide

1

Step 1: Create a Razorpay Account

To start integrating Razorpay, you first need to create an account on the Razorpay website. This will provide you with the necessary keys (API key ID and API key secret) required for the integration process. Ensure you save these keys securely as they will be used in your application.

Keep your API keys secure to prevent unauthorized access
2

Step 2: Set Up Your MERN Project

Ensure your MERN project is set up with the latest versions of React, Node.js, Express, and MongoDB. You can create a new React app using create-react-app and set up a new Node.js project with Express for the backend. Connect your MongoDB database to the Node.js backend.

Execute Command Terminal:

bash
npx create-react-app razorpay-mern && npm init -y && npm install express mongodb
Make sure you have Node.js and MongoDB installed
3

Step 3: Install Razorpay SDK

Install the Razorpay SDK in your Node.js project to interact with the Razorpay API. You can install it using npm by running npm install razorpay

Execute Command Terminal:

bash
npm install razorpay
The SDK simplifies the process of making API calls to Razorpay
4

Step 4: Create an Order

Create an order on your server-side (Node.js) using the Razorpay SDK. This involves making a POST request to the Razorpay orders API with the order amount and other relevant details. The response will contain an order ID which you will use to initiate the payment.

Execute Command Terminal:

javascript
const razorpay = require('razorpay');
const instance = new razorpay({
  key_id: 'YOUR_API_KEY_ID',
  key_secret: 'YOUR_API_KEY_SECRET'
});
instance.orders.create({
  amount: 50000,
  currency: 'INR',
  receipt: 'order_rcptid_11'
})
Replace 'YOUR_API_KEY_ID' and 'YOUR_API_KEY_SECRET' with your actual Razorpay API keys
5

Step 5: Handle Payment Verification

After the user completes the payment, Razorpay sends a payment ID and order ID back to your application. You need to verify this payment by making a request to the Razorpay payments API to confirm the payment status.

Execute Command Terminal:

javascript
instance.payments.fetch('payment_id').then((payment) => {
  // Verify payment
})
Payment verification is crucial for security and to prevent fraud
6

Step 6: Implement Webhooks

Razorpay provides webhooks for real-time updates on payment events such as payment.success, payment.failure, etc. Set up a webhook endpoint in your Node.js application to listen for these events and update your database accordingly.

Execute Command Terminal:

javascript
app.post('/razorpay-webhook', (req, res) => {
  // Process webhook event
})
Webhooks are essential for handling payment updates asynchronously
7

Step 7: Integrate Refund and Failure Handling

Implement refund handling by making a refund request to the Razorpay API. Also, handle payment failures by displaying appropriate error messages to the user and logging the failure for further analysis.

Execute Command Terminal:

javascript
instance.refunds.create({
  payment_id: 'payment_id',
  amount: 50000,
  speed: 'normal'
})
Refund and failure handling improves user experience and helps in debugging

Pro Tips & Optimizations

Always validate user input to prevent security vulnerabilities
Use environment variables to store sensitive keys like API keys
Implement logging for all payment events for easier debugging
Test your integration thoroughly with different payment methods and scenarios

Common Pitfalls to Avoid

Not verifying payments, making the application vulnerable to fraud
Exposing API keys in the frontend code, leading to security breaches
Not handling payment failures and refunds properly, affecting user experience
Conclusion & Next Steps

Integrating Razorpay into a MERN stack application requires careful setup and handling of payments, webhooks, and security measures. By following the steps outlined in this guide and paying attention to security best practices, you can ensure a smooth and secure payment experience for your users. Remember to test your integration thoroughly and monitor payment events for any issues.

Production Best Practices & Hardening

Security Hardening

Disable root SSH access, enforce key-based auth, and enable UFW firewall on ports 80/443.

Memory Management

Set Node.js max-old-space-size to 80% of total RAM to avoid Linux OOM-killer crashes.

Frequently Asked Questions

Yes, all NGINX, Docker, and PM2 deployment steps can be packaged into Infrastructure as Code (IaC) playbooks.

Need Help Implementing This?

Partner with Inteliny's principal architects to audit your stack, automate CI/CD, and accelerate deployment.

How to Integrate Razorpay Payment Gateway in MERN Stack | Inteliny Knowledge Base