Verifying Crypto Payment Webhooks with HMAC (Node, PHP, Python)
Working HMAC-SHA256 verification for crypto payment webhooks in Node, PHP and Python, plus the mistakes that make valid signatures fail or let fake ones through.

To verify a crypto payment webhook, compute HMAC-SHA256 over the raw request body exactly as received, keyed with your API secret, and compare the result with the signature header using a constant-time comparison. Only after the signature matches should you parse the JSON, check the event and invoice, and mark the order as paid. Then make the handler idempotent, because the same event can arrive more than once.
That is the whole idea. Most bugs come from details: a framework that parses JSON before you can read the bytes, a secret with a trailing newline, a plain == comparison, or a handler that ships the product twice when a retry arrives.
This guide gives working code for Node (Express), PHP and Python (Flask and FastAPI), using Zypher's webhook format as the concrete example. The same pattern works for any gateway that signs the body with HMAC.
How a signed crypto payment webhook works
When an invoice is paid, the gateway sends a POST request with a JSON body to the webhook URL you configured for your store. With Zypher the body looks like this (the full field list is in the API docs):
{
"event": "invoice.paid",
"data": {
"invoiceId": "5f0c3a52-7b1e-4f6a-9d2e-0c1b7a9e4d11",
"orderId": "order-123",
"status": "PAID",
"currency": "USDT",
"network": "tron",
"amount": "100.00",
"paidAmount": "100.00"
},
"timestamp": 1767226500000
}Two headers come with it:
| Header | Value |
|---|---|
X-Webhook-Signature | hex HMAC-SHA256 of the raw body, keyed with your store's API secret |
X-Webhook-Event | the event name, invoice.paid |
data.status is either PAID or OVERPAID. If you want to know how an overpaid or underpaid invoice ends up in each state, see underpaid, overpaid and expired crypto invoices.
The signature proves two things: the sender knows your API secret, and the body was not changed on the way. It does not prove the request is fresh, or that you haven't processed it already. Those need their own checks, covered below.
The verification algorithm, step by step
Read the body as raw bytes. Do not parse it yet.
Compute
HMAC-SHA256(key = apiSecret, message = rawBody)and hex-encode it.Read
X-Webhook-Signature. If it is missing, reject.Compare the two values in constant time. On mismatch, return
401and stop.Parse the JSON. Check that
eventis one you handle, and ignore any other event with a200.Check freshness with
timestamp(see the replay section).Look up the order by invoice id. If it is already paid, return
200and do nothing.Check the currency and amount against what you expected, mark the order paid, and return
2xxquickly.
Node.js (Express) with the raw body
Express's express.json() middleware reads and parses the body, so the original bytes are gone by the time your handler runs. Use express.raw() on the webhook route only, so req.body is a Buffer.
import express from 'express';
import crypto from 'node:crypto';
const app = express();
const API_SECRET = process.env.ZYPHER_API_SECRET.trim();
function validSignature(rawBody, received) {
const expected = crypto.createHmac('sha256', API_SECRET).update(rawBody).digest();
const given = Buffer.from(String(received || ''), 'hex');
// timingSafeEqual throws on different lengths, so check that first
return given.length === expected.length && crypto.timingSafeEqual(given, expected);
}
// Raw body only on this route; other routes can keep express.json()
app.post('/webhooks/zypher', express.raw({ type: 'application/json', limit: '256kb' }), async (req, res) => {
if (!validSignature(req.body, req.get('X-Webhook-Signature'))) {
return res.status(401).send('invalid signature');
}
const { event, data, timestamp } = JSON.parse(req.body.toString('utf8'));
if (event !== 'invoice.paid') return res.sendStatus(200); // ignore what you don't handle
try {
await handleInvoicePaid(data, timestamp); // idempotent, see below
res.sendStatus(200);
} catch (err) {
console.error('webhook processing failed', err);
res.sendStatus(500); // a non-2xx answer lets the delivery be retried
}
});
app.use(express.json()); // the rest of your APINotes for other Node stacks:
NestJS: create the app with
NestFactory.create(AppModule, { rawBody: true })and readreq.rawBody.Next.js route handlers: call
await request.text()once and use that string for both the HMAC andJSON.parse.Fastify: register a content-type parser that keeps the body as a
Bufferfor this route.
Decoding the header as hex and comparing buffers handles uppercase and lowercase hex alike. Invalid hex decodes to a shorter buffer, and the length check rejects it.
PHP (plain PHP, Laravel, WordPress)
In PHP the raw body is available from php://input. hash_hmac() returns lowercase hex by default, and hash_equals() compares in constant time.
<?php
$secret = trim(getenv('ZYPHER_API_SECRET'));
$raw = file_get_contents('php://input');
$received = strtolower(trim($_SERVER['HTTP_X_WEBHOOK_SIGNATURE'] ?? ''));
$expected = hash_hmac('sha256', $raw, $secret);
if ($received === '' || !hash_equals($expected, $received)) {
http_response_code(401);
exit('invalid signature');
}
$payload = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
if (($payload['event'] ?? '') !== 'invoice.paid') {
http_response_code(200);
exit;
}
try {
handle_invoice_paid($payload['data'], $payload['timestamp'] ?? null); // idempotent
http_response_code(200);
} catch (Throwable $e) {
error_log('webhook failed: ' . $e->getMessage());
http_response_code(500);
}Laravel: use
$request->getContent()for the raw body and$request->header('X-Webhook-Signature'). Exclude the webhook route from CSRF protection, or every request will be rejected before your code runs.WordPress / WooCommerce: in a REST route callback,
$request->get_body()returns the raw body. If you use one of the ready crypto payment plugins, it already does this check. The WooCommerce plugin guide covers the setup.Never use
==orstrcmp()for the comparison.hash_equals()puts the known value first and the user-supplied value second.
Python (Flask and FastAPI)
Python's hmac.compare_digest() is the constant-time comparison. The key and the message must both be bytes.
import hashlib
import hmac
import json
import os
SECRET = os.environ["ZYPHER_API_SECRET"].strip().encode("utf-8")
def valid_signature(raw: bytes, received: str | None) -> bool:
if not received:
return False
expected = hmac.new(SECRET, raw, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, received.strip().lower())Flask
from flask import Flask, request, abort
app = Flask(__name__)
@app.post("/webhooks/zypher")
def zypher_webhook():
raw = request.get_data() # bytes, read before anything parses the body
if not valid_signature(raw, request.headers.get("X-Webhook-Signature")):
abort(401)
payload = json.loads(raw)
if payload.get("event") != "invoice.paid":
return "", 200
handle_invoice_paid(payload["data"], payload.get("timestamp")) # idempotent
return "", 200Don't touch request.form before get_data(). Reading the form consumes the stream.
FastAPI
from fastapi import FastAPI, Header, HTTPException, Request
app = FastAPI()
@app.post("/webhooks/zypher")
async def zypher_webhook(request: Request, x_webhook_signature: str | None = Header(default=None)):
raw = await request.body()
if not valid_signature(raw, x_webhook_signature):
raise HTTPException(status_code=401, detail="invalid signature")
payload = json.loads(raw)
if payload.get("event") != "invoice.paid":
return {"ok": True}
await handle_invoice_paid(payload["data"], payload.get("timestamp")) # idempotent
return {"ok": True}FastAPI turns the x_webhook_signature parameter into the X-Webhook-Signature header automatically. Avoid declaring a Pydantic model as the body parameter here. It works, but it invites code that trusts parsed fields before the signature check.
Pitfalls that break verification
| Symptom | Likely cause | Fix |
|---|---|---|
| Every webhook fails | JSON parsed and re-serialized before HMAC | Hash the raw bytes |
| Every webhook fails after deploy | Secret has a trailing newline or space from the env file | trim() the secret |
| Fails only in one language | Secret hex-decoded or base64-decoded before use | Use the secret string as-is (UTF-8 bytes) |
| Fails only for some payloads | Middleware changes charset or decompresses the body | Mount the raw-body reader before other middleware |
| Fails behind a proxy or WAF | Body rewritten or truncated | Check the proxy's body limits and rewriting rules |
| Works, but insecure | == comparison, or signature check behind a feature flag | Constant-time compare, always on |
Two more traps:
Floats for money. Amounts like
"100.00"arrive as strings. Keep them as strings or decimals (Decimalin Python,bcmathin PHP, a decimal library in Node). A float turns0.1 + 0.2into a support ticket.Wrong secret. Each store has its own API key and secret. If you run several stores, look up the secret for the store the webhook belongs to, not a global one.
Replay protection with the timestamp
A valid signed request can be captured (from logs, a misconfigured proxy, a debugging tool) and sent again. The signature still matches, because nothing in the body changed. The timestamp field is inside the signed body, so an attacker can't change it without breaking the signature. That makes it useful for a freshness check.
const MAX_AGE_MS = 10 * 60 * 1000;
function isFresh(ts) {
if (typeof ts !== 'number') return false;
const ms = ts < 1e12 ? ts * 1000 : ts; // accept Unix seconds or milliseconds
return Math.abs(Date.now() - ms) <= MAX_AGE_MS;
}What to do with a stale timestamp is a design choice. Rejecting it outright is simple, but a clock problem on your server or a long retry delay could then make you miss a genuine payment. A safer pattern is: if the timestamp is stale, don't act on the body. Fetch the invoice from the API and act on what the API says.
async function fetchInvoice(invoiceId) {
const sign = crypto.createHmac('sha256', API_SECRET).update('').digest('hex'); // GET: empty string
const res = await fetch(`https://zypher.exchange/api/v1/invoice/${encodeURIComponent(invoiceId)}`, {
headers: { 'X-API-Key': process.env.ZYPHER_API_KEY, 'X-API-Sign': sign },
});
if (!res.ok) throw new Error(`invoice lookup failed: ${res.status}`);
return res.json(); // response shape: see /docs
}Re-reading the invoice is cheap, and plenty of teams do it for every webhook, not only stale ones. A forged or replayed request can't change what the API returns.
Idempotency by invoice id and retries
If your endpoint is down, times out, or answers with an error, Zypher retries the delivery, up to 5 attempts in total. Your handler also has to cope with the same event arriving twice when the first answer got lost on the network. So "process exactly once" is your job.
The reliable way is a database constraint, not an if in memory:
CREATE TABLE processed_webhooks (
invoice_id TEXT PRIMARY KEY,
processed_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);async function handleInvoicePaid(data, timestamp) {
const invoice = isFresh(timestamp) ? data : await fetchInvoice(data.invoiceId);
if (!['PAID', 'OVERPAID'].includes(invoice.status)) return;
await db.transaction(async (tx) => {
const inserted = await tx.query(
'INSERT INTO processed_webhooks (invoice_id) VALUES ($1) ON CONFLICT DO NOTHING RETURNING invoice_id',
[data.invoiceId],
);
if (inserted.rowCount === 0) return; // already handled: do nothing, still answer 200
const order = await tx.orders.findByInvoiceId(data.invoiceId);
if (!order || order.currency !== invoice.currency) throw new Error('order mismatch');
await tx.orders.markPaid(order.id, { status: invoice.status });
});
// send emails, licence keys or access links AFTER the commit, from a queue
}Practical rules:
Store the invoice id when you create the invoice.
POST /api/v1/invoicereturns it. Find the order by that id rather than by an order id you parsed out of the body.Answer
2xxfast. Write to the database, put slow work (emails, provisioning, Telegram messages) on a queue, and return. The exact time limit is in the docs.Return
200for duplicates. A duplicate isn't an error. Returning4xxor5xxonly makes more retries.Return
5xxfor your own failures. If your database is down, a non-2xx answer lets a later attempt succeed.Handle
OVERPAIDexplicitly. Fulfil the order, and decide whether you refund the difference or keep it as credit.
Testing your handler locally
You can test the full path before a real payment by signing a sample body yourself:
BODY='{"event":"invoice.paid","data":{"invoiceId":"test-1","status":"PAID","currency":"USDT","amount":"10.00"},"timestamp":'$(date +%s000)'}'
SIG=$(printf '%s' "$BODY" | openssl dgst -sha256 -hmac "$ZYPHER_API_SECRET" | awk '{print $NF}')
curl -i -X POST http://localhost:3000/webhooks/zypher \
-H 'Content-Type: application/json' \
-H "X-Webhook-Signature: $SIG" \
-H 'X-Webhook-Event: invoice.paid' \
--data-binary "$BODY"Run it three times: once as is (expect 200), once with one character of $BODY changed after signing (expect 401), and once more unchanged (expect 200 and no second fulfilment). Use --data-binary, not -d, so curl sends the bytes untouched. Then pay one small real invoice end to end. The webhook URL must be publicly reachable, so expose your local server through a tunnel or test on a staging host.
Checklist before going live:
Raw body hashed, JSON parsed only after the check
Constant-time comparison, missing header rejected
Secret trimmed, per store, kept out of the repository
Unknown events answered with
200and ignoredUnique constraint on invoice id
Stale or suspicious requests re-checked through
GET /api/v1/invoice/:idSlow work moved to a queue
If you are still choosing a provider, the crypto payment gateway overview explains how invoices, deposit addresses and webhooks fit together, and the step-by-step USDT checkout guide shows the invoice side of the same integration. When you're ready, create a store to get an API key and secret.
FAQ
- Why does my webhook signature never match?
In most cases the body was parsed and serialized again before hashing, so the bytes differ from what was signed. The next most common cause is a secret with a trailing newline or space loaded from an environment file. Hash the raw bytes and trim the secret, and the signatures should match.
- Is a plain string comparison really a security problem?
A normal
==stops at the first differing character, so response times can leak how much of a guessed signature is correct. Over a network the effect is small, but it is real enough that every major language ships a constant-time function for this. Usecrypto.timingSafeEqual,hash_equalsorhmac.compare_digest; each costs one line.- How do I stop the same payment being processed twice?
Put a unique constraint on the invoice id and insert the row in the same transaction that marks the order paid. If the insert conflicts, the event was already handled, so return
200and do nothing. That protects you against retries, network duplicates and replayed requests at the same time.- What happens if my server is down when the webhook is sent?
The delivery is retried, up to 5 attempts in total. If all of them fail, you can still read the invoice status with
GET /api/v1/invoice/:id. A periodic job that re-checks recent unpaid orders through the API is a good safety net.- Should I reject webhooks with an old timestamp?
Rejecting stale requests stops simple replays, but a strict window can also drop a genuine payment if your clock drifts. A safer approach is to treat a stale webhook as a hint: don't trust its body, and fetch the invoice from the API before acting. Either way, idempotency by invoice id remains the main protection.
- Can I check the IP address instead of the signature?
IP checks can add a layer, but they break when infrastructure changes and don't prove the body is intact. The HMAC signature covers both who sent the request and what it contains. Treat the signature as required and anything else as optional.