How Payment Webhooks Prove They Are Real, With Python Code
The problem
Your server has a URL like https://yourapp.com/webhooks/razorpay. When a customer's ₹499 renewal goes through, Razorpay sends a POST request there saying subscription.charged, and your code unlocks another month of Pro.
Now think about who else can send a POST request to that URL. Everyone. It is a public address on the internet. If your handler believes whatever JSON arrives, then anyone who guesses the URL and the payload shape gets a free subscription for the cost of one curl command.
So a webhook has to prove two things before you act on it: that Razorpay really sent it, and that you have not already acted on it. This part covers how Razorpay does both, what can still go wrong (duplicates, late arrivals, retries, replays), and then shows Python code we wrote and ran on our own machine for this post. It uses only the standard library, and the output is pasted exactly as it came out.
What a webhook is, in Razorpay's words
Razorpay's docs describe webhooks as push instead of pull. Without them, you would keep asking the API "has anything changed?" With them, Razorpay sends an HTTP POST with a JSON payload to the URL you configured, whenever an event you subscribed to happens.
A few setup facts from the docs:
- You configure webhooks in the Dashboard, with separate URLs for Live mode and Test mode.
- Webhook URLs must use port 80 or 443.
- Razorpay's production environment does not support TLS 1.0 or 1.1. Use TLS 1.2 or later.
- You can optionally allowlist Razorpay's webhook IP addresses.
- For testing on your laptop, several tunnelling and request bin domains are blocked, including
ngrok.io,loca.lt,webhook.siteandrequestbin.com. Razorpay suggestszrokfor localhost.
The events a subscription app cares about
Razorpay's full list covers orders, payments, refunds, disputes, invoices, subscriptions, settlements, payouts and more. For a subscription product, these are the ones that matter most:
| Event | When it fires |
|---|---|
subscription.authenticated | The first payment on the subscription is made (auth amount, upfront amount, plan amount, or a mix) |
subscription.activated | Moves to active from authenticated, pending or halted |
subscription.charged | Every successful charge |
subscription.pending | A charge failed. Fires again on each failed retry |
subscription.halted | All retries used up |
subscription.paused / .resumed | Paused or resumed |
subscription.cancelled | Cancelled |
subscription.completed | All invoices generated, subscription finished |
subscription.updated | Updated, with no state change |
payment.authorized / .captured / .failed | A payment is authorised, captured, or fails |
invoice.paid | An invoice is paid |
refund.created / .processed / .failed | A refund changes state |
Every event arrives in the same envelope. Razorpay's sample payloads show a top level entity: "event", an account_id, the event name, a contains list saying which entities are inside, the payload itself, and a created_at Unix timestamp for the event. Subscription events always carry the subscription entity, and also a payment entity "if a payment attempt was made before the event was triggered".
Proof one: the signature
When you set a webhook secret in the Dashboard, Razorpay signs every request with it. The signature goes in the X-Razorpay-Signature header. Razorpay's validation page gives the recipe in one sentence: HMAC with SHA256, "with your webhook secret set as the key and the webhook request body as the message."
HMAC is a way of mixing a secret into a hash. Only someone who knows the secret can produce the right output for a given message. Change one byte of the message, and the output changes completely. Without the secret, there is no practical way to forge a matching signature for a new body.
So your handler does the same calculation on what it received, and compares. Match: Razorpay sent it, and nobody changed it on the way. No match: drop it.
Two practical notes from the docs. First, the webhook secret is not your API key secret. Razorpay's security checklist lists them separately: the key secret signs Checkout callbacks, the webhook secret signs webhooks. Second, if you change your webhook secret, retries of older events were signed with the old one. Razorpay says to use the old secret when validating those, or you will get mismatches.
Why it has to be the raw bytes
This is the bug that bites almost everyone once. Razorpay's security checklist says to verify the signature "on the raw body, before parsing it", and lists "Webhook verified after parsing" as a common gap, with the consequence: "Re-serialised JSON never matches."
Here is why. The signature covers bytes, not meaning. These two strings hold the same data:
{"amount":49900,"currency":"INR"}
{"amount": 49900, "currency": "INR"}
But they are different bytes, so they produce different HMACs. Many web frameworks helpfully parse the JSON body for you before your code runs. If you then turn that parsed object back into a string and sign it, the spacing, key order or number formatting can come out differently from what Razorpay sent, and the check fails on perfectly genuine webhooks. Step 4 of the demo below shows exactly this happening.
The fix is to grab the raw request body as bytes before anything parses it, verify, and only then parse.
Why the comparison has to be timing safe
A normal string comparison stops at the first character that differs. That means a wrong guess that starts with the right characters takes a tiny bit longer to reject. In principle, an attacker who can time many requests can use that difference to work out a valid signature character by character.
The defence is a comparison that does not stop early. In Python that is hmac.compare_digest, which the Python docs describe as "designed to prevent timing analysis by avoiding content-based short circuiting behaviour", and they recommend it over == for exactly this job. It is also what Razorpay's own Python SDK uses: we downloaded version 2.0.1 of the razorpay package and read its utility.py, and its verify_signature method computes the HMAC SHA256 hex digest and checks it with hmac.compare_digest.
Proof two: you have not seen it before
A valid signature proves Razorpay sent the request. It does not prove this is the first time you got it.
Razorpay is explicit that duplicates are normal. Its best practices page says it follows "at-least-once delivery semantics": if it does not get a successful response, it sends the webhook again. And there is a timer. If your server accepts the event but takes longer than 5 seconds to respond, Razorpay marks the session as timed out, assumes the webhook was not processed, and sends it again.
Think about what that means for a slow handler. You receive subscription.charged, start updating the database, send a welcome email, and respond after 6 seconds. Razorpay never saw your success, so it sends the same event again. If your code is naive, the customer gets two emails and two months of credit.
Razorpay's answer is the x-razorpay-event-id header. Its value "is unique per event". Store every event ID you have processed. When one shows up again, return 2xx and do nothing.
In real code, put the event ID in a database table with a unique constraint, and record it in the same transaction as the work it triggers. If you mark it as seen first and then crash halfway through the work, the retry will be skipped and the work will never finish. Also keep the slow parts (emails, PDF invoices) out of the request: record the event, respond quickly, and do the rest in a background job, so you stay well under 5 seconds.
When events arrive in the wrong order
Razorpay says plainly that you "may not always receive the webhooks in the order" they happened. Its own example is a payment, where you should see payment.authorized and then payment.captured, but "the above order may not be followed at all times." For payouts, it adds that once you have seen a final state, any webhook received after it should be ignored.
For subscriptions, the dangerous case looks like this. A renewal fails, then the retry succeeds. Razorpay sends subscription.pending and then subscription.charged. If the pending one is delayed and lands second, a naive handler sets the customer back to pending and maybe locks them out, even though they just paid.
Two defences, which work well together:
- Compare timestamps. The event envelope has a
created_at. Keep thecreated_atof the last event you applied to each subscription, and skip events older than that. The timestamp is inside the signed body, so an attacker cannot change it. One caution: it is in whole seconds, so two events in the same second tie. - Ask the source. When an event changes access, you can fetch the subscription from the API and store whatever
statusit reports right now. The webhook becomes a nudge to look, not the final word.
Retries, backoff and the 24 hour cliff
Any response other than 2xx counts as a delivery failure. Razorpay then retries "in exponential backoff policy for 24 hours after the event creation timestamp". Exponential backoff means the gaps between attempts grow: quick retries at first, then longer and longer waits. Razorpay does not publish the exact intervals in the pages we read, so do not build anything that depends on a specific retry time.
The part that matters operationally is what happens at the end. If deliveries keep failing for 24 hours, Razorpay disables the webhook. It emails the Alert Email Address you set during setup (or the account email if you did not set one), and you have to turn the webhook back on from the Dashboard after fixing the problem. Until you do, your app hears nothing, not even for new events.
sequenceDiagram participant R as Razorpay participant S as Your server participant D as Your database R->>S: POST event (X-Razorpay-Signature, x-razorpay-event-id) Note over S: down, or slower than 5 seconds S--xR: timeout or non-2xx Note over R: retry with exponential backoff R->>S: POST same event, same event id S->>S: verify HMAC on raw body S->>D: event id new? apply change, store id S-->>R: 200 OK R->>S: POST same event again (at least once delivery) S->>D: event id seen S-->>R: 200 OK, nothing changed Note over R,S: if every attempt fails for 24 hours: webhook disabled, alert email sent
So a 24 hour outage on your side is not just 24 hours of missed events. It switches the pipe off. Monitoring for non-2xx responses on your webhook route is worth an afternoon.

Replays, and what timestamps can and cannot do
A replay attack is simple. Someone captures one genuine, correctly signed webhook (from a leaked log file, say) and sends it to you again later. The signature is still valid, because the bytes have not changed. Signatures alone cannot stop this.
What stops it in Razorpay's design is the event ID check. A replayed request carries the same x-razorpay-event-id, so a handler that remembers IDs rejects it. Step 5 of the demo shows exactly that: a perfectly signed request, turned away because its ID was already used.
Could you also reject old events by time? The pages we read document the signature header and the event ID header, and no separate signed timestamp header. But the body's created_at is signed, so you could refuse events older than some window. If you do, the window has to be longer than 24 hours, because Razorpay legitimately retries for that long. For the same reason, keep stored event IDs for at least that long. In practice the event ID table, kept permanently, is the simpler and stronger defence.
The other signature: Checkout
Webhooks are not the only signed thing. When a customer completes the authorisation transaction in Checkout, Razorpay hands your frontend three values: razorpay_payment_id, razorpay_subscription_id and razorpay_signature. Your frontend sends them to your server, and your server must verify them before trusting the browser's word.
Razorpay's Subscriptions integration guide says to build an HMAC SHA256 hex digest with your key secret, using razorpay_payment_id and the subscription_id. And it is firm on one point: take the subscription ID from your own server, "Do not use the razorpay_subscription_id returned by Checkout." The browser is the attacker's territory. If you trust its ID, someone could pair a real cheap payment with a different subscription.
Now the honest part about the exact string. On that guide, the code block that shows the formula did not render when we read the page, so the docs we could read do not spell out the string format for subscriptions. Here is what we could confirm, and from where:
| Flow | Exact string signed | Where it is confirmed |
|---|---|---|
| One time payment (Orders) | order_id + "|" + razorpay_payment_id | Written out in Razorpay's security best practices page |
| Subscription | razorpay_payment_id + "|" + subscription_id | Razorpay's official Python SDK, version 2.0.1: verify_subscription_payment_signature builds "{}|{}".format(payment_id, subscription_id). Not written out in the docs we could read |
Notice the order flips: order ID first for Orders, payment ID first for Subscriptions. If you copy an Orders example into a subscription flow, every verification will fail. Step 7 of the demo signs the subscription format, and step 8 checks it against the official SDK's own function.
sequenceDiagram participant B as Browser (Checkout) participant S as Your server B->>S: razorpay_payment_id, razorpay_subscription_id, razorpay_signature S->>S: load subscription_id from YOUR database S->>S: HMAC SHA256(key secret, payment_id + "|" + subscription_id) alt matches razorpay_signature S-->>B: OK, show "trial started" else no match S-->>B: reject end Note over S: still wait for the webhook before treating it as final
The demo: signing, verifying, rejecting
Here is the full script, saved as webhook_verify_demo.py. It uses only hmac, hashlib and json from Python's standard library. It never contacts Razorpay. The secrets and IDs are made up, and the payload is a trimmed version of the shape in Razorpay's sample subscription.charged event, with our ₹499 amount (49900 paise).
The last step optionally imports the official razorpay SDK to cross-check our results. If the SDK is not installed, that step prints "skipped" and everything else still runs.
python"""Webhook and checkout signature demo for the BlogLLM subscriptions series, part 4. Standard library only (hmac, hashlib, json). Nothing here talks to Razorpay. The secrets and IDs below are made up for the demo. The payload is shaped like the sample `subscription.charged` event in Razorpay's docs, trimmed down. Run: python3 webhook_verify_demo.py """ import hashlib import hmac import json WEBHOOK_SECRET = b"demo_webhook_secret_not_real" # set in the Dashboard per webhook KEY_SECRET = b"demo_key_secret_not_real" # your API key secret (Checkout) def sign(secret: bytes, message: bytes) -> str: """HMAC SHA256, hex digest. Same recipe Razorpay documents for X-Razorpay-Signature.""" return hmac.new(secret, message, hashlib.sha256).hexdigest() def signature_ok(raw_body: bytes, header_sig: str, secret: bytes = WEBHOOK_SECRET) -> bool: expected = sign(secret, raw_body) # compare_digest takes the same time wherever the first wrong character is return hmac.compare_digest(expected, header_sig) class WebhookReceiver: """The three checks a handler should make, in this order.""" def __init__(self): self.seen_event_ids = set() # use a database table with a UNIQUE key in real life self.last_applied = {} # subscription id -> event created_at we last applied self.status = {} # subscription id -> status we believe def handle(self, raw_body: bytes, headers: dict) -> str: # 1. Authenticity: check the signature on the exact bytes received if not signature_ok(raw_body, headers.get("X-Razorpay-Signature", "")): return "401 rejected: bad signature" # 2. Idempotency: same event id means we already did this work event_id = headers.get("x-razorpay-event-id", "") if event_id in self.seen_event_ids: return "200 ignored: duplicate event id " + event_id self.seen_event_ids.add(event_id) # Only now is it safe to parse event = json.loads(raw_body) sub = event["payload"]["subscription"]["entity"] # 3. Ordering: do not let an older event overwrite newer state if event["created_at"] < self.last_applied.get(sub["id"], 0): return "200 ignored: older than state already applied (%s)" % event["event"] self.last_applied[sub["id"]] = event["created_at"] self.status[sub["id"]] = sub["status"] return "200 applied: %s -> status %s" % (event["event"], sub["status"]) def make_event(name, status, created_at, amount=49900): event = { "entity": "event", "account_id": "acc_DEMO0000000001", "event": name, "contains": ["subscription", "payment"], "payload": { "subscription": {"entity": {"id": "sub_DEMO0000000001", "status": status}}, "payment": {"entity": {"id": "pay_DEMO0000000001", "amount": amount, "currency": "INR"}}, }, "created_at": created_at, } # This string is what goes over the wire. Its exact bytes get signed. return json.dumps(event, separators=(",", ":")).encode() def main(): rx = WebhookReceiver() print("== 1. Razorpay signs the raw body ==") body = make_event("subscription.charged", "active", 1767225600) sig = sign(WEBHOOK_SECRET, body) print("body bytes :", len(body)) print("signature :", sig) print("\n== 2. Genuine delivery ==") print(rx.handle(body, {"X-Razorpay-Signature": sig, "x-razorpay-event-id": "evt_demo_1"})) print("\n== 3. Tampered body: amount 49900 changed to 100 ==") tampered = body.replace(b'"amount":49900', b'"amount":100') print("bodies differ:", tampered != body) print(rx.handle(tampered, {"X-Razorpay-Signature": sig, "x-razorpay-event-id": "evt_demo_2"})) print("\n== 4. Same JSON, re-serialised by a framework (spaces added) ==") reserialised = json.dumps(json.loads(body)).encode() print("same data :", json.loads(reserialised) == json.loads(body)) print("same bytes :", reserialised == body) print("sig matches :", signature_ok(reserialised, sig)) print("\n== 5. Replay: the genuine request sent again, same event id ==") print(rx.handle(body, {"X-Razorpay-Signature": sig, "x-razorpay-event-id": "evt_demo_1"})) print("\n== 6. Out of order: an older pending event arrives late ==") late = make_event("subscription.pending", "pending", 1767225000) print(rx.handle(late, {"X-Razorpay-Signature": sign(WEBHOOK_SECRET, late), "x-razorpay-event-id": "evt_demo_0"})) print("status we hold:", rx.status["sub_DEMO0000000001"]) print("\n== 7. Checkout signature for a subscription ==") payment_id, subscription_id = "pay_DEMO0000000002", "sub_DEMO0000000001" checkout_sig = sign(KEY_SECRET, (payment_id + "|" + subscription_id).encode()) stored_sub_id = "sub_DEMO0000000001" # from YOUR database, not from the browser print("verify with stored id :", hmac.compare_digest( sign(KEY_SECRET, (payment_id + "|" + stored_sub_id).encode()), checkout_sig)) print("verify with other id :", hmac.compare_digest( sign(KEY_SECRET, (payment_id + "|" + "sub_DEMO0000000999").encode()), checkout_sig)) print("\n== 8. Cross-check against the official razorpay SDK, if importable ==") try: from razorpay.utility.utility import Utility u = Utility() print("SDK webhook check :", u.verify_webhook_signature(body.decode(), sig, WEBHOOK_SECRET.decode())) print("SDK subscription check :", u.verify_subscription_payment_signature({ "razorpay_subscription_id": subscription_id, "razorpay_payment_id": payment_id, "razorpay_signature": checkout_sig, "secret": KEY_SECRET.decode()})) except ImportError: print("razorpay SDK not installed, skipped") if __name__ == "__main__": main()
We ran it with Python 3.12.3, with the razorpay 2.0.1 package available for step 8:
$ python3 webhook_verify_demo.py
== 1. Razorpay signs the raw body ==
body bytes : 310
signature : a3181bb4810d46f6087601af19208db0de7999f3a1f5ed69dc0f723a44885316
== 2. Genuine delivery ==
200 applied: subscription.charged -> status active
== 3. Tampered body: amount 49900 changed to 100 ==
bodies differ: True
401 rejected: bad signature
== 4. Same JSON, re-serialised by a framework (spaces added) ==
same data : True
same bytes : False
sig matches : False
== 5. Replay: the genuine request sent again, same event id ==
200 ignored: duplicate event id evt_demo_1
== 6. Out of order: an older pending event arrives late ==
200 ignored: older than state already applied (subscription.pending)
status we hold: active
== 7. Checkout signature for a subscription ==
verify with stored id : True
verify with other id : False
== 8. Cross-check against the official razorpay SDK, if importable ==
SDK webhook check : True
SDK subscription check : True
What each step shows:
- Step 2: a genuine body with its genuine signature is accepted and applied.
- Step 3: change the amount from 49900 to 100, keep the old signature, and it is rejected. This is the free subscription attack from the start of this post, failing.
- Step 4: the same data, re-serialised with different spacing, no longer matches the signature. Nothing was tampered with. This is the raw bytes bug.
- Step 5: the exact genuine request sent a second time. The signature is valid, and it is still ignored, because the event ID was already used.
- Step 6: an older
pendingevent arriving after a newerchargedevent is skipped, and the status staysactive. - Steps 7 and 8: the Checkout signature verifies only with the subscription ID from our own records, and the official SDK agrees with both our webhook check and our subscription check.
A short checklist
- Read the raw body. Verify
X-Razorpay-Signaturewith the webhook secret before parsing. - Compare with a timing safe function.
- Store
x-razorpay-event-idwith a unique constraint, in the same transaction as the work. - Never let an older event overwrite newer state. When in doubt, fetch the subscription.
- Respond 2xx fast, well under 5 seconds. Push slow work to a background job.
- Alert on non-2xx responses before 24 hours of failures disable the webhook.
- Verify Checkout's
razorpay_signaturewith your key secret and your stored subscription ID, in thepayment_id|subscription_idorder.
What's next
Now your app can trust what it hears. The next question is what to do when what it hears is bad news. Next up: what happens when a renewal payment fails, from the first declined charge through retries, pending, halted, and the customers you lose without either side meaning to.
Sources
- About Webhooks, Razorpay docs (last modified Dec 2, 2026)
- Validate and Test Webhooks, Razorpay docs (updated 2026-12-05)
- Webhook Best Practices, Razorpay docs (updated 2026-10-08)
- All Webhook Events, Razorpay docs (last modified Dec 4, 2026)
- Subscriptions Webhook Events and sample payloads, Razorpay docs
- Security best practices, Razorpay docs (last modified Nov 12, 2026)
- Integrate With Subscriptions, Razorpay docs (last modified Oct 8, 2026)
- razorpay-python, Razorpay's official Python SDK on GitHub (we read
razorpay/utility/utility.pyin the 2.0.1 package from PyPI) - hmac: Keyed-Hashing for Message Authentication, Python 3.12 documentation
