Skip to Content
FastracDocs

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:

HeaderExampleMeaning
content-typeapplication/jsonThe body is JSON.
user-agentFastrac-Webhook-Client/1.0Identifies Shipping Engine. Don't rely on it for security.
x-webhook-id7d0f3c1e-2b8a-4f61-9a55-0c3e9b7d21aaUnique event ID. The same on every retry of the event. Use it to drop duplicates.
x-webhook-timestamp1795670142When this attempt was signed, in Unix seconds. New on every attempt.
x-webhook-signaturekeyId=key-2026-11,sig=5b1e…c9The keyId of the secret used, and the hex-encoded signature.
x-webhook-event-typeshipment.deliveredThe event name. See Events.
x-webhook-schema-version2025-10-01The payload format version.
x-webhook-attempt1Attempt 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:

  1. Read the raw body bytes before any JSON parsing.
  2. Read x-webhook-id, x-webhook-timestamp and x-webhook-signature. If one is missing, reject the request.
  3. Split x-webhook-signature on , and then each part on the first =, to get keyId and sig.
  4. Look up your secret for that keyId. If you don't know the keyId, reject the request.
  5. Check the timestamp: if it is more than 300 seconds away from your clock, reject the request.
  6. Compute body_hash, then signed_payload, then the expected HMAC, exactly as above.
  7. Compare the expected value with sig using a constant-time comparison.
  8. Only now parse the JSON and handle the event.

Worked example

Use this to test your code:

InputValue
Secrettest_secret_for_docs_0123456789abcdef
x-webhook-timestamp1795670142
x-webhook-id7d0f3c1e-2b8a-4f61-9a55-0c3e9b7d21aa
Raw body{"shipment_code":"SHP-261120-ABC123"}
Expected values
body_hash      = deeb8ffc05c92e388cd6a6761d26c97e5162bd2bc227d558ee9d28f2c1b21000
signed_payload = 1795670142.7d0f3c1e-2b8a-4f61-9a55-0c3e9b7d21aa.deeb8ffc05c92e388cd6a6761d26c97e5162bd2bc227d558ee9d28f2c1b21000
sig            = 58cdbbf52e2c22a6ddbdd3ac30d5bb1c9cbe3dfca420734d767b395db19dc46c

The 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).

verify.js
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);
}
server.js (Express)
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:

  1. Generate a new secret and pick a new keyId, for example key-2027-01.
  2. Deploy your handler with both secrets in the keyId → secret map.
  3. Call POST /b2b/webhook/setWebhook with the new secret and keyId (and your usual URL and filters).
  4. Check that data.activeSecretKeyIds shows the new keyId.
  5. 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?

On this page