Verify signatures
Check that a webhook really came from Shipping Engine and was not changed or replayed.
- Product
- APIShipping Engine API
- Section
- Webhooks
- Reading time
- 9 min read
Anyone can send a POST to your webhook URL. The signature proves that a request came from Shipping
Engine, that its body was not changed, and that it is recent. Check it on every event before you
act on it.
In short
- The signature is an HMAC-SHA256, keyed with your secret, over
timestamp.id.sha256(body). - Compute it on the raw request body, exactly as received. Never on re-serialised JSON.
- Compare in constant time, reject old timestamps (we recommend 300 seconds), and pick the secret by
keyId.
Headers
Every event request carries these headers:
| Header | Example | Meaning |
|---|---|---|
content-type | application/json | The body is JSON. |
user-agent | Fastrac-Webhook-Client/1.0 | Identifies Shipping Engine. Don't rely on it for security. |
x-webhook-id | 7d0f3c1e-2b8a-4f61-9a55-0c3e9b7d21aa | Unique event ID. The same on every retry of the event. Use it to drop duplicates. |
x-webhook-timestamp | 1795670142 | When this attempt was signed, in Unix seconds. New on every attempt. |
x-webhook-signature | keyId=key-2026-11,sig=5b1e…c9 | The keyId of the secret used, and the hex-encoded signature. |
x-webhook-event-type | shipment.delivered | The event name. See Events. |
x-webhook-schema-version | 2025-10-01 | The payload format version. |
x-webhook-attempt | 1 | Attempt number, starting at 1. |
Header names are case-insensitive. Your framework may show them as X-Webhook-Id or
HTTP_X_WEBHOOK_ID.
The algorithm
Shipping Engine signs each attempt like this:
body_hash = hex( SHA256( raw_body ) )
signed_payload = x-webhook-timestamp + "." + x-webhook-id + "." + body_hash
sig = hex( HMAC_SHA256( key = secret (UTF-8), message = signed_payload ) )All hex is lowercase. To verify an event:
- Read the raw body bytes before any JSON parsing.
- Read
x-webhook-id,x-webhook-timestampandx-webhook-signature. If one is missing, reject the request. - Split
x-webhook-signatureon,and then each part on the first=, to getkeyIdandsig. - Look up your secret for that
keyId. If you don't know thekeyId, reject the request. - Check the timestamp: if it is more than 300 seconds away from your clock, reject the request.
- Compute
body_hash, thensigned_payload, then the expected HMAC, exactly as above. - Compare the expected value with
sigusing a constant-time comparison. - Only now parse the JSON and handle the event.
Worked example
Use this to test your code:
| Input | Value |
|---|---|
| Secret | test_secret_for_docs_0123456789abcdef |
x-webhook-timestamp | 1795670142 |
x-webhook-id | 7d0f3c1e-2b8a-4f61-9a55-0c3e9b7d21aa |
| Raw body | {"shipment_code":"SHP-261120-ABC123"} |
body_hash = deeb8ffc05c92e388cd6a6761d26c97e5162bd2bc227d558ee9d28f2c1b21000
signed_payload = 1795670142.7d0f3c1e-2b8a-4f61-9a55-0c3e9b7d21aa.deeb8ffc05c92e388cd6a6761d26c97e5162bd2bc227d558ee9d28f2c1b21000
sig = 58cdbbf52e2c22a6ddbdd3ac30d5bb1c9cbe3dfca420734d767b395db19dc46cThe header for this example would be x-webhook-signature: keyId=<your keyId>,sig=58cdbbf5…dc46c.
(Your timestamp check will reject this fixed timestamp, so test the hashing step on its own.)
Full code
Each example keeps a map of keyId → secret, so you can rotate secrets without downtime (see
Rotate your secret).
import crypto from 'node:crypto';
const SECRETS = {
[process.env.FASTRAC_WEBHOOK_KEY_ID]: process.env.FASTRAC_WEBHOOK_SECRET,
};
const TOLERANCE_SECONDS = 300;
/**
* @param {Buffer} rawBody the exact request body bytes
* @param {Record<string, string>} headers lower-cased header names
*/
export function verifyWebhook(rawBody, headers) {
const id = headers['x-webhook-id'];
const timestamp = headers['x-webhook-timestamp'];
const signatureHeader = headers['x-webhook-signature'];
if (!id || !timestamp || !signatureHeader) return false;
// 1. Freshness
if (!/^\d+$/.test(timestamp)) return false;
if (Math.abs(Date.now() / 1000 - Number(timestamp)) > TOLERANCE_SECONDS) return false;
// 2. keyId=…,sig=…
const parts = {};
for (const part of signatureHeader.split(',')) {
const i = part.indexOf('=');
if (i > 0) parts[part.slice(0, i).trim()] = part.slice(i + 1).trim();
}
const secret = SECRETS[parts.keyId];
if (!secret || !parts.sig) return false;
// 3. Expected signature
const bodyHash = crypto.createHash('sha256').update(rawBody).digest('hex');
const expected = crypto
.createHmac('sha256', secret)
.update(`${timestamp}.${id}.${bodyHash}`)
.digest();
// 4. Constant-time compare
const received = Buffer.from(parts.sig, 'hex');
return received.length === expected.length && crypto.timingSafeEqual(received, expected);
}import express from 'express';
import { verifyWebhook } from './verify.js';
const app = express();
// Raw body for this route only. Don't put express.json() in front of it.
app.post('/webhooks/shipping-engine', express.raw({ type: '*/*' }), (req, res) => {
if (!req.headers['x-webhook-signature']) {
const { challenge } = JSON.parse(req.body.toString('utf8') || '{}');
return res.json({ challenge });
}
if (!verifyWebhook(req.body, req.headers)) return res.sendStatus(401);
res.sendStatus(200);
queueForProcessing(req.headers['x-webhook-id'], JSON.parse(req.body.toString('utf8')));
});The challenge request is not signed
The verification challenge that Shipping Engine sends when you register an endpoint has no
signature headers. Its body is only {"challenge":"<uuid>"}. Your handler must recognise it (no
x-webhook-signature header) and echo the value back, without running signature verification.
Echoing the value is safe: it reveals nothing, and an unsigned request never reaches your event logic.
Rotate your secret
Calling setWebhook again replaces the secret immediately. To rotate without rejecting any
events:
- Generate a new secret and pick a new
keyId, for examplekey-2027-01. - Deploy your handler with both secrets in the
keyId→ secret map. - Call
POST /b2b/webhook/setWebhookwith the newsecretandkeyId(and your usual URL and filters). - Check that
data.activeSecretKeyIdsshows the newkeyId. - After a few minutes, remove the old secret from your handler.
Retries of older events are signed again with the new secret, so you never need the old one for long.
Common mistakes
Verifying parsed JSON instead of the raw body
JSON.stringify(req.body), json.dumps(request.json) or json_encode(json_decode(...)) changes
spacing, key order and escaping, so the hash never matches. Read the raw bytes first: express.raw(),
request.get_data(), php://input, io.ReadAll(r.Body). A global JSON body parser in front of
the route causes the same failure.
Old secret after registering again
Each setWebhook call replaces the secret at once. If you re-registered (for example from another
environment or a script) with a different secret, every event fails verification. Check
activeSecretKeyIds with GET /b2b/webhook/info; the keyId in the signature header tells you which
secret was used.
Clock skew
The timestamp check compares with your server clock. If your clock is minutes off, valid events are rejected. Keep servers in sync with NTP. Don't widen the tolerance to hours: that lets old requests be replayed.
Rejected events are not retried
A 401 (or any 4xx other than 408, 409 and 429) tells Shipping Engine not to retry. That is
right for forged requests, but if your secret is misconfigured, real events are lost. Alert on a
rising number of signature failures.
Wrong sandbox or production secret
Sandbox and production are separate. Each has its own registered endpoint and its own secret. Make sure each handler uses the secret registered in the same environment.
Was this page helpful?