Accepting Payments Safely
By the end of this lesson EventHub can sell tickets for paid meetups such as the ₹149 Pune PostgreSQL Evening. The server creates every order with the price from PostgreSQL, Razorpay Checkout collects the money, and a seat is booked only after an HMAC signature proves the payment is genuine. You will also make the booking idempotent, so a double click or a repeated webhook never books twice. Everything here uses test mode and test values only.
What you should know first: Server Actions & Forms, Route Handlers (API Routes) and Caching & Revalidation. The ideas behind signatures are in Cryptography Basics. Versions checked on 16 November 2026: razorpay (Node.js SDK) 2.9.8, Next.js 16.4.6. Facts about Razorpay come from its official documentation on that date.
The golden rule: the browser is not the cashier
Picture a movie hall in Lucknow. The ticket counter, not the customer, decides the price. When the customer shows a UPI payment screen, the clerk checks the payment on their own device before printing a ticket, because a screenshot can be edited.
Online payments follow the same rule. Anything that comes from the browser, including the price, the "payment successful" message and the ids, can be changed by the user. So:
- The server creates the order, reading the amount from the database.
- Razorpay Checkout (a payment window from Razorpay) takes the card, UPI or netbanking details. Your server never sees them.
- The server verifies a signature before booking anything.
- A webhook (a server-to-server message from Razorpay) confirms the payment even if the customer's browser closed.
| Step | Who | What crosses the network |
|---|---|---|
| Create order | Your server to Razorpay | amount in paise, currency, receipt; secret key in the auth header |
| Pay | Browser to Razorpay | card or UPI details, never to your server |
| Confirm | Browser to your server | order id, payment id, signature |
| Webhook | Razorpay to your server | event JSON plus X-Razorpay-Signature |
Step 1: Test keys and environment
Sign up at Razorpay, switch the Dashboard to Test Mode and generate API keys. Test keys start with rzp_test_, and test payments move no real money. Add three names to .env and placeholders to .env.example:
# Razorpay TEST mode keys (Dashboard > Account & Settings > API Keys, with Test Mode on)
RAZORPAY_KEY_ID="rzp_test_replace_me"
RAZORPAY_KEY_SECRET=""
# Secret you type when adding the webhook in the Razorpay Dashboard
RAZORPAY_WEBHOOK_SECRET=""None of them has the NEXT_PUBLIC_ prefix. Remember the warning line from the env checker in Set Up a Full Stack Next.js Project: a payment secret in browser code is a disaster. The key id is safe to show to the browser and the server sends it when needed; the key secret and the webhook secret never leave the server.
npm install razorpay@2.9.8Step 2: Tables for payments
Add two models to prisma/schema.prisma (plus payments Payment[] on User and Event):
model Payment {
id String @id @default(cuid())
razorpayOrderId String @unique
razorpayPaymentId String? @unique
amountInPaise Int
status PaymentStatus @default(CREATED)
eventId String
event Event @relation(fields: [eventId], references: [id])
userId String
user User @relation(fields: [userId], references: [id])
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@index([eventId, userId])
}
enum PaymentStatus {
CREATED
PAID
FAILED
}
model WebhookEvent {
id String @id // the x-razorpay-event-id header
type String
receivedAt DateTime @default(now())
}Run npx prisma migrate dev --name payments and npx prisma generate. The two @unique columns and the WebhookEvent primary key are the database's part of idempotency: some duplicates are impossible to store at all.
Step 3: Create the order on the server
Create lib/payments.ts. The interesting function is createOrderFor:
import "server-only";
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 createOrderFor(userId: string, slug: string): Promise<CheckoutOrder | { error: string }> {
const event = await db.event.findUnique({
where: { slug },
select: { id: true, title: true, priceInPaise: true, startsAt: true },
});
if (!event || event.startsAt <= new Date()) return { error: "This meetup is not open for booking." };
if (event.priceInPaise === 0) return { error: "This meetup is free. Just RSVP." };
const paid = await db.payment.findFirst({ where: { eventId: event.id, userId, status: "PAID" } });
if (paid) return { error: "You already have a ticket." };
// Idempotency: a double click or a reload reuses the open order instead of creating another.
const open = await db.payment.findFirst({
where: { eventId: event.id, userId, status: "CREATED", amountInPaise: event.priceInPaise },
orderBy: { createdAt: "desc" },
});
const keyId = process.env.RAZORPAY_KEY_ID!;
if (open) return { orderId: open.razorpayOrderId, amountInPaise: open.amountInPaise, keyId, title: event.title };
const order = await razorpay.orders.create({
amount: event.priceInPaise, // paise, exactly what EventHub stores
currency: "INR",
receipt: `eh_${event.id}`.slice(0, 40),
notes: { eventSlug: slug, userId },
});
await db.payment.create({
data: { razorpayOrderId: order.id, amountInPaise: event.priceInPaise, eventId: event.id, userId },
});
return { orderId: order.id, amountInPaise: event.priceInPaise, keyId, title: event.title };
}Razorpay's Orders API takes amount in the smallest unit of the currency, so ₹149 is 14900. EventHub has stored paise since the first lesson, so there is no conversion and no rounding. The receipt may be at most 40 characters, hence the slice. The browser sends only a slug; it has no say in the price.
A Server Action in app/events/pay-actions.ts wraps it:
"use server";
export async function startCheckout(slug: string): Promise<CheckoutOrder | { error: string }> {
const user = await requireUser();
if (typeof slug !== "string") return { error: "Something was missing." };
try {
return await createOrderFor(user.id, slug);
} catch (error) {
// Log the details for us; show the member a calm message without internals.
console.error("[payments] order create failed:", JSON.stringify(error));
return { error: "Payments are not available right now. Please try again." };
}
}We have no real Razorpay account in our test setup, so we called the Orders API directly with made-up test keys to see what a wrong key looks like:
curl -u rzp_test_EventHubDemo01:test_secret_only_for_learning -H "Content-Type: application/json" -d '{"amount":14900,"currency":"INR","receipt":"eh_demo"}' https://api.razorpay.com/v1/orders{"error":{"code":"BAD_REQUEST_ERROR","description":"Authentication failed"}}
[401]In Chrome, signed in as Kabir, the "Buy ticket · ₹149.00" button on the Pune meetup then showed "Payments are not available right now. Please try again." The member sees a calm message; the details go only to the server log.
Step 4: Open Checkout in the browser
components/pay-button.tsx is a Client Component. It loads Razorpay's script with next/script and opens Checkout with the order the server made:
"use client";
export function PayButton({ slug, label }: { slug: string; label: string }) {
const [message, setMessage] = useState("");
const [pending, startTransition] = useTransition();
function pay() {
startTransition(async () => {
const order = await startCheckout(slug); // the server decides the amount
if ("error" in order) return setMessage(order.error);
if (!window.Razorpay) return setMessage("Checkout did not load. Check your connection.");
new window.Razorpay({
key: order.keyId, // the public key id; the key secret stays on the server
amount: order.amountInPaise,
currency: "INR",
name: "EventHub",
description: order.title,
order_id: order.orderId,
handler: (response) => {
startTransition(async () => setMessage((await confirmPayment(response)).message));
},
modal: { ondismiss: () => setMessage("Payment cancelled. You have not been charged.") },
}).open();
});
}
return (
<div className="my-3">
<Script src="https://checkout.razorpay.com/v1/checkout.js" strategy="lazyOnload" />
<Button onClick={pay} disabled={pending}>{pending ? "Please wait..." : label}</Button>
<p aria-live="polite" className="mt-2 text-muted">{message}</p>
</div>
);
}The same file declares a small TypeScript type for window.Razorpay. The event page shows PayButton for paid meetups with seats left, RsvpButton for free ones, and "You have a ticket" once paid. toggleRsvp also gained one line, because a free RSVP on a paid meetup would be a back door: if (event.priceInPaise > 0) return { status: null, message: "This is a paid meetup. Buy a ticket to book a seat." };. In test mode, Checkout accepts Razorpay's published test cards and the test UPI id success@razorpay.
Step 5: Verify the Checkout signature
When a payment succeeds, Checkout calls handler with razorpay_payment_id, razorpay_order_id and razorpay_signature. The signature is an HMAC: a hash of a message mixed with a secret key. Only someone who knows RAZORPAY_KEY_SECRET (Razorpay and your server) can produce the right value for order_id|payment_id. Create lib/razorpay-signature.ts, with no server-only import so tests can load it:
import { createHmac, timingSafeEqual } from "node:crypto";
// Compare two hex strings in constant time, so timing reveals nothing about the right answer.
function safeEqualHex(expected: string, received: string): boolean {
const a = Buffer.from(expected, "hex");
const b = Buffer.from(received, "hex");
return a.length === b.length && a.length > 0 && timingSafeEqual(a, b);
}
// Checkout handler: HMAC-SHA256 of "order_id|payment_id" with the key secret.
export function verifyPaymentSignature(orderId: string, paymentId: string, signature: string, keySecret: string): boolean {
const expected = createHmac("sha256", keySecret).update(`${orderId}|${paymentId}`).digest("hex");
return safeEqualHex(expected, signature);
}
// Webhooks: HMAC-SHA256 of the raw request body with the webhook secret.
export function verifyWebhookSignature(rawBody: string, signature: string, webhookSecret: string): boolean {
const expected = createHmac("sha256", webhookSecret).update(rawBody).digest("hex");
return safeEqualHex(expected, signature);
}timingSafeEqual takes the same time whether the first character or the last one differs, so an attacker cannot guess a signature one character at a time by measuring replies. We checked our functions against the helpers inside the razorpay package with a script, scripts/check-signature.mts, using test values only:
signature f4cf4b1177613b5741dae3b60bcfd8d8ef5ab83211de425bcfd1462dace2748a ours true razorpay true other order false wrong key false webhook true true tampered false
Both implementations agree. A signature made for one order does not work for another, a guessed key fails, and changing one number in a webhook body breaks its signature.
The confirmPayment action uses it, and it trusts nothing from the browser until the check passes:
export async function confirmPayment(response: CheckoutResponse): Promise<{ ok: boolean; message: string }> {
const user = await requireUser();
const { razorpay_order_id: orderId, razorpay_payment_id: paymentId, razorpay_signature: signature } = response;
if (![orderId, paymentId, signature].every((v) => typeof v === "string")) return { ok: false, message: "Bad request." };
// The order must exist in OUR database and belong to THIS user.
const payment = await findPayment(orderId);
if (!payment || payment.userId !== user.id) return { ok: false, message: "Unknown order." };
if (!verifyPaymentSignature(orderId, paymentId, signature, process.env.RAZORPAY_KEY_SECRET!)) {
return { ok: false, message: "Payment could not be verified." };
}
const result = await markPaid(orderId, paymentId);
updateTag(`rsvps:${payment.event.slug}`);
return result === "paid" || result === "already"
? { ok: true, message: "Payment received. Your seat is booked!" }
: { ok: false, message: "Payment could not be verified." };
}Razorpay's docs say to build the string from the order id stored on your server. Looking the order up in our own table first does exactly that.
Step 6: Book the seat exactly once
Both the handler and the webhook call markPaid. Either can arrive first, and webhooks may arrive more than once. Make the booking safe to repeat:
export async function markPaid(orderId: string, paymentId: string, amountInPaise?: number): Promise<MarkPaidResult> {
return db.$transaction(async (tx) => {
const payment = await tx.payment.findUnique({ where: { razorpayOrderId: orderId } });
if (!payment) return "unknown";
if (amountInPaise !== undefined && amountInPaise !== payment.amountInPaise) return "mismatch";
// Only a CREATED row can become PAID, so a second caller updates 0 rows.
const { count } = await tx.payment.updateMany({
where: { id: payment.id, status: "CREATED" },
data: { status: "PAID", razorpayPaymentId: paymentId },
});
if (count === 0) return "already";
await tx.rsvp.upsert({
where: { eventId_userId: { eventId: payment.eventId, userId: payment.userId } },
update: { status: "GOING" },
create: { eventId: payment.eventId, userId: payment.userId, status: "GOING" },
});
return "paid";
});
}Idempotent means "doing it twice has the same effect as doing it once", like pressing a lift button that is already lit. The where: { status: "CREATED" } condition turns "check, then update" into one atomic statement, and the RSVP is an upsert, so it cannot be duplicated either.
Step 7: The webhook
Create app/api/webhooks/razorpay/route.ts. Razorpay signs the raw body and its docs warn against parsing it first, because re-serialising JSON can change the bytes:
export async function POST(request: Request) {
// 1. Verify the signature on the RAW body, before parsing anything.
const raw = await request.text();
const signature = request.headers.get("x-razorpay-signature") ?? "";
if (!verifyWebhookSignature(raw, signature, process.env.RAZORPAY_WEBHOOK_SECRET!)) {
return jsonError(400, "BAD_SIGNATURE", "Signature check failed.");
}
// 2. Idempotency: remember each event id once. A repeat delivery is acknowledged and skipped.
const eventId = request.headers.get("x-razorpay-event-id");
if (!eventId) return jsonError(400, "NO_EVENT_ID", "Missing event id.");
const body = JSON.parse(raw) as RazorpayWebhook;
try {
await db.webhookEvent.create({ data: { id: eventId, type: body.event } });
} catch (error) {
if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === "P2002") {
return Response.json({ status: "duplicate" });
}
throw error;
}
// 3. Act only on the events EventHub cares about.
const payment = body.payload.payment?.entity;
if (body.event === "payment.captured" && payment && payment.currency === "INR") {
const result = await markPaid(payment.order_id, payment.id, payment.amount);
const row = await findPayment(payment.order_id);
if (row) revalidateTag(`rsvps:${row.event.slug}`, "max");
return Response.json({ status: result });
}
return Response.json({ status: "ignored" });
}The x-razorpay-event-id header is unique per event, so storing it with a primary key makes a repeat delivery fail with P2002, which we answer with 200 and skip. A webhook passes the amount Razorpay actually captured, and markPaid compares it with the stored amount. It uses revalidateTag, not updateTag, because this is a Route Handler. In the Dashboard you would add the URL https://your-domain/api/webhooks/razorpay with the payment.captured event and your webhook secret. Razorpay cannot reach localhost, so we played Razorpay ourselves.
Step 8: Test it for real
We inserted a CREATED payment row for Meera's ₹149 Pune ticket with the test order id order_TEST1234567890, as createOrderFor would have done. Then scripts/send-webhook.mts built a payment.captured body, signed it with RAZORPAY_WEBHOOK_SECRET exactly as Razorpay does, and posted it to the running app. The last argument tamper changes the amount after signing:
npx tsx scripts/send-webhook.mts evt_test_001 order_TEST1234567890 pay_TEST0987654321 14900 tamper
npx tsx scripts/send-webhook.mts evt_test_001 order_TEST1234567890 pay_TEST0987654321 14900
npx tsx scripts/send-webhook.mts evt_test_001 order_TEST1234567890 pay_TEST0987654321 14900
npx tsx scripts/send-webhook.mts evt_test_002 order_TEST1234567890 pay_TEST0987654321 14900
npx tsx scripts/send-webhook.mts evt_test_003 order_TEST_UNKNOWN pay_TEST1 14900evt_test_001 (tampered) -> 400 {"error":{"code":"BAD_SIGNATURE","message":"Signature check failed."}}
evt_test_001 -> 200 {"status":"paid"}
evt_test_001 -> 200 {"status":"duplicate"}
evt_test_002 -> 200 {"status":"already"}
evt_test_003 -> 200 {"status":"unknown"}Read it line by line. The tampered body was refused before anything was stored. The genuine one booked the seat. The same delivery again was a duplicate. A different event about the same payment found the row already PAID and changed nothing. An order EventHub never created did nothing. PostgreSQL afterwards held one PAID row with pay_TEST0987654321, three WebhookEvent rows, and one RSVP for Meera, not two. Her meetup page showed 1 going · 39 seats left | You have a ticket. See you there!.
Try it: verify a signature in the browser
The browser's Web Crypto API can compute the same HMAC. This shows why a forged confirmation fails. (In a real app the secret never reaches the browser; here it is a test value.)
import { createRoot } from "react-dom/client";
async function hmacHex(secret, message) {
const enc = new TextEncoder();
const key = await crypto.subtle.importKey("raw", enc.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
const sig = await crypto.subtle.sign("HMAC", key, enc.encode(message));
return [...new Uint8Array(sig)].map((b) => b.toString(16).padStart(2, "0")).join("");
}
const keySecret = "test_secret_only_for_learning"; // TEST value only
const fromRazorpay = "f4cf4b1177613b5741dae3b60bcfd8d8ef5ab83211de425bcfd1462dace2748a";
const cases = [
["genuine", "order_TEST1234567890", "pay_TEST0987654321"],
["swapped order", "order_SOMEONEELSE00001", "pay_TEST0987654321"],
["fake payment", "order_TEST1234567890", "pay_FAKE0000000000"],
];
const lines = [];
for (const [label, orderId, paymentId] of cases) {
const expected = await hmacHex(keySecret, `${orderId}|${paymentId}`);
const line = `${label.padEnd(14)} ${expected.slice(0, 16)}... ${expected === fromRazorpay ? "VALID" : "REJECT"}`;
console.log(line);
lines.push(line);
}
createRoot(document.getElementById("root")).render(<pre>{lines.join("\n")}</pre>);genuine f4cf4b1177613b57... VALID swapped order d4e935c28af7c25c... REJECT fake payment 984e6c3698c79037... REJECT
The genuine value matches the signature our Node.js script printed earlier. Change one character of keySecret and even the genuine case is rejected.
Common mistakes
- Sending the amount from the browser. The client can change it to ₹1. Read the price from the database on the server.
- Booking the seat in the Checkout
handlerwithout a server check. The handler runs in the browser and can be faked. Verify the signature on the server. - Parsing the webhook body before verifying. Sign-check the raw text; re-serialised JSON may differ by one byte.
- Comparing signatures with
===. UsetimingSafeEqual. - Processing every webhook delivery. Record
x-razorpay-event-idand makemarkPaida no-op the second time. - Live keys in development. Use
rzp_test_keys until launch, and keep all three secrets out of Git and out ofNEXT_PUBLIC_.
Interview questions
1. Why must the payment order be created on the server?
The server reads the price from its own database and attaches the order to the signed-in user. If the browser created the order or sent the amount, a user could change the price. The secret key needed to call the Orders API must also stay on the server.
2. How do you verify a Razorpay payment after Checkout succeeds?
Compute HMAC-SHA256 of order_id|payment_id with the key secret, using the order id stored on your server, and compare it with razorpay_signature in constant time. Only if they match do you mark the order paid. A webhook is verified the same way, using the raw body and the webhook secret.
3. What does idempotency mean for a payment webhook, and how do you implement it?
Processing the same event many times must have the same effect as processing it once, because providers retry deliveries. Store each event id under a unique constraint and skip repeats, and make the state change conditional, for example "update only rows still CREATED".
4. Why do both the Checkout handler and a webhook exist?
The handler gives the user instant feedback, but it depends on their browser staying open. The webhook comes from Razorpay's servers, so the order is still marked paid if the tab closed or the network dropped. With idempotent code, whichever arrives second changes nothing.
Key points
- The server creates orders with
amountin paise from PostgreSQL; the browser sends only the meetup slug. - Card and UPI details go from the browser to Razorpay, never through EventHub.
- Verify
order_id|payment_idand webhook bodies with HMAC-SHA256 andtimingSafeEqual. - Make bookings idempotent with unique constraints, stored event ids and conditional updates.
- Use
rzp_test_keys and test values while building; keep every secret server-only. - Test the webhook by signing your own test payloads, including tampered and repeated ones.
Exercise
Razorpay also sends payment.failed. Handle it in the webhook: if the payment's order is still CREATED, set its status to FAILED (an atomic updateMany), so that createOrderFor makes a fresh order next time instead of reusing a failed one. Then write the three send-webhook style calls you would use to test it, and say what each should return.
Show solution
// app/api/webhooks/razorpay/route.ts, after the idempotency check
if (body.event === "payment.failed" && payment) {
const { count } = await db.payment.updateMany({
where: { razorpayOrderId: payment.order_id, status: "CREATED" },
data: { status: "FAILED" },
});
return Response.json({ status: count === 1 ? "failed" : "ignored" });
}createOrderFor already reuses only CREATED rows, so after this a retry creates a new order. Tests (with a script that can send payment.failed): a fresh failure event for a CREATED order returns {"status":"failed"}; the same event id again returns {"status":"duplicate"}; a failure event for an order that is already PAID returns {"status":"ignored"}, so a late failure can never cancel a good payment.
Quick Quiz
1. Where should the ticket amount for an order come from?
Anything from the client can be changed; the database price cannot.
2. What does Razorpay sign in the Checkout response?
Recompute the HMAC on the server with the stored order id and compare.
3. The same payment.captured webhook arrives twice. What should EventHub do the second time?
Storing the event id under a unique key makes repeats harmless.
4. Why does the webhook read await request.text() before JSON.parse?
Verify the raw body first, then parse it.
Learn Next.js Full Stack with a mentor
Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
