How Payment Gateways Work: Complete Guide with Razorpay Integration in Node.js

Search for a command to run...

No comments yet. Be the first to comment.
While working on one of the feature in Leadlly, a platform designed to help students organize and maintain their self-studies, I encountered an interesting issue that got me thinking about race conditions in code. The app is designed to generate new ...

JSON Web Token (JWT) is widely used for handling authentication and authorization in modern web applications. JWT allows secure and compact transmission of information between parties as a JSON object, and this information is verifiable and trusted b...

We know, as applications grow in complexity and usage, efficient, secure, and scalable data handling becomes crucial. Handling file uploads is a common requirement in web applications, especially in scenarios where users upload large amounts of data ...

Scaling backend infrastructure is one of the most critical steps in handling growing traffic and ensuring smooth operation under heavy loads. As systems grow, a single server processing all the tasks synchronously can become a bottleneck. This is whe...

A payment gateway is a service that facilitates online payments between buyers and sellers. It acts as a bridge between the customer, the merchant, and the bank. Payment gateways securely transmit payment information for credit cards, debit cards, UPI, and other payment methods.
Merchant: The business or individual selling a product or service.
Customer: The buyer who makes the payment.
Acquiring Bank: The merchant's bank that receives the payment.
Issuing Bank: The customer’s bank that issues the credit or debit card.
Payment Processor: Handles the transaction processing and communicates between the acquiring bank and issuing bank.
Payment Gateway: The service that authorizes and handles the secure transmission of payment information.
Here’s the step-by-step flow of how a payment gateway processes payments:

Step 1: Customer Initiates Payment
The customer selects products/services on a merchant’s website and proceeds to checkout.
At the checkout, the customer chooses a payment method (e.g., credit/debit card, UPI).
Step 2: Payment Gateway Authorization
Step 3: Acquirer Requests Authorization
Step 4: Issuing Bank Validates
Step 5: Approval or Denial
Based on the validation, the issuing bank approves or denies the transaction.
The decision is communicated back to the payment gateway.
Step 6: Payment Confirmation
The payment gateway informs the merchant if the payment was successful or failed.
If successful, the merchant processes the order.
Step 7: Settlement
SSL Encryption: Ensures secure data transmission between customers and payment gateways.
PCI-DSS Compliance: Industry standard for securely handling credit card information stated in Payment Card Industry Data Security Standard.
Tokenization: Sensitive data is replaced by unique identification symbols (tokens) that are exchanged during the payment.
3D Secure: 3D Secure (3-domain structure), an additional security layer that addresses issues of fraud in online debit or credit card transactions.
Razorpay is a popular payment gateway that supports multiple payment methods, including credit/debit cards, UPI, net banking, and wallets. Razorpay simplifies the process for merchants by providing an easy-to-integrate API for accepting payments.

Let’s now go step by step on how to integrate Razorpay into a Node.js project.
You need to install the Razorpay Node.js SDK and any other required dependencies.
npm install razorpay express body-parser
Sign up on Razorpay.
Create an API key in the Razorpay dashboard. You will get a key_id and key_secret, which will be used to authenticate API requests.
In your Node.js application, you need to initialize Razorpay using the SDK. Create a file called payment.js to manage your payment logic.
const Razorpay = require("razorpay");
const razorpayInstance = new Razorpay({
key_id: process.env.RAZORPAY_KEY_ID, // Replace with your Razorpay key_id
key_secret: process.env.RAZORPAY_KEY_SECRET, // Replace with your Razorpay key_secret
});
You need to create an endpoint to generate a payment order before sending it to the client for payment.
app.post("/api/create-order", async (req, res) => {
const { amount, currency, receipt } = req.body;
try {
const options = {
amount: amount * 100, // amount in the smallest currency unit (e.g., paise for INR)
currency,
receipt,
};
const order = await razorpayInstance.orders.create(options);
res.status(200).json(order);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
On the client side, you need to display the Razorpay payment form. Use the Razorpay checkout script:
<script src="https://checkout.razorpay.com/v1/checkout.js"></script>
Then, initialize Razorpay when the user clicks on the "Pay Now" button.
const options = {
key: "YOUR_RAZORPAY_KEY_ID", // Enter the Key ID generated from Razorpay Dashboard
amount: order.amount, // Amount in paise
currency: order.currency,
name: "Merchant Name",
description: "Test Transaction",
order_id: order.id, // Order ID created in the backend
callback_url: "/api/verify-payment", // Usually for verifying subscription
prefill: {
name: "Customer Name",
email: "customer@example.com",
contact: "9999999999",
},
};
const rzp = new Razorpay(options);
rzp.open();
Once the payment is successful, Razorpay sends back a payment ID and order ID. You can use this data to verify the payment on the server side.
app.post("/api/verify-payment", (req, res) => {
const { razorpay_order_id, razorpay_payment_id, razorpay_signature } = req.body;
const body = razorpay_order_id + "|" + razorpay_payment_id;
const crypto = require("crypto");
const expectedSignature = crypto
.createHmac("sha256", process.env.RAZORPAY_KEY_SECRET)
.update(body.toString())
.digest("hex");
if (expectedSignature === razorpay_signature) {
res.send({ success: true });
} else {
res.send({ success: false });
}
});
A payment gateway ensures that online transactions are conducted securely and efficiently. In this blog, we discussed how payment gateways work, and we provided a detailed guide on integrating Razorpay with Node.js. You can now enable payments in your Node.js app using Razorpay, following this step-by-step guide.