HomeBlogHow to Integrate Razorpay into a...

Engineering Guide · 8 min read · August 31, 2026

How to Integrate Razorpay into a Node.js Application

Client-side Razorpay callbacks frequently drop on mobile UPI and netbanking flows, leaving paid orders stuck as pending. This guide walks through server-side order creation in paise, constant-time HMAC signature checks, raw-body webhook ingestion, and an idempotent PostgreSQL ledger.

Author
Smit Desai
Published
August 31, 2026
Read time
8 min read
Topic
APIs & Integrations
Services
Custom Web · Mobile Apps · All Services

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.

Razorpay Node.js Payment Architecture


Why Checkout Callbacks Alone Fail in Production

Razorpay splits a payment lifecycle across two separate channels:

  1. 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.
  2. Asynchronous Webhook delivery: Sent directly from Razorpay's servers to your backend when order.paid, payment.captured, or payment.failed occurs. 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_paise equality on capture: Verify payment.amount === order.amount_paise and payment.currency === order.currency before marking an order paid.
  • Separate secrets by environment: Never allow RAZORPAY_KEY_SECRET or RAZORPAY_WEBHOOK_SECRET in client bundles or frontend .env files.
  • Handle payment.authorized vs payment.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.

Written by Smit Desai · Principal Full-Stack & FDSE

8+ years shipping production systems · 171 case studies · 300+ WordPress servers managed for Finland partners.

Next Steps and Recommended Resources

Next Steps · Recommended Resources

Pillar 1 · Custom Web & SaaS

Custom Web Application Development

Production Laravel, Next.js, API, and multi-tenant SaaS systems engineered end to end at $55/day (8–9 hrs) or $1,999/mo.

Comparison · Buyer Guide

SmitDev vs Software Agencies

See side-by-side economics, senior code ownership, and onboarding speed vs traditional dev shops and marketplaces.

01 — Frequently asked questions

apis & integrations

Why is verifying the Razorpay Checkout callback alone unsafe for production?

Mobile browsers frequently lose connectivity or get killed by the OS while switching to a UPI app like PhonePe or Google Pay. If your backend relies only on the browser callback to mark an order paid, money leaves the customer's bank account while your database never records the capture.

Why should Razorpay amounts always be stored and transmitted as integers in paise?

Floating-point arithmetic in JavaScript causes rounding drift (for example, 19.99 * 100 evaluating to 1998.9999999999998). Passing integer paise values such as 1999 ensures the Razorpay order amount matches your PostgreSQL integer ledger exactly.

How do you prevent duplicate order fulfillment when Razorpay retries a webhook?

Store every incoming webhook event ID or payment ID in a table with a unique database constraint, wrap state transitions inside a database transaction, and verify the current order status before triggering fulfillment or invoice generation.

Why does Express webhook signature verification fail if express.json() runs first?

Razorpay signs the exact raw byte payload of the HTTP POST request. Parsing and re-serializing JSON alters whitespace or key ordering, which breaks the HMAC-SHA256 digest comparison.

03 — Have an engineering need?

hire the right expertise

Let's talk tech.

Deciding between an embedded forward deployed engineer or a senior full stack developer? Share your technical context and timeline.

Solitaire Corporate Park, Makarba, Ahmedabad, Gujarat 380015, India · IST (UTC+5:30) · --:-- IST · Mon–Fri 09:00–18:00 IST · US & EU overlap daily

No newsletter, no CRM. Just a reply.