Webhooks: verify and receive
IDS POSTs every event your key reads in GET /events to the https endpoints you register — the same events, with the same ids and bodies. Webhooks are the fast path; the event feed is the recovery path. Deliveries are signed by Standard Webhooks.
1 · Register an endpoint
- POST /webhook-endpoints
{ "url": "https://…", "eventTypes": [ … ] }(scopewebhooks:manage; noeventTypes— every type, also types added later). The answer carries the signing secretwhsec_…once: put it in your secret manager. A shop can do the same in the IDS cabinet (Integrations / API). - A test key's endpoints receive test events only, a live key's live events only. Events from before the endpoint was created are not sent — read them from the feed.
- The URL is https on port 443 at a public host: never an internal network, a cloud metadata address or IDS itself (
422 WEBHOOK_URL_NOT_ALLOWED, checked again before every attempt; redirects are never followed). At most 5 endpoints per account and environment. - POST /webhook-endpoints/{id}/test sends a
pingevent to that endpoint only — signed and retried like every delivery.
2 · What a delivery carries
POST <your url>, Content-Type: application/json, User-Agent: IDS-Express-Webhooks/1.0, the body = the event exactly as in the feed, and:
| Header | Meaning |
|---|---|
| webhook-id | The event id (evt_…) — the same on every retry: deduplicate on it. |
| webhook-timestamp | Unix seconds of this attempt — reject one more than 5 minutes off. |
| webhook-signature | Space-separated v1,<base64 HMAC-SHA256 of "<webhook-id>.<webhook-timestamp>.<raw body>"> — one per signing secret (two during a rotation). |
The signature is v1, + base64 of HMAC-SHA256 with the key = the base64-decoded part of your secret after whsec_, over <webhook-id>.<webhook-timestamp>.<raw body>. During a secret rotation (24 hours) two signatures are sent, separated by a space — accept the delivery if any matches.
3 · Verify, then answer fast
- Check the signature over the raw bytes you received — never re-serialised JSON.
- Reject a timestamp more than 5 minutes off (a replay).
- Deduplicate on
webhook-id(= the event id): seen already → answer 2xx and do nothing. - Store the event, answer 2xx within 10 seconds, then process it.
- Apply «the latest
sequenceper subject wins»: order is not guaranteed.
import crypto from 'node:crypto';
// rawBody: the request body exactly as received (a Buffer); headers: their names in lower case.
export function verifyWebhook(rawBody, headers, secret, toleranceSec = 300) {
const id = headers['webhook-id'];
const timestamp = headers['webhook-timestamp'];
const signatures = headers['webhook-signature'];
if (!id || !signatures || !/^[0-9]+$/.test(timestamp ?? '')) return false;
if (Math.abs(Date.now() / 1000 - Number(timestamp)) > toleranceSec) return false; // a replay
const key = Buffer.from(secret.replace(/^whsec_/, ''), 'base64');
const expected = crypto.createHmac('sha256', key).update(id + '.' + timestamp + '.').update(rawBody).digest();
// Two signatures while a rotated secret still signs: accept if any matches.
return signatures.split(' ').some((entry) => {
const [version, value] = entry.split(',');
if (version !== 'v1' || !value) return false;
const given = Buffer.from(value, 'base64');
return given.length === expected.length && crypto.timingSafeEqual(given, expected);
});
}// npm i standardwebhooks — the reference library of the standard
import { Webhook } from 'standardwebhooks';
export function verifyWithLibrary(rawBody, headers, secret) {
try {
new Webhook(secret).verify(rawBody, headers); // the signature and the 5-minute window
return true;
} catch {
return false;
}
}// Express: keep the raw bytes for this route — a JSON parser would re-serialise the body.
app.post('/ids/webhooks', express.raw({ type: 'application/json' }), async (req, res) => {
if (!verifyWebhook(req.body, req.headers, process.env.IDS_WEBHOOK_SECRET)) return res.status(400).end();
const event = JSON.parse(req.body.toString('utf8'));
if (await alreadySeen(event.id)) return res.status(204).end(); // webhook-id = event.id: deduplicate on it
await store(event); // store first …
res.status(204).end(); // … answer within 10 seconds, process after
});import base64
import hashlib
import hmac
import time
def verify_webhook(raw_body: bytes, headers: dict, secret: str, tolerance_sec: int = 300) -> bool:
"""raw_body: the request body exactly as received; headers: their names in lower case."""
msg_id = headers.get("webhook-id", "")
timestamp = headers.get("webhook-timestamp", "")
signatures = headers.get("webhook-signature", "")
if not msg_id or not signatures or not timestamp.isdigit():
return False
if abs(time.time() - int(timestamp)) > tolerance_sec: # a replay
return False
key = base64.b64decode(secret.removeprefix("whsec_"))
signed = msg_id.encode() + b"." + timestamp.encode() + b"." + raw_body
expected = base64.b64encode(hmac.new(key, signed, hashlib.sha256).digest()).decode()
# Two signatures while a rotated secret still signs: accept if any matches.
for entry in signatures.split(" "):
version, _, value = entry.partition(",")
if version == "v1" and hmac.compare_digest(value.encode(), expected.encode()):
return True
return False# Flask
@app.post("/ids/webhooks")
def ids_webhook():
headers = {name.lower(): value for name, value in request.headers.items()}
if not verify_webhook(request.get_data(), headers, os.environ["IDS_WEBHOOK_SECRET"]):
return "", 400
event = request.get_json()
if not already_seen(event["id"]): # webhook-id = event id: deduplicate on it
store(event) # store first, process after the answer
return "", 204<?php
// $rawBody: file_get_contents('php://input'); $headers: their names in lower case,
// e.g. array_change_key_case(getallheaders(), CASE_LOWER).
function verify_webhook(string $rawBody, array $headers, string $secret, int $toleranceSec = 300): bool
{
$id = $headers['webhook-id'] ?? '';
$timestamp = $headers['webhook-timestamp'] ?? '';
$signatures = $headers['webhook-signature'] ?? '';
if ($id === '' || $signatures === '' || !ctype_digit($timestamp)) {
return false;
}
if (abs(time() - (int) $timestamp) > $toleranceSec) { // a replay
return false;
}
$key = base64_decode(preg_replace('/^whsec_/', '', $secret), true);
if ($key === false) {
return false;
}
$expected = base64_encode(hash_hmac('sha256', $id . '.' . $timestamp . '.' . $rawBody, $key, true));
// Two signatures while a rotated secret still signs: accept if any matches.
foreach (explode(' ', $signatures) as $entry) {
$parts = explode(',', $entry, 2);
if (count($parts) === 2 && $parts[0] === 'v1' && hash_equals($expected, $parts[1])) {
return true;
}
}
return false;
}$rawBody = file_get_contents('php://input');
$headers = array_change_key_case(getallheaders(), CASE_LOWER);
if (!verify_webhook($rawBody, $headers, getenv('IDS_WEBHOOK_SECRET'))) {
http_response_code(400);
exit;
}
$event = json_decode($rawBody, true);
if (!already_seen($event['id'])) { // webhook-id = event id: deduplicate on it
store($event); // store first, process after the answer
}
http_response_code(204);Other languages: any Standard Webhooks library (Go, Ruby, Java, C#, Rust, …) verifies IDS deliveries as they are.
4 · Retries, switching off, recovery
- Any answer but 2xx — a 3xx too — or no answer in 10 seconds is retried: about 5 s, 5 min, 30 min, 2 h, 5 h, 10 h, 14 h, 20 h, then daily — for 72 hours from the event. A
429/503withRetry-Afterwaits that long (at most 6 hours). Your answer counts by its status line; its body is not read. - After 72 hours the delivery is dead — the event stays in GET /events for 90 days. A
410 Goneanswer switches the endpoint off at once; an endpoint failing for 72 hours without one success is switched off too (statusdisabled) and IDS is alerted. - Keep a feed reader as your safety net: follow
nextCursor(an opaque position — store it, send it back) and process what a webhook missed; the same event id may arrive both ways — deduplicate. - Rotate the secret with POST /webhook-endpoints/{id}/rotate-secret: the previous secret keeps signing next to the new one for 24 hours — switch your verifier over in that time. Your API key never signs anything, and the signing secret never authenticates an API call.