A webhook endpoint is a public URL that changes orders. Anyone who finds it can send it a request that says "invoice paid", so the only thing standing between a forged request and a shipped order is the signature check. This post builds that check in PHP and in Node.js, step by step, and runs it against a valid request, a forged one and a replayed one.
The examples use the Stablevoy header format, X-Stablevoy-Signature: t=<unix seconds>,v1=<hex>. Many payment providers sign webhooks the same way and differ only in the header name and the encoding, so the code carries over with small changes.
How a signed delivery works
The sender and your server share one secret. The sender never sends it: it uses the secret to compute an HMAC of the request and puts the result in a header. Your server computes the same HMAC from what it received. If the two match, the request came from someone who knows the secret and nobody changed it on the way.
One delivery. A request without a 2xx answer in time is sent again, so the same event can arrive more than once.
Two things follow from this picture. A valid signature says who sent the request, not when, so an old request recorded by someone in the middle would still pass on its own. And retries mean one event can reach you several times. The check below handles both.
What exactly gets signed
The signed string is the timestamp, a dot and the raw request body. The timestamp is inside the signed string, so it cannot be changed without breaking the signature.
The v1 value is HMAC-SHA256 of "t.body" with your signing secret, written as 64 hex characters.
"Raw body" means the bytes exactly as they arrived. If your framework parses the JSON first and you encode it again, the keys may come out in another order, a slash may get escaped, a number may lose a trailing zero, and the HMAC no longer matches even though the data is the same. Read the body before anything touches it.
Verify in PHP
PHP has everything built in: hash_hmac for the signature (HMAC is defined in RFC 2104) and hash_equals for a comparison that takes the same time whether the first or the last character differs. A plain === stops at the first wrong character, and that difference in time can be measured over many requests.
<?php declare(strict_types=1); // Checks X-Stablevoy-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256 of "<t>.<raw body>">. function verify_webhook(string $rawBody, string $header, string $secret, int $tolerance = 300, ?int $now = null): bool { $timestamp = null; $signatures = []; foreach (explode(',', $header) as $part) { [$key, $value] = array_pad(explode('=', trim($part), 2), 2, ''); if ($key === 't' && ctype_digit($value)) { $timestamp = (int) $value; } elseif ($key === 'v1' && $value !== '') { $signatures[] = $value; } } if ($timestamp === null || $signatures === []) { return false; // malformed header } if (abs(($now ?? time()) - $timestamp) > $tolerance) { return false; // too old or from the future: a replay, or a wrong clock } $expected = hash_hmac('sha256', $timestamp . '.' . $rawBody, $secret); foreach ($signatures as $signature) { if (hash_equals($expected, $signature)) { return true; } } return false; } Three details matter here:
- The parser accepts more than one
v1value. Stablevoy sends one, but the format allows several, and a sender that signs with an old and a new secret during a rotation would otherwise be refused. - The five-minute window (
$tolerance = 300) is what stops a replay: a recorded request is rejected once it is older than that. Keep the server clock in sync with NTP, or valid requests start failing too. - The body comes from
php://input, never from$_POST, which is empty for a JSON request anyway.
In the endpoint it looks like this:
$secret = getenv('STABLEVOY_WEBHOOK_SECRET') ?: throw new RuntimeException('STABLEVOY_WEBHOOK_SECRET is not set'); $rawBody = file_get_contents('php://input'); // the exact bytes, not $_POST $header = $_SERVER['HTTP_X_STABLEVOY_SIGNATURE'] ?? ''; if (!verify_webhook($rawBody, $header, $secret)) { http_response_code(400); exit; } $event = json_decode($rawBody, true, 512, JSON_THROW_ON_ERROR); The secret lives in the environment, not in the code. If it is missing, the script stops with an error instead of checking against an empty string.
Mark an order paid only from a verified webhook. The page the buyer returns to after paying proves nothing: anyone can open that address by hand.
Verify in Node.js
In Node.js the same check uses createHmac and timingSafeEqual from node:crypto. timingSafeEqual throws when the two buffers differ in length, so the header value is checked to be 64 hex characters before it becomes a buffer.
import { createHmac, timingSafeEqual } from 'node:crypto'; // rawBody is a Buffer with the exact bytes received, before any JSON parsing. export function verifyWebhook(rawBody, header, secret, { tolerance = 300, now = Date.now() / 1000 } = {}) { let timestamp = null; const signatures = []; for (const part of (header ?? '').split(',')) { const [key, value = ''] = part.trim().split('=', 2); if (key === 't' && /^\d+$/.test(value)) timestamp = Number(value); else if (key === 'v1' && /^[0-9a-f]{64}$/.test(value)) signatures.push(Buffer.from(value, 'hex')); } if (timestamp === null || signatures.length === 0) return false; // malformed header if (Math.abs(now - timestamp) > tolerance) return false; // too old or from the future const expected = createHmac('sha256', secret).update(`${timestamp}.`).update(rawBody).digest(); return signatures.some((given) => timingSafeEqual(given, expected)); } The raw body is where Node.js setups usually go wrong. express.json() reads the stream and hands you a parsed object, and the original bytes are gone. Mount the webhook route with express.raw({ type: 'application/json' }) instead, so req.body is a Buffer, or read the stream yourself:
// inside the request handler const chunks = []; let size = 0; for await (const chunk of req) { size += chunk.length; if (size > 64 * 1024) return res.writeHead(413).end(); // a webhook is small; refuse anything large chunks.push(chunk); } const rawBody = Buffer.concat(chunks); if (!verifyWebhook(rawBody, req.headers['x-stablevoy-signature'], secret)) return res.writeHead(400).end(); const event = JSON.parse(rawBody.toString('utf8')); Run it against four requests
Both versions were run on one body signed the way the sender signs it, then on three requests that must fail: the same signature over a changed body, the original request ten minutes later, and a signature made with another secret.
$ php verify.php valid accepted body changed rejected replayed after 10 min rejected wrong secret rejected $ node verify.mjs valid accepted body changed rejected replayed after 10 min rejected wrong secret rejected The PHP run used PHP 8.3, the Node.js run Node.js 22 and 26 with the same result. For the same secret, time and body both produce the signature ff2448e5...f6e35b3c, which is also what the Stablevoy sender computes, so a request signed by one side passes the check of the other.
Handle each event once
Verification answers "is this request genuine". The next question is "have I already handled it", because a delivery is retried until your server answers 2xx in time, and an answer that got lost on the way back looks like a failure to the sender.
Every failure has one answer. A duplicate is not an error: answer 200 so the retries stop.
Every delivery carries the event id in X-Stablevoy-Event-Id. Store it under a unique key in the same transaction that marks the order paid, and let the database refuse the second copy:
$eventId = $_SERVER['HTTP_X_STABLEVOY_EVENT_ID'] ?? $event['id']; $pdo->beginTransaction(); try { // processed_events.event_id is the primary key: the second delivery of the same event fails here. $pdo->prepare('INSERT INTO processed_events (event_id, type) VALUES (?, ?)')->execute([$eventId, $event['type']]); } catch (PDOException $e) { $pdo->rollBack(); // SQLSTATE class 23 is a constraint violation: 23000 on MySQL and SQLite, 23505 on PostgreSQL. if (str_starts_with((string) $e->getCode(), '23')) { http_response_code(200); // already handled: answer 2xx so the retries stop exit; } throw $e; } // ... mark the order paid here, with the same $pdo $pdo->commit(); http_response_code(200); The order of the steps is the point. The event id and the order change are saved together or not at all: if the order update throws, the transaction is rolled back, the endpoint answers 500, and the next retry handles the event from the start. Only the insert sits inside the try, so an error in the order update is never mistaken for a duplicate.
A check like SELECT ... then INSERT leaves a gap where two parallel retries both see "not yet" and both ship the order. The unique key closes that gap.
Against a local server with this code, the first delivery got 200, the same event sent again got 200 with still one row in processed_events, a forged body got 400 and a request without the header got 400. With an order update that throws, both deliveries got 500 and the table stayed empty, which is what lets the retry succeed later.
Answer fast. Stablevoy waits 10 seconds for an answer and treats a slower one as failed, so do the heavy work (emails, stock updates, calls to other services) after the event is saved, or in a queue.
Mistakes that break the check
| Mistake | What happens | Fix |
|---|---|---|
| JSON parsed before the check | The bytes change, valid requests fail | Verify the raw body, parse after |
== or === on the signature | The comparison leaks timing | hash_equals in PHP, timingSafeEqual in Node.js |
| No time window | A recorded request stays valid forever | Refuse a t older than five minutes |
| The secret in the code or the repository | Anyone who reads the repository can forge events | Keep it in the environment, and rotate it in the dashboard if it leaks |
| 500 for a duplicate | The sender retries it again and again | A known event id gets 200 |
| A redirect or plain HTTP in front | The delivery fails | Point the webhook at the final https address on port 443 |
Or let the SDK do it
The Stablevoy SDKs for PHP, Node.js and Python include a verifier that does all of the above and returns the parsed event, or throws with a message that says what was wrong: a missing header, an old timestamp or a body that does not match. The SDK page shows how to install them, and the webhooks documentation lists every event, how retries work and the delivery rules. How the payments behind these events stay bound to your own wallet is on the security page.
Questions
Why does my signature never match even with the right secret?
Almost always the body was parsed and encoded again before the check. Compute the HMAC over the raw bytes the server received, and make sure the string is the timestamp, a dot and the body, in that order.
Is a five-minute window too short?
No, as long as the server clock is synced. Deliveries are signed when they are sent, retries included, so a valid request is seconds old when it arrives.
Do I still need the signature if the endpoint URL is secret?
Yes. URLs end up in logs, browser histories and error trackers. The signature is the only part an attacker cannot copy without the secret.
What should the endpoint answer to a request that fails the check?
A 400 with no details, and no change to any order. Log it on your side if you want to see who is probing the endpoint.