Razorpay Webhook HMAC: 2026 Replay Attack Guard Guide
Book Call
WEB DEV ยท 8 min read ยท 1,463 words

Razorpay Webhook HMAC: 2026 Replay Attack Guard Guide

TL;DR ยท Key Engineering Summary

Razorpay webhook HMAC verification & replay attack guard (2026): raw-body SHA-256 check, x-razorpay-event-id Valkey lock, runnable Node/PHP code, and tests.

Author: Deepak Bagada Topic: WEB DEV Updated: Dec 2026

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, breaking X-Razorpay-Signature validation silently.
  • Event-ID Replay Guard: Lock x-razorpay-event-id in 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) or hash_equals (PHP) to block timing side-channel leaks.
  • Verify Amount & Currency: Never trust payment.captured aloneโ€”assert amount === expected_order_amount_paise and currency === '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:

  1. 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_SECRET is empty.
  2. Test Out-of-Order Events: payment.authorized and payment.captured can arrive milliseconds apart or out of order. Ensure your state machine never downgrades a captured order back to authorized.
  3. Log Rejected Signatures Without Secret Leakage: Record the client IP, x-razorpay-event-id, and HTTP status on 401 rejections, but never log the computed expectedHex or webhookSecret to stdout.
  4. Reconcile Missed Webhooks Nightly: Run a cron job at 2:00 AM IST querying Razorpay's /v1/orders API for any pending orders 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 handler callbacks 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

Related Engineering Guides


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.

// FREE IN-BROWSER UTILITIES

Test schemas, JSON, regex & tokens in real time

Use Deepak's 25+ client-side developer utilities โ€” zero ads, zero server uploads.

Open Developer Tools โ†’

KEEP READING

โ† All journal articles Book Architecture Call โ†’
Book Architecture Call