Webhooks
Verifying signatures
Every webhook is signed with your endpoint's secret. Check the signature before you trust a single byte of the payload.
Why
Your webhook URL is public. Anyone who finds it can post JSON to it. The signature proves a request came from Ordexs, for your endpoint, and wasn't changed on the way.
The signature header
Ordexs-Signature: t=1760177100,v1=5f2b9c…e41atis the Unix time the request was signed.v1is a hex HMAC-SHA256 of the string<t>.<raw body>, keyed with the endpoint's secret (whsec_…).- During a secret rotation there are two
v1entries, one per secret. Accept the request if any of them matches.
Checking it
- Read the raw request body, exactly as received. Parse JSON only after verifying: re-serialising changes the bytes and the signature won't match.
- Split the header on
,and each part on the first=. - Reject the request if
tis more than 5 minutes from your clock. This stops someone replaying an old request. - Compute HMAC-SHA256 of
t + "." + raw bodywith your secret, as lowercase hex. - Compare it to each
v1with a constant-time comparison. If none matches, answer400and stop.
import crypto from 'node:crypto'
export function verifyOrdexsSignature(rawBody, header, secret, toleranceSeconds = 300) {
let t = 0
const signatures = []
for (const part of (header ?? '').split(',')) {
const i = part.indexOf('=')
const key = part.slice(0, i).trim()
const value = part.slice(i + 1).trim()
if (key === 't') t = Number(value)
else if (key === 'v1') signatures.push(value)
}
if (!t || Math.abs(Date.now() / 1000 - t) > toleranceSeconds) return false
const expected = crypto.createHmac('sha256', secret).update(`${t}.${rawBody}`).digest('hex')
return signatures.some(
(sig) => sig.length === expected.length && crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(expected)),
)
}
// Express: keep the body raw for this route.
app.post('/webhooks/ordexs', express.raw({ type: 'application/json' }), (req, res) => {
const raw = req.body.toString('utf8')
if (!verifyOrdexsSignature(raw, req.get('Ordexs-Signature'), process.env.ORDEXS_WEBHOOK_SECRET)) {
return res.status(400).send('Bad signature')
}
const event = JSON.parse(raw)
queue.add(event) // do the work later
res.sendStatus(200)
})<?php
function verify_ordexs_signature(string $rawBody, string $header, string $secret, int $tolerance = 300): bool
{
$t = 0;
$signatures = [];
foreach (explode(',', $header) as $part) {
[$key, $value] = array_pad(explode('=', trim($part), 2), 2, '');
if ($key === 't') $t = (int) $value;
elseif ($key === 'v1') $signatures[] = $value;
}
if ($t === 0 || abs(time() - $t) > $tolerance) return false;
$expected = hash_hmac('sha256', $t . '.' . $rawBody, $secret);
foreach ($signatures as $signature) {
if (hash_equals($expected, $signature)) return true;
}
return false;
}
$raw = file_get_contents('php://input');
$header = $_SERVER['HTTP_ORDEXS_SIGNATURE'] ?? '';
if (!verify_ordexs_signature($raw, $header, getenv('ORDEXS_WEBHOOK_SECRET'))) {
http_response_code(400);
exit('Bad signature');
}
$event = json_decode($raw, true);
// Queue the work, then answer.
http_response_code(200);import hashlib
import hmac
import time
def verify_ordexs_signature(raw_body: bytes, header: str, secret: str, tolerance: int = 300) -> bool:
t, signatures = 0, []
for part in (header or "").split(","):
key, _, value = part.strip().partition("=")
if key == "t" and value.isdigit():
t = int(value)
elif key == "v1":
signatures.append(value)
if not t or abs(time.time() - t) > tolerance:
return False
expected = hmac.new(secret.encode(), f"{t}.".encode() + raw_body, hashlib.sha256).hexdigest()
return any(hmac.compare_digest(expected, s) for s in signatures)
# Flask
@app.post("/webhooks/ordexs")
def ordexs_webhook():
raw = request.get_data() # bytes, before any JSON parsing
if not verify_ordexs_signature(raw, request.headers.get("Ordexs-Signature", ""), os.environ["ORDEXS_WEBHOOK_SECRET"]):
return "Bad signature", 400
event = json.loads(raw)
queue.enqueue(event)
return "", 200Common mistakes
- Verifying the parsed body. Frameworks that parse JSON for you (Express's
express.json(), Laravel's$request->all()) give you a re-built object. Use the raw bytes. - A clock that drifts. Keep your server on NTP; a clock more than 5 minutes off rejects every event.
- Checking only the first
v1. During a rotation the matching signature may be the second one. - Trimming or re-encoding the body in a proxy in front of your app. Pass it through untouched.
