How to verify payment webhooks (HMAC signatures explained)
To verify a payment webhook, take the timestamp from the signature header, join it to the raw request body with a full stop, compute an HMAC-SHA256 of that string with your signing secret, and compare the result to the signature in constant time. Then reject the request if the timestamp is more than five minutes old. On CoinStack the header is CoinStack-Signature: t=...,v1=.... Almost every failed check comes from a framework that parsed the body before you hashed it.
Why does a payment webhook need verifying?
Your webhook URL is public. Anyone who finds it, guesses it or reads it in a log can send a POST with a JSON body that says "kind": "checkout.completed". If your handler believes the body, that request ships an order, activates a server or credits a balance for free. Stripe's webhook documentation puts it plainly: "Without verification, an attacker could send fake webhook events to your endpoint to trigger actions like fulfilling orders, granting account access, or modifying records."
A valid signature proves two things: the request was produced by someone who holds your signing secret, and not one byte of the body changed on the way. It does not prove the event is new or that it arrived in order. Those need the replay window below and the handling covered in reliable payment webhooks.
A second layer costs one API call. After verifying, get the checkout by its checkout_id and act on the status the API returns, not on the copy inside the event. A forged body then has nothing to work with, and an event that arrives late cannot roll an order backwards.
How does an HMAC signature with a timestamp work?
HMAC is a way of hashing a message with a secret key mixed in, defined in RFC 2104. Without the key you cannot produce the right output, and changing the message changes the output completely. SHA-256 is the hash underneath.
Every CoinStack webhook request carries this header:
CoinStack-Signature: t=1796228678,v1=0e6494f309fc69039d6469d87098d20bf41703c430fb059d36e057beeb6ce6a4t is when the request was signed, in Unix seconds. v1 is the HMAC-SHA256, as lowercase hex, of this string:
1796228678.{"event_id":"e41b7c92-3a5d-4f8e-b1c6-9d2a7f4e0b85","kind":"checkout.completed",...}That is the timestamp, a full stop, then the body exactly as it was sent. The key is your webhook's signing secret, the whole string including the whsec_ prefix. The webhooks guide lists the check in 5 steps:
- Read
tandv1from the header. - Build the string
t.bodyfrom the raw body. - Compute the HMAC-SHA256 of it with your secret and write it as lowercase hex.
- Compare it with
v1using a constant-time comparison. - Reject the request if
tis more than 5 minutes old.
Because t sits inside the signed string, an attacker who captured a real request cannot change its timestamp to make it look fresh without breaking the signature.
When a check fails and you cannot see why, compute the signature by hand from a request you logged, with the body saved byte for byte:
{ printf '%s.' 1796228678; cat body.json; } | openssl dgst -sha256 -hmac "$COINSTACK_WEBHOOK_SECRET"If that matches v1 and your code does not, your code is hashing different bytes.
Why does the raw request body matter?
The signature covers bytes, not meaning. Two JSON documents can describe the same object and still differ byte for byte, and only one of them was signed. Frameworks are helpful here in the wrong way: they parse the body into an object, and if you turn that object back into text you get their formatting, not the sender's.
Small differences are enough. JSON.stringify drops the spaces after colons and writes 1.50 as 1.5. PHP's json_encode writes https:// as https:\/\/ and escapes non-ASCII characters. Python's json.dumps adds its own spacing. Any of these changes the hash.
| Framework | Where the raw body is | What usually breaks it |
|---|---|---|
| Express | express.raw() on the webhook route gives a Buffer | app.use(express.json()) registered before the route |
| Next.js (App Router) | await request.text() in a route handler | Calling request.json() first, then re-encoding |
| Django | request.body (bytes) | Reading request.read() first, or re-encoding json.loads output |
| Laravel | $request->getContent() | Hashing json_encode($request->all()) |
Express
Keep the check in one function so every route uses the same code. This version takes a string or a Buffer, rejects malformed headers before comparing, and feeds the exact bytes to the HMAC. It assumes an ES module project ("type": "module" in package.json).
// lib/coinstack-signature.js
import crypto from "node:crypto";
export function verifySignature(header, body, secret, toleranceSeconds = 300) {
const parts = {};
for (const item of String(header ?? "").split(",")) {
const index = item.indexOf("=");
if (index > 0) parts[item.slice(0, index)] = item.slice(index + 1);
}
if (!/^\d+$/.test(parts.t ?? "") || !/^[0-9a-f]{64}$/.test(parts.v1 ?? "")) {
return false;
}
const expected = crypto
.createHmac("sha256", secret)
.update(`${parts.t}.`)
.update(body)
.digest();
const given = Buffer.from(parts.v1, "hex");
const fresh = Math.abs(Date.now() / 1000 - Number(parts.t)) <= toleranceSeconds;
return fresh && crypto.timingSafeEqual(expected, given);
}The order of middleware is the trap. If app.use(express.json()) runs first, it consumes the body, express.raw() on the route then does nothing, and req.body is a plain object. Its string form is [object Object], so every signature fails. Register the webhook route before the global JSON parser:
import express from "express";
import { verifySignature } from "./lib/coinstack-signature.js";
const app = express();
app.post("/webhooks/coinstack", express.raw({ type: "application/json" }), (req, res) => {
const body = Buffer.isBuffer(req.body) ? req.body : Buffer.alloc(0);
if (!verifySignature(req.get("CoinStack-Signature"), body, process.env.COINSTACK_WEBHOOK_SECRET)) {
return res.status(400).send("Invalid signature");
}
const event = JSON.parse(body);
// Record event.event_id, queue the work, then answer.
res.sendStatus(200);
});
app.use(express.json()); // every other route still gets parsed JSONThe Node.js and Express tutorial builds the rest of that integration.
Next.js
An App Router route handler receives a standard Request, and nothing parses it for you. Read it once as text and pass that text to the same function. TypeScript accepts the module above if you add types to its parameters, or you can keep it as a .js file.
// app/api/webhooks/coinstack/route.ts
import { verifySignature } from "@/lib/coinstack-signature";
export async function POST(request: Request) {
const body = await request.text();
const header = request.headers.get("CoinStack-Signature");
if (!verifySignature(header, body, process.env.COINSTACK_WEBHOOK_SECRET!)) {
return new Response("Invalid signature", { status: 400 });
}
const event = JSON.parse(body);
// Record event.event_id and queue the work.
return new Response(null, { status: 200 });
}Route handlers run on the Node.js runtime by default, which node:crypto needs. On the older Pages Router, API routes parse JSON bodies automatically, so add export const config = { api: { bodyParser: false } } to the route file and read the stream yourself. The Next.js tutorial covers the full app.
Django
Django gives you the raw bytes as request.body. Its documentation warns that reading the request through read() first makes body raise a RawPostDataException. The view also needs csrf_exempt: Django's CSRF middleware answers a POST without a token with 403, and CoinStack has no token to send.
import hashlib
import hmac
import json
import os
import time
from django.http import HttpResponse, HttpResponseBadRequest
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
SECRET = os.environ["COINSTACK_WEBHOOK_SECRET"].encode()
def verify_signature(header: str, body: bytes, tolerance: int = 300) -> bool:
parts = dict(item.split("=", 1) for item in header.split(",") if "=" in item)
timestamp = parts.get("t", "")
if not timestamp.isdigit():
return False
signed = timestamp.encode() + b"." + body
expected = hmac.new(SECRET, signed, hashlib.sha256).hexdigest()
return (
hmac.compare_digest(expected.encode(), parts.get("v1", "").encode())
and abs(time.time() - int(timestamp)) <= tolerance
)
@csrf_exempt
@require_POST
def coinstack_webhook(request):
header = request.headers.get("CoinStack-Signature", "")
if not verify_signature(header, request.body):
return HttpResponseBadRequest("Invalid signature")
event = json.loads(request.body)
# Record event["event_id"] and queue the work.
return HttpResponse(status=200)Both sides of compare_digest are encoded to bytes on purpose. Python's hmac documentation allows str arguments only if they are ASCII, so a header carrying other characters would raise an error and return 500 instead of 400. The Python tutorial has the Flask version.
Laravel
In Laravel the check fits in a middleware, which keeps controllers free of it. $request->getContent() returns the body as received.
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class VerifyCoinStackSignature
{
public function handle(Request $request, Closure $next): Response
{
$parts = [];
foreach (explode(',', (string) $request->header('CoinStack-Signature')) as $item) {
[$key, $value] = array_pad(explode('=', $item, 2), 2, '');
$parts[$key] = $value;
}
$timestamp = $parts['t'] ?? '';
$given = $parts['v1'] ?? '';
$expected = hash_hmac(
'sha256',
$timestamp.'.'.$request->getContent(),
config('services.coinstack.webhook_secret'),
);
if (! ctype_digit($timestamp)
|| ! hash_equals($expected, $given)
|| abs(time() - (int) $timestamp) > 300) {
return response('Invalid signature', 400);
}
return $next($request);
}
}Attach it to the webhook route with ->middleware(VerifyCoinStackSignature::class). A route in routes/web.php also has to be excluded from request forgery protection, or Laravel answers 419 before your middleware runs. On Laravel 13 that is $middleware->preventRequestForgery(except: ['webhooks/coinstack']) in bootstrap/app.php, as the Laravel CSRF documentation shows; Laravel 11 and 12 call the same method validateCsrfTokens. The PHP and Laravel tutorial wires this into a full integration with a queue.
Why must the comparison be constant-time?
An ordinary string comparison stops at the first byte that differs. A request whose signature shares its first 10 characters with the right one takes slightly longer to reject than one that shares none. Measured over many requests, that difference can leak the correct signature one character at a time.
Each language has a function that takes the same time whatever the content:
- Node.js:
crypto.timingSafeEqual. It throws if the two buffers differ in length, which is why the Express function checks thatv1is 64 hex characters before calling it. - Python:
hmac.compare_digest, which the docs describe as "designed to prevent timing analysis by avoiding content-based short circuiting behaviour". - PHP:
hash_equals. The manual says to pass the user-supplied string second, so your computed value goes first.
Never use ==, === or strcmp on signatures.
How does the five-minute replay window work?
A replay is a captured, genuinely signed request sent again. The signature is still valid, because nothing in it changed. The timestamp check is what stops a request captured last week from working today: CoinStack's docs say to reject a request whose t is more than 5 minutes old, and the code above uses the absolute difference, so timestamps from the future fail too.
Retries do not trip this check. t is the time that particular request was signed, so an event retried 8 hours after it happened arrives with a fresh timestamp.
The window has 2 practical consequences. Inside it a replay is still possible, so record each event_id and skip one you have already handled; the idempotency guide shows the table. And your server's clock has to be right. Stripe's docs recommend using Network Time Protocol for the same reason; a server that drifts by minutes rejects valid events.
How do you rotate a webhook signing secret?
Rotate when a secret may have leaked: it was committed to a repository, pasted into a ticket, or known to someone who has left. The OWASP Secrets Management Cheat Sheet also advises rotating API keys and machine credentials on a schedule set by their risk, and says secrets should never be logged.
On CoinStack, select Rotate secret on the webhook under Developers, or call Rotate a webhook secret (POST /webhooks/{webhook_id}/rotate). The response holds the new secret once. The old one stops working straight away, so put the new value in your secret store and reload the app as one step. A script that calls the endpoint and writes the result keeps the gap to seconds.
Any event that fails verification in that gap gets a 400 from you and counts as a failed delivery. CoinStack retries it after 1 minute, then 5 minutes, then 30, so a short gap fixes itself. After rotating, open Recent events in the dashboard and resend anything that is still undelivered.
Each webhook has its own secret. If you run several endpoints (an account can have up to 10 webhooks), store each secret against its endpoint and rotate them one at a time.
How do you check that your verification works?
Use Send test on the webhook in the dashboard. It sends a sample checkout.completed event for 10 US dollars with the reference test, signed like a real one, and shows the status your server returned. A 200 means your check passed. Then send the same body with a changed signature, or with one character of the body changed, and confirm you get 400. Testing a crypto checkout covers the rest of a launch test.
If genuine events fail, check these in order:
- The secret is complete, with its
whsec_prefix and no trailing newline from the environment file. - It belongs to this webhook, not another endpoint or an older rotation.
- Nothing between CoinStack and your code (a body parser, a logging middleware, a proxy) rewrites the body.
- The server clock is synchronized.
Frequently asked questions
What status should my endpoint return for an invalid signature?
Return 400 and do nothing else. CoinStack treats any status outside the 2xx range as a failed delivery and retries it. That is harmless for forged requests, which will never pass, and useful for genuine ones that failed because of a configuration mistake: once you fix the secret, the next retry succeeds, or you can resend the event from the dashboard.
Does HTTPS make signature checks unnecessary?
No. HTTPS encrypts the connection and proves your server's identity to the sender. It says nothing about who is sending to you, and anyone can open an HTTPS connection to a public URL. The signature is the only thing in the request that proves it came from the holder of your signing secret, so both are needed.
Why does verification pass locally but fail in production?
Usually because production uses a different secret, or something in front of the app changes the request. Each webhook has its own secret, so a staging endpoint and a production endpoint never share one. Also look for a reverse proxy, firewall or framework middleware that decompresses, re-encodes or trims the body, and for clock drift on the production server.
Is the webhook signing secret the same as the API key?
No. The API key starts with sk_ and authenticates your requests to CoinStack. The signing secret starts with whsec_, belongs to one webhook, and is only used to check requests CoinStack sends to you. Keep both on the server, out of logs and out of version control. They are replaced separately: a leaked secret is rotated on its webhook, and a leaked API key is deleted in the dashboard and replaced with a new one.
Should my handler verify the dashboard test event?
Yes. The test event is signed exactly like a real one, so it is the quickest proof that your check works. It is not saved and does not appear in your events. Its checkout has the reference test and matches no order of yours, so a handler that looks up the order before fulfilling will ignore it.