In short
- Six gateways use five different ways to prove a webhook is real. What matters is what each proof covers.
- Razorpay and Cashfree sign the whole body. Only Cashfree also signs a timestamp, which stops old requests being replayed.
- PayU and Easebuzz hash only some fields. PhonePe and Juspay sign nothing in the body, so check the order with the gateway before you ship.
- Verify the raw bytes, de-duplicate on signed fields, and handle amounts as integer paise.
Written for: Backend developers taking payments in India.
A payment gateway tells your server that a customer paid by sending it a webhook: an HTTP request with the payment in the body. Your server reads it and marks the order paid. Anyone on the internet can send that same request to that same URL. The only thing that separates the real one from a forged one is the proof the gateway attaches to it.
I build payment software for a living, and I assumed that proof worked the same way everywhere. It does not. Six widely used Indian gateways, Razorpay, Cashfree, PhonePe, PayU, Juspay and Easebuzz, use five different schemes. Some sign every byte. Some sign a few fields. Two sign nothing in the body at all.
I read each gateway's docs and official SDK and wrote india-webhooks, a small open-source package that checks all six and returns one event shape. This post is what I learned doing it.
Six gateways, five schemes
| Gateway | Where the proof is | How it is made |
|---|---|---|
| Razorpay | X-Razorpay-Signature |
HMAC-SHA256 of the raw body, hex |
| Cashfree | x-webhook-signature |
HMAC-SHA256 of x-webhook-timestamp followed by the raw body, base64 |
| PayU |
hash form field |
SHA-512 of the salt and some form fields, joined with `\ |
| Easebuzz | {% raw %}hash form field |
The same idea as PayU, with a different field order |
| PhonePe | Authorization |
SHA-256 of username:password from your dashboard |
| Juspay | Authorization |
HTTP Basic auth with the username and password from your dashboard |
The difference that matters is not the hash function. It is what the proof covers.
Razorpay and Cashfree: the body is signed
Razorpay computes an HMAC of the request body with your webhook secret and puts it in a header. You compute the same HMAC over the bytes you received and compare. If one byte of the body changed, the values will not match.
Cashfree does the same, but puts a timestamp in front of the body before signing. That one change matters a lot. Cashfree's docs say to reject anything older than five minutes, so a request someone captured yesterday cannot be sent again today. Of the six, it is the only one with replay protection built into the signature.
src/providers/cashfree.ts
export async function cashfreeSignature(timestamp: string, body: Uint8Array, secret: string): Promise<string> {
return toBase64(await hmacSha256(utf8(secret), concatBytes(utf8(timestamp), body)));
}
Both are simple to verify. Both are also easy to get wrong in one specific way.
The raw body problem
The signature covers the exact bytes the gateway sent. Most web frameworks parse the body as JSON before your handler sees it. If you take that parsed object and turn it back into text, you get different bytes. Cashfree's own docs give the example: "payment_amount": 170.00 comes back as 170, and the signature no longer matches.
Express
// Wrong: the JSON parser has already thrown the original bytes away
app.post('/webhooks/razorpay', express.json(), (req, res) => {
const body = JSON.stringify(req.body); // not what Razorpay signed
});
// Right: keep the bytes for this route
app.post('/webhooks/razorpay', express.raw({ type: '*/*' }), async (req, res) => {
const result = await verifyWebhook('razorpay', {
rawBody: req.body, // a Buffer
headers: req.headers,
secret: process.env.RAZORPAY_WEBHOOK_SECRET!,
});
res.sendStatus(result.ok ? 200 : 400);
});
It usually goes wrong in a quiet way. Every test payload happens to re-serialise to the same text, so verification passes in development. Then a real payment with 170.00 fails in production. Or a developer sees the failures, decides the check is flaky, and turns it off.
PayU and Easebuzz: only some fields are signed
PayU and Easebuzz send webhooks as form posts, not JSON, with a hash field. The hash is a SHA-512 of your salt and a fixed list of fields joined with pipes. For PayU it is:
PayU reverse hash: the fields, in order
SALT|status||||||udf5|udf4|udf3|udf2|udf1|email|firstname|productinfo|amount|txnid|key
The order runs backwards compared with the request hash you send when starting a payment, which is why PayU calls it a reverse hash. The five empty slots after status are always empty. PayU's official SDK hard-codes them.
The important part is what is missing from that list. status, amount and txnid are covered. PayU's own payment id mihpayid, the payment mode, bank_ref_num and unmappedstatus are not. Anyone who has one real webhook can change those fields and the hash still matches.
india-webhooks does exactly that, and puts every field the hash does not cover into a separate event.unverified object. Your code then shows clearly which values were checked and which were not.
There is one more trap in form bodies. A field can appear twice: status=failure&status=success. Different parsers disagree on which copy wins. If the verifier hashes the first and your app reads the last, the check passes on a value your app never uses. The package rejects any body with a repeated field name, even when the copies are equal.
PhonePe and Juspay: nothing in the body is signed
This is the part that surprised me most. PhonePe's Authorization header is a SHA-256 of the username and password you typed into its dashboard. Juspay sends the same username and password as HTTP Basic auth. Neither one depends on the body.
That has two consequences. A valid header proves the sender knows your credentials, but says nothing about whether the body was changed. And because the PhonePe header is the same on every request, one leaked request is enough. Anyone who has it can attach it to any body they like, forever.
PhonePe's dashboard does offer a newer HMAC option, but the docs do not say which hash it uses, how it is encoded, or exactly which bytes are signed, and the official SDK has no code for it. I left it out rather than guess.
Try it yourself
Here are both kinds of check, running for real in your browser. On the Razorpay tab, change the amount and watch the signature fail. Then try “Parse and re-serialise”: the data is the same, but the bytes are not, so it fails too. On the PhonePe tab, make the same change and see the check still pass.
Run the live demo (real hashing, nothing is sent anywhere): https://mokshupadhyay.com/writing/indian-payment-webhooks#try-it-yourself
Webhooks arrive twice, late and out of order
Gateways send a webhook again when your server does not answer with a success in time, and Razorpay's and Juspay's docs say plainly that the same event can arrive more than once. Razorpay's also say events can arrive out of order. So a handler has to de-duplicate. The obvious key is the delivery id the gateway sends: x-razorpay-event-id or Cashfree's x-idempotency-key.
Both are headers, and neither signature covers them. Someone replaying a captured Razorpay request can put any value there and pass your de-duplication check. That is why india-webhooks builds event.id only from fields inside the signature, such as the event name, the payment id and the signed timestamp, and keeps the delivery id separately for logging.
A handler that holds up
const result = await verifyWebhook(provider, { rawBody, headers, secret });
if (!result.ok) return new Response(null, { status: 400 });
const { event } = result;
if (event.type === 'payment.captured') {
const { orderId, amountMinor } = event.payment!;
// PhonePe and Juspay sign nothing in the body: ask the gateway first.
// fetchOrderStatus is your own call to the gateway's status API.
if (provider === 'phonepe' || provider === 'juspay') {
if ((await fetchOrderStatus(provider, orderId)) !== 'paid') {
return new Response(null, { status: 200 });
}
}
// One transaction: store event.id in a unique column, then update the order.
// A duplicate delivery finds the id already stored and changes nothing.
await db.transaction(async (tx) => {
if (!(await tx.insertEventIdIfNew(event.id))) return;
await tx.markPaid(orderId, amountMinor); // checks amountMinor against the order
});
}
return new Response(null, { status: 200 });
Out-of-order delivery needs the same care. If a customer's first attempt fails and the second succeeds, the payment.failed for the first can reach you after the payment.captured for the second. Move an order forward from a webhook, never backwards: a paid order should not become unpaid because an older event showed up late.
Amounts: four gateways send rupees
Razorpay and PhonePe send amounts as integer paise: 50000 means ₹500. Cashfree and Juspay send rupees as JSON numbers like 1.8. PayU and Easebuzz send rupees as text like "40.00".
The tempting fix is Math.round(amount * 100). It usually works, but it multiplies a binary float: in JavaScript 1.005 * 100 is 100.49999999999999. It also rounds amounts that should never have been accepted: 12.345 becomes 1235 paise without complaint. A mismatch between the amount a webhook reports and the amount you charged is exactly what you want to catch, not hide.
The package converts amounts as decimal text, never as floats, and rejects anything that is not an exact number of paise:
src/core/amount.ts
const match = DECIMAL.exec(text); // /^(\d+)(?:\.(\d+))?$/
if (!match) return null;
const whole = match[1];
const fraction = match[2] || '';
if (fraction.length > 2 && !/^0+$/.test(fraction.slice(2))) return null; // "12.345" is not paise
return stripLeadingZeros(whole + fraction.slice(0, 2).padEnd(2, '0')); // "1.8" → "180"
The result, amountMinor, is a string. It stays exact at any size, and you compare it with the amount in paise you stored when you created the order.
How I tested it
Where a gateway publishes a test vector, a known secret with its expected signature, the tests use it. Razorpay, PhonePe and PayU publish one in their official SDKs, and I recomputed each with openssl or shasum before trusting it. Cashfree, Juspay and Easebuzz publish none, so those rely on sample payloads and round trips.
Most of the confidence comes from property-based tests with fast-check. For random payloads and secrets they check that:
- anything the package signs, it verifies;
- changing any single byte of a signed body makes verification fail;
- a request without valid authentication only ever gets
missing_headerorbad_signature; -
amountMinoris always an integer string that matches the amount sent; -
verifyWebhooknever throws, whatever it is given.
To check the tests themselves, I broke the source on purpose once per property, for example by making Cashfree's signature stop covering the body, and confirmed that the right property failed. That run is written up in the repo.
The package also ships the same tools for your own tests. india-webhooks/testing signs payloads exactly the way each gateway does and generates duplicated, out-of-order, late, tampered and stale deliveries, so you can check that your handler updates an order once and ends in the right state.
The short version
- Verify against the raw bytes, before any body parser runs.
- Know what your gateway's proof covers. For PayU and Easebuzz, trust only the hashed fields. For PhonePe and Juspay, trust nothing in the body until you have checked the order status with the gateway.
- De-duplicate on values inside the signature, not on delivery id headers.
- Move order state forward only.
- Handle amounts as integer paise, converted from text, and compare them with what you charged.
Every rule above comes from the gateway's own docs or SDK, and the sources page lists each one with the date it was read. india-webhooks is MIT licensed and has no runtime dependencies. If a real webhook verifies with the gateway but fails with the package, or the reverse, please open an issue.
Originally published at mokshupadhyay.com. I'm Moksh, a full-stack engineer building stablecoin settlement and cross-border payments, and I maintain the open-source payment libraries these posts are about.
Top comments (0)