Razorpay webhook HMAC verification is a cryptographic integrity check using HMAC-SHA256 over the unparsed HTTP request body, paired with event-ID deduplication to prevent spoofed payment confirmations and replay attacks.
Quick Answer: To secure Razorpay webhooks against forged payloads and replay attacks in 2026, compute HMAC-SHA256 strictly over the raw request bytes (never re-serialized JSON), compare using a constant-time equality check, and enforce an atomic SETNX lock on x-razorpay-event-id backed by a unique payment_id database constraint.
Key Architecture Takeaways
- Raw Body Only: Express
express.json()or Laravel JSON middleware alters whitespace and key order, breakingX-Razorpay-Signaturevalidation silently. - Event-ID Replay Guard: Lock
x-razorpay-event-idin Valkey for 72 hours (or store it in a unique SQL column) so intercepted or retried deliveries cannot double-credit wallets. - Constant-Time Comparison: Always use
crypto.timingSafeEqual(Node.js) orhash_equals(PHP) to block timing side-channel leaks. - Verify Amount & Currency: Never trust
payment.capturedaloneโassertamount === expected_order_amount_paiseandcurrency === 'INR'before unlocking digital products.
flowchart TD
A[Razorpay POST /webhooks/razorpay] --> B[Capture Raw Bytes Buffer]
B --> C{HMAC-SHA256 == X-Razorpay-Signature?}
C -->|No| D[Return 401 Unauthorized + Alert]
C -->|Yes| E{x-razorpay-event-id Seen?}
E -->|Yes| F[Return 200 OK Idempotent Skip]
E -->|No| G[Verify Order Amount Paise & Status]
G --> H[Atomic DB Transaction: Credit Order]
H --> I[Return 200 OK]
Why Broken Webhook Guards Cost Indian SaaS Founders Real Money
I built and audited Razorpay checkout and webhook pipelines for my own digital product store (deepakbagada.in/products) and over a dozen Indian SaaS clients from Junagadh to Bengaluru. Almost every payment bug I rescue falls into one of two traps: either signature verification fails in production because middleware parsed the JSON first, or a missing replay guard lets a retry double-credit a customer's wallet.
War Story 1 โ The Re-Serialized JSON Bug That Dropped 140 Paid Orders:
A Vadodara ed-tech founder migrated their Express.js backend and added a global app.use(express.json()) middleware above their Razorpay webhook route. When they verified the signature using JSON.stringify(req.body), floating-point formatting and key spacing differed by two bytes from Razorpay's raw payload. Every single webhook returned 400 Invalid Signature for six hours during a weekend webinar launch, leaving 140 paying students locked out of their courses until we switched the route to express.raw({ type: 'application/json' }).
War Story 2 โ The Double-Credited Wallet from a 5xx Retry:
A Jaipur SaaS client processed payment.captured, credited the user's API wallet inside an un-transactional block, and then timed out while sending a confirmation email. Razorpay's retry engine re-sent the exact webhook 5 minutes later. Without an x-razorpay-event-id idempotency guard, the user received โน4,999 worth of credits twice for a single UPI payment.
Runnable Production Code: Raw-Body HMAC Verification + Replay Guard (Node.js & PHP)
Here are the exact verification handlers I deploy in production across Node.js/Express and Laravel/PHP stacks.
src/routes/razorpayWebhook.mjs โ Node.js Raw-Buffer Verification + Valkey Lock
import crypto from "node:crypto";
import express from "express";
export function createRazorpayWebhookRouter({ valkey, db, webhookSecret }) {
const router = express.Router();
// Mount BEFORE global express.json() or use express.raw() on this route
router.post(
"/webhooks/razorpay",
express.raw({ type: "application/json" }),
async (req, res) => {
const signature = req.header("x-razorpay-signature");
const eventId = req.header("x-razorpay-event-id");
const rawBody = req.body; // Buffer
if (!signature || !eventId || !Buffer.isBuffer(rawBody)) {
return res.status(400).json({ error: "Missing raw body or Razorpay headers" });
}
const expectedHex = crypto
.createHmac("sha256", webhookSecret)
.update(rawBody)
.digest("hex");
const sigBuf = Buffer.from(signature, "utf8");
const expBuf = Buffer.from(expectedHex, "utf8");
if (sigBuf.length !== expBuf.length || !crypto.timingSafeEqual(sigBuf, expBuf)) {
return res.status(401).json({ error: "Invalid HMAC signature" });
}
// Replay attack & retry guard: 72-hour atomic lock on eventId
const locked = await valkey.set(`rzp:evt:${eventId}`, "1", "NX", "EX", 259200);
if (!locked) {
return res.status(200).json({ status: "duplicate_ignored" });
}
const event = JSON.parse(rawBody.toString("utf8"));
if (event.event === "payment.captured") {
const payment = event.payload.payment.entity;
await db.fulfillOrderAtomic({
razorpayOrderId: payment.order_id,
razorpayPaymentId: payment.id,
amountPaise: payment.amount,
currency: payment.currency,
});
}
return res.status(200).json({ status: "processed" });
}
);
return router;
}
app/Http/Controllers/RazorpayWebhookController.php โ Laravel 11/12 Constant-Time Guard
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class RazorpayWebhookController extends Controller
{
public function handle(Request $request)
{
$rawBody = $request->getContent();
$signature = $request->header('X-Razorpay-Signature', '');
$eventId = $request->header('X-Razorpay-Event-Id', '');
$secret = config('services.razorpay.webhook_secret');
$expected = hash_hmac('sha256', $rawBody, $secret);
if (!hash_equals($expected, $signature)) {
return response()->json(['error' => 'Invalid signature'], 401);
}
if ($eventId === '') {
return response()->json(['error' => 'Missing event id'], 400);
}
$inserted = DB::table('webhook_events')->insertOrIgnore([
'provider' => 'razorpay',
'event_id' => $eventId,
'created_at' => now(),
]);
if ($inserted === 0) {
return response()->json(['status' => 'duplicate_ignored'], 200);
}
$payload = json_decode($rawBody, true, 512, JSON_THROW_ON_ERROR);
if (($payload['event'] ?? '') === 'payment.captured') {
$payment = $payload['payload']['payment']['entity'];
// Fulfill order inside DB::transaction() checking amount_paise === order.amount_paise
}
return response()->json(['status' => 'ok'], 200);
}
}
Razorpay Webhook Security Matrix: Attack Vectors & Exact Defenses
| Threat Vector | What Happens Without Guard | Exact Production Defense | Latency Cost |
|---|---|---|---|
Forged payment.captured POST |
Attacker unlocks paid tier for โน0 | HMAC-SHA256 on raw bytes + timingSafeEqual |
< 0.2 ms |
| Intercepted Payload Replay | Same event re-sent to double-credit wallet | SETNX rzp:evt:{id} + Unique SQL index |
< 1.5 ms |
| JSON Middleware Mutation | Legitimate payments fail signature check | express.raw() / $request->getContent() |
0 ms |
| Paise Tampering / Partial Pay | โน1 order unlocks โน9,999 product | Server-side payment.amount === order.amount |
< 0.5 ms |
| Slow Email Blocking Webhook | Razorpay marks delivery failed & retries | Enqueue email/PDF generation after DB::commit() |
Saves 1,200 ms |
Operational Verification Before Going Live on Razorpay Production Keys
Run these four checks on staging before flipping from Razorpay Test Mode to Live Mode:
- Separate Secrets Per Environment: Razorpay's dashboard generates distinct webhook secrets for Test Mode and Live Mode. Store them separately and fail application boot if
RAZORPAY_WEBHOOK_SECRETis empty. - Test Out-of-Order Events:
payment.authorizedandpayment.capturedcan arrive milliseconds apart or out of order. Ensure your state machine never downgrades acapturedorder back toauthorized. - Log Rejected Signatures Without Secret Leakage: Record the client IP,
x-razorpay-event-id, and HTTP status on401rejections, but never log the computedexpectedHexorwebhookSecretto stdout. - Reconcile Missed Webhooks Nightly: Run a cron job at 2:00 AM IST querying Razorpay's
/v1/ordersAPI for anypendingorders older than 15 minutes so rare ISP outages never leave a customer unfulfilled.
When NOT to Use This Architecture
- Pure Client-Side Static Pages: If you have no backend server at all, use Razorpay Payment Links or Payment Pages instead of building a custom webhook listener.
- Polling-Only Low-Volume Flows: Never rely solely on frontend
handlercallbacks without webhooksโIndian UPI users frequently close their browser tab inside GPay/PhonePe before returning to your checkout page.
โก Implementation Resources & Commercial Architecture:
Selling digital products or SaaS subscriptions in India? Download India Offer & Pricing Kit (โน699 โ milestone agreements & scope protection) or Indian D2C ROAS Anti-RTO Engine (โน899). Validate webhook JSON structures with our free JSON Formatter or compute tax splits via GST Calculator. For custom payment & SaaS builds (โน3Lโโน25L), connect at Deepak Bagada Systems Advisory.
Authoritative Primary Sources & Research Citations
- Razorpay Webhooks Validation & Signature Documentation
- Node.js
crypto.timingSafeEqualSecurity Reference - OWASP Webhook Security Cheat Sheet
Related Engineering Guides
- WhatsApp Cloud API AI Agent: 2026 Webhook Architecture
- PostgreSQL 17 JSONB vs MongoDB: 2026 Query Benchmark
- India Offer & Pricing Kit
- AI Development Services in India
Frequently Asked Questions
Why does Razorpay webhook verification fail when using req.body in Express.js?
Because express.json() parses and re-serializes the JSON, altering whitespace or Unicode escaping. You must pass the exact unparsed Buffer from express.raw({ type: 'application/json' }) into crypto.createHmac.
Is X-Razorpay-Signature enough to stop replay attacks?
No. A valid signature proves the payload came from Razorpay, not that it is the first time you are processing it. You must also deduplicate x-razorpay-event-id and enforce a unique payment_id constraint.
What HTTP status code should I return for a duplicate Razorpay event?
Return 200 OK immediately after confirming it is a duplicate. Returning 4xx or 5xx tells Razorpay the delivery failed, triggering up to 24 hours of retries.
Should I verify Razorpay webhooks in addition to the frontend checkout signature?
Yes. Users on mobile UPI apps often drop off before the frontend callback fires, making the server-to-server webhook your true source of truth.
Bottom Line
A single unverified or non-idempotent webhook endpoint can leak inventory or double-credit wallets overnight. Verify HMAC-SHA256 on the raw byte buffer, lock x-razorpay-event-id for 72 hours, and assert amount in paise inside an atomic transaction. Grab India Offer & Pricing Kit or schedule a backend security review.