Every payment bug I get called to fix on Indian SaaS and e-commerce backends starts with the same assumption: the developer treated Razorpay's frontend Checkout handler callback as the source of truth.
In local testing on office Wi-Fi, that works every time. In production, a buyer pays through a UPI intent on a shaky 4G connection, the banking app takes twelve seconds to return control to the browser, or the user closes the tab the moment they see the debit SMS. Your frontend POST /api/payments/verify request never fires. The customer is debited, and your database still shows pending.
If you are building custom web application development for Indian businesses, you need an architecture where client verification accelerates the UI, while signed server-to-server webhooks and a strict database ledger guarantee financial accuracy.

Why Checkout Callbacks Alone Fail in Production
Razorpay splits a payment lifecycle across two separate channels:
- Synchronous Checkout callback: Returned to the browser immediately after the customer completes authentication. Useful for showing an instant receipt screen, unreliable as a system of record.
- Asynchronous Webhook delivery: Sent directly from Razorpay's servers to your backend when
order.paid,payment.captured, orpayment.failedoccurs. Retried with exponential backoff if your server is temporarily unreachable.
The Two-Channel Rule
Treat the synchronous verification endpoint and the asynchronous webhook handler as competing paths to the same idempotent state transition. Whichever arrives first locks the order row, records the payment, and transitions the order from created to paid. The second path sees the row is already paid and exits cleanly with 200 OK.
PostgreSQL Schema for Idempotent Payment Ledgers
Never store payment state as a single mutable status string on an orders table without an audit trail. Use integer paise (BIGINT) for all monetary columns to avoid JavaScript IEEE-754 floating-point drift, and enforce uniqueness at the database layer.
CREATE TABLE orders (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
merchant_receipt VARCHAR(40) NOT NULL UNIQUE,
razorpay_order_id VARCHAR(64) UNIQUE,
amount_paise BIGINT NOT NULL CHECK (amount_paise > 0),
currency CHAR(3) NOT NULL DEFAULT 'INR',
status VARCHAR(24) NOT NULL DEFAULT 'created',
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE TABLE payment_events (
id BIGSERIAL PRIMARY KEY,
razorpay_payment_id VARCHAR(64) NOT NULL,
razorpay_order_id VARCHAR(64) NOT NULL,
event_type VARCHAR(48) NOT NULL,
idempotency_key VARCHAR(128) NOT NULL UNIQUE,
payload JSONB NOT NULL,
processed_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
Notice the UNIQUE constraint on idempotency_key (composed of ${event}:${paymentId}). Even if two concurrent requests—one from the browser and one from a Razorpay webhook—arrive within the same millisecond, PostgreSQL rejects the duplicate insert cleanly instead of sending two GST invoices.
Server-Side Order Creation and HMAC Verification
Always calculate order totals on your server from your own product catalog. Never accept amount from the client request body.
Creating Orders via the Official SDK
import Razorpay from 'razorpay';
import crypto from 'node:crypto';
const razorpay = new Razorpay({
key_id: process.env.RAZORPAY_KEY_ID,
key_secret: process.env.RAZORPAY_KEY_SECRET,
});
export async function createPaymentOrder(db, userId, items) {
const amountPaise = await calculateCatalogTotalPaise(db, items);
const receipt = `rcpt_${crypto.randomBytes(8).toString('hex')}`;
const rzpOrder = await razorpay.orders.create({
amount: amountPaise,
currency: 'INR',
receipt,
notes: { user_id: String(userId) },
});
await db.query(
`INSERT INTO orders (merchant_receipt, razorpay_order_id, amount_paise, status)
VALUES ($1, $2, $3, 'created')`,
[receipt, rzpOrder.id, amountPaise]
);
return {
orderId: rzpOrder.id,
amountPaise,
currency: 'INR',
keyId: process.env.RAZORPAY_KEY_ID,
};
}
Constant-Time Signature Check for Checkout Return
When the frontend posts razorpay_order_id, razorpay_payment_id, and razorpay_signature, verify the HMAC-SHA256 digest using crypto.timingSafeEqual so timing side-channels cannot leak partial signature matches.
export function verifyCheckoutSignature({ orderId, paymentId, signature }) {
const expected = crypto
.createHmac('sha256', process.env.RAZORPAY_KEY_SECRET)
.update(`${orderId}|${paymentId}`)
.digest('hex');
const expectedBuf = Buffer.from(expected, 'utf8');
const receivedBuf = Buffer.from(signature || '', 'utf8');
if (expectedBuf.length !== receivedBuf.length) {
return false;
}
return crypto.timingSafeEqual(expectedBuf, receivedBuf);
}
Do not skip the length check before calling crypto.timingSafeEqual; Node.js throws a RangeError if the two buffers differ in byte length, which can crash an unhandled route or trigger an unnecessary 500.
Raw Body Webhook Processing and Queue Offloading
Webhooks fail most often in Express or Fastify because a global JSON body parser consumes the stream before your route sees it. You must preserve the raw bytes solely for the webhook path, verify X-Razorpay-Signature against your dedicated RAZORPAY_WEBHOOK_SECRET (which is not your API key_secret), and offload downstream work like PDF invoicing or ERP syncs.
If you want deeper background-worker patterns, see our guide on scaling background jobs and queues with Redis and standard webhook signature verification practices.
import express from 'express';
import crypto from 'node:crypto';
const router = express.Router();
router.post(
'/webhooks/razorpay',
express.raw({ type: 'application/json' }),
async (req, res) => {
const signature = req.get('x-razorpay-signature') || '';
const expected = crypto
.createHmac('sha256', process.env.RAZORPAY_WEBHOOK_SECRET)
.update(req.body)
.digest('hex');
const sigBuf = Buffer.from(signature, 'utf8');
const expBuf = Buffer.from(expected, 'utf8');
if (sigBuf.length !== expBuf.length || !crypto.timingSafeEqual(sigBuf, expBuf)) {
return res.status(401).json({ error: 'Invalid webhook signature' });
}
const event = JSON.parse(req.body.toString('utf8'));
if (event.event === 'order.paid' || event.event === 'payment.captured') {
const payment = event.payload.payment.entity;
await enqueueOrderCaptureJob({
razorpayOrderId: payment.order_id,
razorpayPaymentId: payment.id,
amountPaise: payment.amount,
eventType: event.event,
rawPayload: event,
});
}
return res.status(200).json({ received: true });
}
);
Returning 200 OK immediately after durable enqueueing prevents Razorpay from timing out your endpoint while your worker generates GST invoices or updates inventory.
Architecture Comparison: Choosing Your Settlement Flow
| Integration Pattern | Network Drop Resilience | UI Confirmation Speed | Duplicate Risk | Operational Complexity |
|---|---|---|---|---|
| Checkout Callback Only | Fails on UPI/tab close | Instant | Low | Low (unsafe for production) |
| Webhook Only | High (automatic retries) | 1–5 sec polling delay | Medium without unique keys | Medium |
| Dual-Path + Ledger Lock | High | Instant on happy path | Zero (DB unique constraint) | Medium (recommended) |
| Dual-Path + Nightly Reconcile | Maximum | Instant | Zero | Higher (adds cron sweep) |
For businesses handling significant daily volume, add a nightly reconciliation job that queries Razorpay's payments.all API for any local order still sitting in created older than 30 minutes. That catches edge cases where a webhook endpoint was misconfigured during a DNS change or firewall update.
Production Security and Reconciliation Checklist
Review these boundaries against the OWASP API Security guidelines before switching from rzp_test_ to rzp_live_ keys:
- Enforce
amount_paiseequality on capture: Verifypayment.amount === order.amount_paiseandpayment.currency === order.currencybefore marking an order paid. - Separate secrets by environment: Never allow
RAZORPAY_KEY_SECRETorRAZORPAY_WEBHOOK_SECRETin client bundles or frontend.envfiles. - Handle
payment.authorizedvspayment.captured: Enable auto-capture on your Razorpay order or explicitly capture authorized funds; otherwise funds auto-refund after 5 days. - Pin webhook IP or enforce strict HMAC: Because webhooks arrive over public HTTPS, constant-time HMAC verification and raw body parsing are mandatory.
- Log correlation IDs, never card or secret fields: Redact headers and secrets in structured JSON logs so payment debugging never leaks credentials.
Shipping Reliable Payment Systems with SmitDev
At SmitDev, I have architected payment ledgers, multi-currency checkout flows, and webhook pipelines across 170+ shipped case studies for teams operating in India, the US, Europe, the UK, UAE, Australia, and Singapore.
Whether you need a dedicated principal engineer at $55/day for 8–9 hours of focused delivery, a $1,999/month dedicated engineering retainer to harden your Node.js billing backend, or a broader custom API and platform build, we scope the database ledger, webhook retry strategy, and reconciliation tooling cleanly from day one.
Ready to ship a payment integration that never drops an order? Discuss your Node.js and Razorpay requirements with Smit.