TL;DR: A production Razorpay integration in Next.js has five parts. Create the order on the server with an amount you calculate yourself. Open Razorpay Checkout in the browser with that order ID. Verify the payment signature on the server before showing success. Treat webhooks as the source of truth, verifying their signature against the raw body and processing each event once. Handle refunds and failures through the same order record. The two mistakes that cause real money problems are trusting an amount from the browser and marking orders paid without verifying a signature.
Key takeaways
- Amounts are in paise and are always computed on the server. Never accept a price from the client.
- Checkout success in the browser is a hint, not proof. Verify the signature, then rely on webhooks.
- Webhook verification needs the raw request body. In the App Router, read it with
req.text()before parsing. - Webhooks arrive more than once and out of order. Make processing idempotent and state transitions one-way.
- Keep one order record per purchase, and move it through clear states: created, paid, failed, refunded.
Why a careful Razorpay integration matters
Razorpay is one of the most widely used payment gateways in India, supporting UPI, cards, netbanking and wallets through a single Checkout. Its quick-start examples get a payment button working in an hour. That is useful, and it also hides the parts that matter once real money moves: duplicate charges when a user double-clicks, orders stuck as unpaid because the browser closed before the success callback, fraudulent "paid" orders created by someone calling your success endpoint directly, and refunds nobody can trace.
Most of these failures come from treating the browser as trustworthy. The browser is where the customer pays, but your server must decide what was bought, how much it costs and whether the money actually arrived. This guide builds that server-centred flow in a Next.js App Router project, with code you can adapt.
If you are comparing gateways or need redundancy, our guide to a multi-gateway payment router with Stripe and Razorpay covers that architecture. Here we focus on doing a single Razorpay integration properly.
How a Razorpay payment flows
Understand the sequence before writing code:
- The customer clicks Pay. Your frontend asks your server to create an order for the items in the cart.
- Your server creates a Razorpay order. It calculates the amount from your database and calls the Orders API with your secret key. Razorpay returns an order ID.
- The browser opens Razorpay Checkout with your public key ID and the order ID. The customer pays with UPI, a card or another method.
- Checkout returns three values to your handler:
razorpay_payment_id,razorpay_order_idandrazorpay_signature. - Your server verifies the signature using your key secret. If it matches, the payment really belongs to that order.
- Razorpay sends webhooks such as
payment.capturedandorder.paidto your server, signed with a separate webhook secret. These confirm the payment even if the browser never returned. - Your server marks the order paid exactly once and fulfils it.
Two independent confirmations, the verified callback and the verified webhook, both lead to the same idempotent "mark paid" function. Whichever arrives first wins, and the second is a no-op.
Prerequisites and setup
You need a Razorpay account with test mode enabled, a Next.js project using the App Router, and a database for orders. Install the official Node SDK:
npm install razorpay
From the Razorpay Dashboard, in test mode, generate API keys and create a webhook with its own secret. Store them as environment variables:
# .env.local: never commit this file
RAZORPAY_KEY_ID=rzp_test_xxxxxxxxxxxx
RAZORPAY_KEY_SECRET=your_test_key_secret
RAZORPAY_WEBHOOK_SECRET=a_long_random_webhook_secret
NEXT_PUBLIC_RAZORPAY_KEY_ID=rzp_test_xxxxxxxxxxxx
Only the key ID is public. It is safe in the browser, because it can only open Checkout for orders you created. The key secret and webhook secret must stay on the server, so they never get the NEXT_PUBLIC_ prefix.
Also decide how payments are captured. Razorpay first authorizes a payment, then captures it. For most products, enable automatic capture in the Dashboard's payment capture settings, so authorized payments are captured without extra code. Authorized payments that are never captured are refunded to the customer automatically after a period, which is a common source of "the customer paid but we never got the money" confusion.
The order data model
Before calling Razorpay, design your own order record. Razorpay's records are not a replacement for yours. You need to know what was bought and what state it is in:
// prisma/schema.prisma (excerpt): one row per purchase attempt
model Order {
id String @id @default(cuid())
userId String
amountPaise Int // integer minor units, never floats
currency String @default("INR")
status OrderStatus @default(CREATED)
razorpayOrderId String? @unique
razorpayPaymentId String? @unique
refundedPaise Int @default(0)
items Json // snapshot of what was bought, at what price
createdAt DateTime @default(now())
paidAt DateTime?
}
enum OrderStatus {
CREATED
PAID
FAILED
PARTIALLY_REFUNDED
REFUNDED
}
model ProcessedWebhook {
eventId String @id // Razorpay's event ID, so each event is handled once
receivedAt DateTime @default(now())
}
Store money as integers in paise. Floating point arithmetic on rupees produces rounding errors that eventually show up as a one paisa mismatch between your total and Razorpay's. The unique constraints on Razorpay IDs stop one payment from ever being attached to two orders.
Step 1: Create the order on the server
The order route calculates the amount from your own data. The browser sends only what it wants to buy, never what it costs:
// app/api/payments/order/route.ts
import { NextResponse } from 'next/server';
import Razorpay from 'razorpay';
import { z } from 'zod';
import { requireUser } from '@/lib/auth';
import { db } from '@/lib/db';
import { priceCart } from '@/lib/pricing';
const razorpay = new Razorpay({
key_id: process.env.RAZORPAY_KEY_ID!,
key_secret: process.env.RAZORPAY_KEY_SECRET!,
});
const Body = z.object({
items: z.array(z.object({ sku: z.string(), qty: z.number().int().min(1).max(20) })).min(1),
});
export async function POST(req: Request) {
const user = await requireUser();
const parsed = Body.safeParse(await req.json());
if (!parsed.success) return NextResponse.json({ error: 'Invalid cart' }, { status: 400 });
// Prices come from the database, never from the request.
const { lines, totalPaise } = await priceCart(parsed.data.items);
if (totalPaise < 100) return NextResponse.json({ error: 'Minimum is 1 rupee' }, { status: 400 });
const order = await db.order.create({
data: { userId: user.id, amountPaise: totalPaise, items: lines },
});
const rzpOrder = await razorpay.orders.create({
amount: totalPaise, // in paise
currency: 'INR',
receipt: order.id, // our ID, visible in the Razorpay Dashboard
notes: { orderId: order.id, userId: user.id },
});
await db.order.update({ where: { id: order.id }, data: { razorpayOrderId: rzpOrder.id } });
return NextResponse.json({
orderId: order.id,
razorpayOrderId: rzpOrder.id,
amount: totalPaise,
currency: 'INR',
});
}
The receipt and notes fields link Razorpay's order back to yours. When you search the Dashboard during a support ticket, your own order ID is right there.
Step 2: Open Checkout in the browser
Load Razorpay's Checkout script only on the page that needs it, so it does not slow down the rest of your site. In the App Router, next/script with lazy loading handles this:
'use client';
import Script from 'next/script';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
export function PayButton({ items }: { items: { sku: string; qty: number }[] }) {
const router = useRouter();
const [busy, setBusy] = useState(false);
async function pay() {
setBusy(true); // blocks double clicks that would create two orders
try {
const res = await fetch('/api/payments/order', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ items }),
});
if (!res.ok) throw new Error('Could not start payment');
const order = await res.json();
const checkout = new window.Razorpay({
key: process.env.NEXT_PUBLIC_RAZORPAY_KEY_ID,
order_id: order.razorpayOrderId,
amount: order.amount,
currency: order.currency,
name: 'Your Store',
description: `Order ${order.orderId}`,
handler: async (response: Record<string, string>) => {
const verify = await fetch('/api/payments/verify', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ orderId: order.orderId, ...response }),
});
router.push(
verify.ok ? `/orders/${order.orderId}` : `/orders/${order.orderId}?pending=1`,
);
},
modal: { ondismiss: () => setBusy(false) },
});
checkout.on('payment.failed', () => setBusy(false));
checkout.open();
} catch {
setBusy(false);
}
}
return (
<>
<Script src="https://checkout.razorpay.com/v1/checkout.js" strategy="lazyOnload" />
<button type="button" onClick={pay} disabled={busy}>
{busy ? 'Opening payment...' : 'Pay now'}
</button>
</>
);
}
Add a type declaration for window.Razorpay in a .d.ts file to keep TypeScript happy. If your site uses a content security policy, allow Razorpay's checkout and API domains for scripts, frames and connections, or Checkout will fail silently.
Notice the redirect after verification. If verification fails or is slow, the user lands on an order page marked pending, not an error. The webhook will usually confirm the payment moments later. Telling a customer their payment failed when it actually succeeded generates angry support tickets and duplicate payments.
Step 3: Verify the payment signature
Razorpay signs the Checkout response so you can prove it is genuine. The signature is an HMAC SHA256 of the order ID and payment ID, joined by a pipe character, using your key secret:
// app/api/payments/verify/route.ts
import crypto from 'node:crypto';
import { NextResponse } from 'next/server';
import { z } from 'zod';
import { requireUser } from '@/lib/auth';
import { db } from '@/lib/db';
import { markOrderPaid } from '@/lib/payments';
const Body = z.object({
orderId: z.string(),
razorpay_order_id: z.string(),
razorpay_payment_id: z.string(),
razorpay_signature: z.string(),
});
function safeEqual(a: string, b: string) {
const left = Buffer.from(a);
const right = Buffer.from(b);
return left.length === right.length && crypto.timingSafeEqual(left, right);
}
export async function POST(req: Request) {
const user = await requireUser();
const body = Body.parse(await req.json());
const order = await db.order.findFirst({ where: { id: body.orderId, userId: user.id } });
if (!order || order.razorpayOrderId !== body.razorpay_order_id) {
return NextResponse.json({ error: 'Order mismatch' }, { status: 400 });
}
const expected = crypto
.createHmac('sha256', process.env.RAZORPAY_KEY_SECRET!)
.update(`${order.razorpayOrderId}|${body.razorpay_payment_id}`)
.digest('hex');
if (!safeEqual(expected, body.razorpay_signature)) {
return NextResponse.json({ error: 'Invalid signature' }, { status: 400 });
}
await markOrderPaid(order.id, body.razorpay_payment_id);
return NextResponse.json({ ok: true });
}
Two details matter. The order ID used in the HMAC comes from your database, not from the request, so a signature for one order cannot be replayed against another. And the comparison uses timingSafeEqual, which avoids leaking information through response timing.
Step 4: Handle webhooks as the source of truth
The browser callback fails in ordinary situations: the user closes the tab, the phone loses signal after a UPI payment, or the UPI app takes a minute to confirm. Webhooks cover all of these. Configure your webhook URL in the Dashboard and subscribe at least to payment.captured, payment.failed, order.paid and the refund events.
Razorpay signs each webhook with an HMAC SHA256 of the raw request body using your webhook secret, sent in the X-Razorpay-Signature header. The word "raw" is essential. If you parse the JSON first and then stringify it, whitespace or key order can change and the signature will not match. In the App Router, read the body as text:
// app/api/payments/webhook/route.ts
import crypto from 'node:crypto';
import { NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { markOrderPaid, markOrderFailed, recordRefund } from '@/lib/payments';
export async function POST(req: Request) {
const raw = await req.text(); // raw body, before any parsing
const signature = req.headers.get('x-razorpay-signature') ?? '';
const expected = crypto
.createHmac('sha256', process.env.RAZORPAY_WEBHOOK_SECRET!)
.update(raw)
.digest('hex');
const valid =
signature.length === expected.length &&
crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected));
if (!valid) return NextResponse.json({ error: 'Invalid signature' }, { status: 400 });
// Razorpay retries deliveries; process each event ID once.
const eventId = req.headers.get('x-razorpay-event-id');
if (eventId) {
const seen = await db.processedWebhook.findUnique({ where: { eventId } });
if (seen) return NextResponse.json({ ok: true, duplicate: true });
}
const event = JSON.parse(raw);
const payment = event.payload?.payment?.entity;
const orderId = payment?.notes?.orderId;
switch (event.event) {
case 'payment.captured':
case 'order.paid':
if (orderId && payment?.id) await markOrderPaid(orderId, payment.id);
break;
case 'payment.failed':
if (orderId) await markOrderFailed(orderId, payment?.error_description);
break;
case 'refund.processed':
await recordRefund(event.payload.refund.entity);
break;
}
if (eventId) await db.processedWebhook.create({ data: { eventId } });
return NextResponse.json({ ok: true });
}
Respond quickly with a 2xx status. If you need slow work, such as sending invoices or provisioning accounts, put it on a queue and return immediately. Razorpay retries failed deliveries, and a slow endpoint turns into repeated deliveries. For high volumes, our guide to idempotent webhook ingestion covers queue-based designs.
The order ID reaches the payment entity because Razorpay copies an order's notes onto its payments. That is why Step 1 put orderId in the notes.
Step 5: Make state changes idempotent
The verify route and the webhook both call markOrderPaid, often within seconds of each other. The function must be safe to call twice, and a late payment.failed must never undo a success:
// lib/payments.ts
import { db } from '@/lib/db';
export async function markOrderPaid(orderId: string, paymentId: string) {
// Conditional update: only CREATED or FAILED orders can become PAID.
const result = await db.order.updateMany({
where: { id: orderId, status: { in: ['CREATED', 'FAILED'] } },
data: { status: 'PAID', razorpayPaymentId: paymentId, paidAt: new Date() },
});
if (result.count === 1) await fulfilOrder(orderId); // runs once, on the real transition
}
export async function markOrderFailed(orderId: string, reason?: string) {
// A failure never overwrites a payment that already succeeded.
await db.order.updateMany({
where: { id: orderId, status: 'CREATED' },
data: { status: 'FAILED' },
});
console.info('payment failed', { orderId, reason });
}
The conditional updateMany is the whole trick. The database decides atomically whether this call performed the transition, and only that call triggers fulfilment. A customer may fail one attempt and succeed on retry within the same order, which is why FAILED can still move to PAID.
| Event or action | Allowed from | Moves to | Side effect |
|---|---|---|---|
| Order created | Nothing | CREATED | Razorpay order created |
Verified callback or payment.captured or order.paid | CREATED, FAILED | PAID | Fulfil once |
payment.failed | CREATED | FAILED | Show retry option |
| Partial refund processed | PAID, PARTIALLY_REFUNDED | PARTIALLY_REFUNDED | Update refunded amount |
| Full refund processed | PAID, PARTIALLY_REFUNDED | REFUNDED | Revoke access if digital |
Step 6: Issue and track refunds
Refunds start from your admin panel or support tooling and go through the Payments API. Refund against the payment ID, in paise, and record the result:
// lib/refunds.ts
import Razorpay from 'razorpay';
import { db } from '@/lib/db';
const razorpay = new Razorpay({
key_id: process.env.RAZORPAY_KEY_ID!,
key_secret: process.env.RAZORPAY_KEY_SECRET!,
});
export async function refundOrder(orderId: string, amountPaise: number, reason: string) {
const order = await db.order.findUniqueOrThrow({ where: { id: orderId } });
if (!order.razorpayPaymentId) throw new Error('Order has no captured payment');
const remaining = order.amountPaise - order.refundedPaise;
if (amountPaise < 1 || amountPaise > remaining) throw new Error('Refund exceeds paid amount');
// Razorpay processes the refund asynchronously; the refund webhook confirms it.
return razorpay.payments.refund(order.razorpayPaymentId, {
amount: amountPaise,
speed: 'normal',
notes: { orderId, reason },
});
}
Update refundedPaise and the order status from the refund.processed webhook, not from the API response, because the refund completes asynchronously. Restrict this function to staff roles and log who refunded what, since refunds are a classic insider fraud path.
UPI and mobile behaviour you should plan for
In India, a large share of payments go through UPI, and UPI behaves differently from cards in ways that affect your code.
Payments can complete after the customer leaves. With UPI collect requests and intent flows, the customer approves the payment in a separate app such as Google Pay, PhonePe or Paytm. They may switch back to your site late, or never. The webhook often arrives before or without the Checkout handler. This is the strongest reason to treat webhooks as the source of truth.
Pending states last longer. A UPI payment can sit in a pending state for seconds or, occasionally, minutes while banks confirm. Your order page should show a clear "confirming your payment" state that refreshes on its own, rather than an error. A short polling call to your own API, which reads the order status your webhook maintains, is enough.
Mobile browsers are fragile. On low-end Android phones, switching to a UPI app can cause the browser to reload your page when the customer returns. Never keep payment state only in React state or session memory. The order ID in the URL plus the order record on the server lets the page recover no matter what the browser does.
Customers retry. If a customer thinks a payment failed, they will try again, sometimes creating a second order and paying twice. Show pending orders clearly, block a second order for the same cart while one is pending, and make refunds for genuine duplicates quick and easy.
Reconciliation and settlements
Getting paid is not the end of the money flow. Razorpay settles captured funds to your bank account on a schedule, minus its fees and any applicable taxes. Finance teams need to match three things: your orders, Razorpay payments and bank settlements.
Build this in from the start rather than in a spreadsheet later. Store the Razorpay payment ID on every paid order, as the data model above does. Pull settlement reports from the Dashboard or the Settlements API on a schedule, and match each settled payment to an order. Flag payments with no matching order, orders marked paid with no settled payment after the expected window, and refunds that do not appear in a settlement.
A weekly reconciliation report catches integration bugs that tests miss, such as a webhook handler that silently failed for a day. It also gives your accountant the evidence they need for GST filings, and it turns "we think the numbers match" into a check you can show.
Testing before you go live
Test mode behaves like live mode without moving money. Use it thoroughly:
- Happy path: pay with a test card and with the test UPI flow, and confirm the order becomes
PAIDonce. - Closed tab: pay, then close the browser before the callback runs. The webhook should still mark the order paid.
- Failure: use a failing test payment and confirm the order shows a retry option.
- Duplicate webhooks: resend an event from the Dashboard and confirm nothing happens twice.
- Tampering: call the verify route with a wrong signature and with another order's IDs. Both must fail.
- Refunds: refund partially, then fully, and confirm the statuses and amounts.
To receive webhooks on your laptop, expose your local server with a tunnelling tool and set that URL as a test webhook. Keep separate webhooks and secrets for test and live mode.
Going live
When moving from test to live mode, work through these changes deliberately:
| Item | Test mode | Live mode |
|---|---|---|
| API keys | rzp_test_ key and secret | rzp_live_ key and secret, in production secrets only |
| Webhook | Test URL and secret | Production URL, new secret, same subscribed events |
| Account | Basic setup | KYC complete, settlement account verified |
| Payment methods | All test methods | Enabled methods reviewed for your business |
| Capture | Auto-capture tested | Auto-capture enabled in live settings |
| Monitoring | Logs only | Alerts on webhook failures and stuck CREATED orders |
Add a scheduled job that looks for orders stuck in CREATED for more than an hour and asks Razorpay for their payment status. It catches the rare case where both the callback and the webhooks were missed, for example during a deployment.
If you need help with any of this, our payment gateway integration services cover Razorpay, Stripe and multi-gateway setups, including subscriptions, invoicing and reconciliation.
Security considerations
- Server-side pricing only. The most common Razorpay bug is accepting
amountfrom the browser. - Secrets stay on the server. The key secret and webhook secret never use the
NEXT_PUBLIC_prefix and never appear in logs. - Verify every signature with constant-time comparison, for both the callback and webhooks.
- Bind verification to the user and order from your database, so IDs from one purchase cannot confirm another.
- Rate limit the order route, so a bot cannot create thousands of orders.
- Restrict refunds to authorised staff and record an audit trail.
- Do not store card data. Razorpay Checkout handles it, which keeps most PCI DSS scope off your servers.
Common mistakes and failure modes
- Trusting the client amount, allowing a user to pay ₹1 for a ₹10,000 order.
- Marking paid in the browser callback without verification, so anyone can call the success route.
- Parsing the webhook body before verifying, which breaks the signature check.
- No idempotency, so retried webhooks fulfil an order twice or send duplicate emails.
- Letting failure overwrite success, when events arrive out of order.
- Using rupee floats, causing paise rounding mismatches.
- Forgetting capture settings, so authorized payments are refunded automatically.
- One webhook secret for test and live, or a secret committed to git.
- Loading Checkout on every page, which slows the whole site for no benefit.
Production checklist
- Order amounts are calculated on the server from the database, in integer paise.
- Each purchase has its own order record with clear states and unique Razorpay IDs.
- Checkout loads lazily on the payment page only, and double clicks are blocked.
- The callback signature is verified on the server with constant-time comparison.
- Webhooks verify the raw body signature and are processed once per event ID.
markOrderPaidis idempotent; failures never overwrite a successful payment.- Refunds are restricted, audited and confirmed by webhook.
- Auto-capture is enabled and tested in live mode.
- Test, closed-tab, failure, duplicate and tampering scenarios all pass.
- Live keys and webhook secrets live only in production secret storage.
- Alerts fire on webhook errors and on orders stuck in
CREATED.
Conclusion and next steps
A Razorpay integration that survives production is not much more code than the quick start, but the code sits in different places. The server owns pricing, order state and verification. The browser only collects the payment. Webhooks confirm what really happened, and an idempotent state machine makes sure each payment is counted once.
Start in test mode with the order model and the five routes in this guide, run every test scenario, then go live with alerts in place. If you later add subscriptions or a second gateway, this structure extends cleanly.
Building a checkout for an Indian product, or fixing one that loses payments? Talk to our team about your payment flow, or see our fintech software development work for larger payment systems.
Sources
- Razorpay Docs: Standard Checkout integration
- Razorpay Docs: Orders API
- Razorpay Docs: Webhooks and validation
- Razorpay Docs: Refunds API
- razorpay-node SDK on GitHub
- Next.js Docs: Route Handlers
Frequently Asked Questions
How do I integrate Razorpay in Next.js?
Create the order on the server with the Razorpay Node SDK, open Razorpay Checkout in a client component with the returned order ID, verify the payment signature in a route handler, and process signed webhooks to confirm payments. Keep the key secret on the server.
How is the Razorpay payment signature verified?
Compute an HMAC SHA256 of the order ID and payment ID joined by a pipe character, using your key secret, and compare it in constant time with the razorpay_signature returned by Checkout. Use the order ID from your database, not from the request.
Why does my Razorpay webhook signature not match?
Usually because the body was parsed and re-serialised before verification. Compute the HMAC over the raw request body, which you can read with req.text() in a Next.js route handler, and use the webhook secret, not the API key secret.
Should I rely on the Checkout handler or webhooks?
Both, through the same idempotent function. The handler gives the user immediate feedback, and webhooks confirm payments even when the browser closes or the network drops. Treat webhooks as the source of truth.
Is the Razorpay amount in rupees or paise?
In paise, the smallest currency unit. ₹499 is sent as 49900. Store amounts as integers in paise throughout your system to avoid rounding errors.
Why was a Razorpay payment refunded automatically?
Payments that are authorized but never captured are refunded automatically after a set period. Enable automatic capture in the Dashboard's payment capture settings, or capture payments through the API.
