To verify webhook signature hmac correctly, calculate an HMAC-SHA256 digest from the exact request body and compare it with the sender’s signature before you parse or process the event. This guide shows the complete pattern in PHP, Python and Node.js, using a PaymentSetu webhook as the working example.
Why sign webhooks
A webhook is an HTTP request that tells your application an event happened, such as a UPI payment being matched to an order. Without authentication, any internet user who discovers the URL could send a convincing-looking JSON request and make your application change an order, subscription or invoice.
HMAC authentication gives both sides a shared secret. The sender signs the body with that secret. Your server calculates the signature independently. If the two values match, the body is very likely from a sender that knows the secret and has not been changed in transit.
This is authentication and integrity checking, not encryption. Use HTTPS as well, keep the secret private, and do not treat a valid signature as permission to skip your normal order or amount checks.
PaymentSetu is a payment verification service: the customer pays into your own connected merchant account, PaymentSetu matches the payment to the order and sends your webhook. Your endpoint should verify the signature first, then confirm the event and update your order exactly once.
What you need
Before writing the handler, collect these four inputs:
- The webhook URL on your HTTPS server.
- The signing secret from your PaymentSetu configuration. Store it as a server-side environment variable, not in browser JavaScript, source control or a log.
- The exact signature header name and encoding. The examples below use
X-Webhook-Signatureand a lowercase hexadecimal SHA-256 digest as a clear convention. Map the variable to the exact header and format specified by your webhook setup. - A unique event or order identifier in the JSON body so you can make processing idempotent.
The examples assume the signature is the raw 64-character hexadecimal HMAC value. If your webhook contract adds a documented prefix such as sha256=, remove only that documented prefix before comparing. Do not trim, reformat, sort, re-encode or pretty-print the body before calculating the digest.
Step 1: Define the verification flow
Why this matters: the order of operations prevents an unauthenticated request from reaching business logic.
Use the same sequence in every language:
- Read the raw body bytes.
- Read the signature header and the secret.
- Calculate HMAC with SHA-256 over the raw body.
- Compare the calculated and received values with a timing-safe function.
- Return an error without side effects if the comparison fails.
- Parse the JSON only after the signature passes.
- Check the event type, order ID, amount and payment state against your own records.
- Record the event ID or transaction ID before doing an action that must happen once, such as granting access or marking an invoice paid.
- Return a 2xx response after the event is durably accepted. If your application cannot accept it, return a non-2xx response so the sender can retry according to its webhook policy.
The HMAC formula is simple:
expected_signature = HMAC-SHA256(secret, raw_request_body)
The important detail is that the message is the raw body, not the decoded object. PHP’s hash_hmac() returns lowercase hexadecimal by default; Python’s hexdigest() and Node’s digest('hex') produce the same useful representation. The PHP hash_hmac documentation, Python hmac documentation and Node.js crypto documentation describe these primitives and their comparison helpers.
Success looks like this: a correctly signed request reaches your JSON handler, while a changed body, wrong secret, missing header or malformed signature stops before any order update.
Step 2: Verify the signature in PHP
Why this matters: PHP frameworks often make parsed request data convenient, but the signature must be calculated from the original input stream.
The following endpoint uses PHP’s raw input stream, hash_hmac() and hash_equals():
<?php
declare(strict_types=1);
$rawBody = file_get_contents('php://input');
$receivedSignature = $_SERVER['HTTP_X_WEBHOOK_SIGNATURE'] ?? '';
$secret = getenv('PAYMENTSETU_WEBHOOK_SECRET');
if ($rawBody === false || $receivedSignature === '' || $secret === false) {
http_response_code(401);
exit('Invalid webhook');
}
$expectedSignature = hash_hmac('sha256', $rawBody, $secret);
if (!hash_equals($expectedSignature, $receivedSignature)) {
http_response_code(401);
exit('Invalid webhook');
}
try {
$event = json_decode($rawBody, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $exception) {
http_response_code(400);
exit('Invalid JSON');
}
// Check the event and your database record before changing order state.
// Save an event or transaction ID to make repeated deliveries harmless.
http_response_code(200);
echo 'accepted';
hash_hmac('sha256', $rawBody, $secret) signs the bytes received by the server. hash_equals() compares the calculated value with the untrusted header without using an ordinary early-exit string comparison. Keep the secret in the environment and replace HTTP_X_WEBHOOK_SIGNATURE only if your configured header has a different name.
Success looks like this: the handler returns 200 for a valid, well-formed event and returns 401 for a missing, incorrect or changed signature. Put your order update between successful verification and the final response, with an idempotency check around it.
Step 3: Verify the signature in Python
Why this matters: Python’s hmac.compare_digest() is designed for comparing externally supplied digests, but it still requires matching representations.
This framework-neutral example can sit inside a Flask, Django or another Python request handler. It assumes the framework provides the raw body bytes and request headers:
import hashlib
import hmac
import json
import os
def verify_webhook(raw_body: bytes, received_signature: str) -> dict:
secret = os.environ["PAYMENTSETU_WEBHOOK_SECRET"].encode("utf-8")
expected_signature = hmac.new(
secret,
raw_body,
hashlib.sha256,
).hexdigest()
if not received_signature:
raise ValueError("Missing webhook signature")
if not hmac.compare_digest(expected_signature, received_signature):
raise ValueError("Invalid webhook signature")
return json.loads(raw_body)
# In your framework handler:
# raw_body = request.get_data(cache=True, as_text=False)
# signature = request.headers.get("X-Webhook-Signature", "")
# event = verify_webhook(raw_body, signature)
# check event and process it idempotently
Keep raw_body as bytes from the framework. Do not call request.get_json() first and then pass a re-encoded object to verify_webhook(). hmac.new() creates the SHA-256 HMAC, hexdigest() produces a text representation, and compare_digest() avoids the ordinary == comparison for the security-sensitive check. Python’s documentation specifically recommends compare_digest() when comparing an externally supplied digest.
Success looks like this: valid bytes and the expected header return a Python dictionary; invalid signatures raise an error before json.loads() runs. Convert that error into your framework’s 401 or 403 response without logging the secret or full request if it may contain sensitive payment details.
Step 4: Verify the signature in Node.js
Why this matters: Express’s JSON parser can consume and transform the body before your route runs, so the webhook route must receive a Buffer.
Register the raw-body middleware for the webhook path before a general express.json() middleware:
const express = require('express');
const {
createHmac,
timingSafeEqual,
} = require('node:crypto');
const app = express();
const secret = process.env.PAYMENTSETU_WEBHOOK_SECRET;
app.post(
'/webhooks/paymentsetu',
express.raw({ type: 'application/json' }),
(req, res) => {
const receivedSignature = req.get('X-Webhook-Signature') || '';
if (!secret || !receivedSignature || !Buffer.isBuffer(req.body)) {
return res.status(401).send('Invalid webhook');
}
const expectedSignature = createHmac('sha256', secret)
.update(req.body)
.digest('hex');
const expectedBytes = Buffer.from(expectedSignature, 'utf8');
const receivedBytes = Buffer.from(receivedSignature, 'utf8');
const valid = expectedBytes.length === receivedBytes.length
&& timingSafeEqual(expectedBytes, receivedBytes);
if (!valid) {
return res.status(401).send('Invalid webhook');
}
let event;
try {
event = JSON.parse(req.body.toString('utf8'));
} catch (error) {
return res.status(400).send('Invalid JSON');
}
// Check the event and process its unique ID idempotently.
return res.status(200).send('accepted');
},
);
// Register app.use(express.json()) for ordinary JSON routes after this route.
createHmac() updates the digest with the original Buffer. Node’s timingSafeEqual() requires equal-length byte values, which is why the example checks lengths before calling it. If the sender uses a documented signature prefix or a different encoding, normalise that value according to the contract before converting it to bytes.
Success looks like this: req.body is a Buffer, a valid signature passes, and the JSON is parsed only after the constant-time comparison. If express.json() runs first, the original bytes may no longer be available and every otherwise-correct signature can fail.
Step 5: Add idempotency and payment checks
Why this matters: signature verification proves who signed a body and whether it changed; it does not stop a valid event from being delivered more than once.
After verification, apply application-level checks in this order:
- Read the event’s unique ID or transaction identifier.
- Look for that identifier in a database table with a unique constraint.
- If it was already accepted, return
200without repeating the side effect. - If it is new, compare the order reference, amount and expected payment state with your own pending order.
- In one database transaction, record the event and apply the state change.
- Return
200only after the transaction commits.
For a PaymentSetu integration, this is where your application matches the verified webhook to the order or invoice it created. PaymentSetu sends the verification result; your code still decides whether that particular order is open, whether the amount matches, and what fulfilment action is appropriate.
Do not use the signature itself as an idempotency key. The same event can legitimately be delivered again with the same signature. Use the event ID or transaction ID from the payload, and enforce uniqueness in the database so two concurrent deliveries cannot both perform the side effect.
Step 6: Test the handler safely
Why this matters: most HMAC bugs come from changing the body, the encoding or the comparison rather than from the cryptographic function itself.
Create a test fixture with a non-production secret and a small JSON body. Generate the expected digest with the same secret and exact body bytes, then test all of these cases:
| Test | Expected result |
|---|---|
| Exact body and correct secret | Accept and process once |
| One body character changed | Reject before parsing or side effects |
| Correct body with wrong secret | Reject |
| Missing signature header | Reject |
| Correct digest with different case | Follow the documented encoding; do not silently change it |
| Valid event delivered twice | Second delivery returns safely without repeating the side effect |
| Valid signature with malformed JSON | Reject as bad input, with no order change |
For a local test, log only a short test identifier and whether verification passed. Never print the production secret or the full signed payload. Test through the same web-server and framework middleware used in production so you catch body-parser changes before launch.
Common mistakes
Parsing JSON before verifying
This is the most frequent mistake. A JSON object can be represented with different whitespace, escaping and key order. Sign the original request bytes, then parse them after verification.
Comparing with ==, === or a normal string helper
Use hash_equals() in PHP, hmac.compare_digest() in Python and timingSafeEqual() in Node.js. These helpers are intended for secret or digest comparisons and avoid the content-based short-circuiting of ordinary comparisons.
Hashing the wrong value
HMAC is not plain SHA-256. It is also not a hash of the parsed JSON, a URL, a timestamp by itself or a Base64 version of the body unless the webhook contract explicitly says so. Use HMAC-SHA256 with the shared secret and the exact raw body.
Mixing hex and binary output
Choose one representation on both sides. The examples use lowercase hexadecimal text. If your sender supplies Base64 or raw bytes, compare the corresponding representation rather than comparing a hex string with decoded bytes.
Doing business work before verification
Do not mark an order paid, issue access, send a fulfilment request or credit an account before the signature passes and the payload checks succeed. Reject invalid requests early.
Treating a successful HTTP response as proof of payment
An HTTP 200 means your endpoint accepted the webhook. It is not a substitute for checking the signed event, the order identifier, the amount and your own order state. Keep those checks in your handler.
FAQ
What is the correct HMAC algorithm for a webhook?
Use the algorithm named by the webhook provider. These examples use HMAC-SHA256, which combines the shared secret with the raw request body. Do not substitute plain SHA-256 or a different digest without changing both sides of the integration contract.
Should I verify the raw body or parsed JSON?
Verify the raw body bytes. Parsing and serialising JSON can alter formatting, so the resulting bytes may not be the bytes that were signed. Parse the body only after the signature comparison succeeds.
Which comparison function should I use?
Use PHP hash_equals(), Python hmac.compare_digest() or Node.js crypto.timingSafeEqual(). Node requires equal-length byte values, so check lengths before calling it; also keep the surrounding code free of avoidable secret-dependent branches.
How do I prevent a webhook from being processed twice?
Store a unique event ID or transaction ID with a database uniqueness constraint before applying the side effect. When the same verified event arrives again, recognise the stored ID and return a successful response without repeating the order update.
Where should I store the webhook secret?
Keep it in a server-side environment variable or secret manager with restricted access. Never expose it to browser code, commit it to a repository, include it in a URL or print it in application logs.
When you are ready to connect a custom checkout, register for PaymentSetu and configure the webhook endpoint with the raw-body verification pattern above. If you run WooCommerce, the PaymentSetu WooCommerce plugin can handle the order integration while your server keeps the same signature and idempotency principles.