How to verify shipping webhook signatures and handle retries safely

To verify shipping webhook signatures, recompute an HMAC-SHA256 hash of the raw request body with your shared secret, compare it to the signature header using a constant-time function, and reject stale timestamps. This guide from ExperShip, multi-carrier shipping software with an API, shows the code and how to handle retries safely.
Key takeaways
- Sign-check the raw bytes of the request body, not re-serialized JSON, and compare with a constant-time function.
- Include a timestamp in the signed payload and reject anything older than about five minutes to block replays.
- Webhooks are delivered at least once, so retries and duplicates are normal. Dedupe on the event ID and acknowledge fast.
- Do the slow work (emails, refunds, inventory updates) after you return a 2xx, from a queue.
What is a webhook signature, and why does a shipping webhook need one?
A webhook is an HTTP POST that a service sends to your server when something happens, such as a package moving from "in transit" to "delivered." A webhook signature is a keyed hash (an HMAC, hash-based message authentication code) the sender attaches to each request. Only someone who knows the shared secret can produce a valid one.
Your webhook URL is just a public endpoint. Anyone who finds it can POST to it. Without a signature check, a forged "delivered" event could trigger a review request, close a support ticket, release a drop-ship payment or mark a refund as unnecessary. The damage is rarely dramatic. It is usually quiet and expensive: wrong statuses flowing into customer emails and ERP records for weeks before anyone notices.
If you are new to the concept, the tracking webhooks explainer covers how push-based tracking works and why it beats polling. This article is the security and reliability follow-up, and it sits under the broader shipping API guide.
How do you verify a shipping webhook signature step by step?
The scheme below is the common pattern (HMAC-SHA256 over timestamp plus body). Header names, encoding (hex or base64) and the exact signed string differ between providers, so treat the names here as placeholders and confirm the real values in your provider's documentation, including the ExperShip developer pages.
- Capture the raw body. Read the request as bytes or a plain string before any JSON parser touches it. Parsing and re-stringifying changes whitespace and key order, and the hash will no longer match.
- Read the signature and timestamp headers. If either is missing, return 400 and stop.
- Check the timestamp. Reject if it differs from your server clock by more than your tolerance (300 seconds is a sensible default). This is your replay defense.
- Build the signed payload. Usually
timestamp + "." + rawBody. - Compute the HMAC-SHA256 of that string with your webhook secret and encode it the way the sender does.
- Compare in constant time. Use
crypto.timingSafeEqual(Node) orhmac.compare_digest(Python). A plain===can leak how many leading characters matched. - Only then parse the JSON and process the event.
Node.js (Express) example
Note express.raw on this route. If you register express.json() globally first, the raw body is gone.
import express from "express";
import crypto from "node:crypto";
const app = express();
const SECRET = process.env.WEBHOOK_SECRET;
const TOLERANCE_SECONDS = 300;
app.post("/webhooks/shipping",
express.raw({ type: "application/json" }),
async (req, res) => {
const timestamp = req.get("X-Webhook-Timestamp");
const signature = req.get("X-Webhook-Signature");
if (!timestamp || !signature) return res.sendStatus(400);
const age = Math.abs(Date.now() / 1000 - Number(timestamp));
if (!Number.isFinite(age) || age > TOLERANCE_SECONDS) {
return res.sendStatus(400);
}
const signedPayload = `${timestamp}.${req.body.toString("utf8")}`;
const expected = crypto
.createHmac("sha256", SECRET)
.update(signedPayload)
.digest("hex");
const a = Buffer.from(expected, "hex");
const b = Buffer.from(signature, "hex");
if (a.length !== b.length || !crypto.timingSafeEqual(a, b)) {
return res.sendStatus(401);
}
const event = JSON.parse(req.body.toString("utf8"));
await saveAndQueue(event); // dedupe + enqueue, see below
res.sendStatus(200);
});Python (Flask) example
import hmac, hashlib, time, os
from flask import Flask, request, abort
app = Flask(__name__)
SECRET = os.environ["WEBHOOK_SECRET"].encode()
@app.post("/webhooks/shipping")
def shipping_webhook():
ts = request.headers.get("X-Webhook-Timestamp")
sig = request.headers.get("X-Webhook-Signature", "")
if not ts:
abort(400)
try:
if abs(time.time() - float(ts)) > 300:
abort(400)
except ValueError:
abort(400)
body = request.get_data() # raw bytes
signed = ts.encode() + b"." + body
expected = hmac.new(SECRET, signed, hashlib.sha256).hexdigest()
if not hmac.compare_digest(expected, sig):
abort(401)
save_and_queue(request.get_json())
return "", 200The underlying construction is standardized in RFC 2104 (HMAC), and the Node comparison function is documented in the Node.js crypto reference.

Why does signature verification fail even when the secret is right?
Most failures in practice are not attacks. They are plumbing. These are the ones that eat an afternoon:
| Symptom | Likely cause | Fix |
|---|---|---|
| Every request fails, secret confirmed | Body was parsed and re-serialized before hashing | Use a raw-body parser on the webhook route only |
| Works locally, fails in production | Proxy, CDN or framework middleware alters the body, or a different secret is loaded | Log the body length and a hash of it at the edge and in the app; check the environment variable |
| Intermittent timestamp rejections | Server clock drift | Run NTP time sync; keep tolerance at 300 seconds, not 5 |
| Hex vs. base64 mismatch | Encoding differs from what the sender uses | Match the documented encoding exactly |
| Fails after secret rotation | Old secret still in use | Accept both old and new secrets during a short overlap window |
| Test events pass, live events fail | Separate test and live secrets | Store them under separate config keys |
Why do shipping webhooks get retried?
Most webhook senders guarantee at-least-once delivery: they would rather send an event twice than lose it. If your endpoint times out, returns a 5xx, or the connection drops, the sender tries again, usually with exponential backoff (waits that grow longer each attempt) over hours or days. The exact schedule is provider-specific, so read it rather than assuming.
Two consequences follow. First, your handler will see duplicates, sometimes even when you did return 200 (the response can be lost on the way back). Second, events can arrive out of order: a retried "out for delivery" can land after "delivered."
What should your endpoint return?
| Situation | Response | Why |
|---|---|---|
| Valid signature, event stored | 200 (or 204) | Tells the sender to stop retrying |
| Duplicate event you already stored | 200 | Retrying again will never help |
| Missing headers or stale timestamp | 400 | Malformed or replayed request |
| Bad signature | 401 | Do not explain why in the body |
| Your database is down | 500 or 503 | You want the sender to retry later |
Answer within a few seconds. A common mistake is doing the full job inside the request: send the customer email, call the ERP, update inventory, then respond. Under load that blows through the sender's timeout, which triggers a retry, which does the work again. Store the event, enqueue it, return 200.
How do you make a webhook handler idempotent?
Idempotent means processing the same event twice has the same result as processing it once. It is the same principle as the one in our guide to avoiding duplicate labels with idempotency keys, applied on the receiving side.
- Find the unique event ID in the payload (not the tracking number, which repeats across many events).
- Insert it into a table with a unique constraint and let the database decide who wins:
CREATE TABLE webhook_events ( event_id text PRIMARY KEY, payload jsonb NOT NULL, received_at timestamptz NOT NULL DEFAULT now(), processed_at timestamptz ); INSERT INTO webhook_events (event_id, payload) VALUES ($1, $2) ON CONFLICT (event_id) DO NOTHING; - If zero rows were inserted, it is a duplicate. Return 200 and do nothing else.
- Process from the table, not from memory. A worker picks up rows where
processed_at IS NULL. If the app crashes between insert and enqueue, the worker still finds the row. That removes the "stored but never queued" gap. - Make side effects safe too. If the handler sends a "your order was delivered" email, record that it was sent per shipment and status so a replay cannot send it again.
How do you handle out-of-order events?
Do not blindly overwrite the shipment's current status with whatever arrives last. Store the event's own occurrence time (the carrier scan time, not your receive time) and apply an update only if it is newer than what you hold. Treat terminal states such as delivered or returned to sender as sticky unless a newer event explicitly supersedes them. Keep every event in your log anyway, since the full timeline is useful for support.
What other safeguards belong on a webhook endpoint?
- HTTPS only. The signature proves authenticity, not secrecy. Tracking payloads contain names, addresses and tracking numbers, so keep them encrypted in transit.
- Keep the secret out of code. Use a secrets manager or environment variable, one secret per environment, and rotate on a schedule or after any staff departure that had access.
- Cap request size. A 1 MB limit on the webhook route stops oversized junk before you hash it.
- Do not log secrets or full signatures. Log the event ID and the verification result.
- Alert on spikes of 401s. A burst of failed signatures is either a misconfiguration after a deploy or someone probing your URL. Both deserve a look.
- Build a replay tool. A script that re-queues stored events by ID saves hours after a bug fix. Re-processing from your own table is safer than asking the provider to resend.
- Add a reconciliation job. Even good webhooks occasionally go missing. A daily pass that polls tracking for shipments still in transit after an expected window closes the gap.
How do you test webhook verification before going live?
- Write a unit test that signs a fixture body with a known test secret and asserts your function accepts it.
- Add negative tests: one flipped character in the body, a wrong secret, a timestamp ten minutes old, a missing header, a truncated signature. All must be rejected.
- Send the same valid event twice and confirm one database row and one side effect.
- Send an older event after a newer one and confirm the status does not regress.
- Temporarily make your handler return 500 and confirm the sender retries and the event is eventually stored once.
Where does this fit in a shipping integration?
Webhooks are the receiving half of an integration. The sending half is buying labels, which is where idempotency keys matter, and which is covered in how to create a shipping label with an API. Once a label exists, tracking events flow back to you, and the checks above keep those events trustworthy. The ExperShip API is included on the Growth plan ($49.99/month, 5,000 labels a month), and the developer pages are the place to confirm current event types and signing details before you build.
Frequently asked questions
What is the most common mistake when verifying webhook signatures?
Hashing the parsed-then-re-serialized JSON instead of the raw request body. Even tiny whitespace or key-order changes produce a different hash, so every legitimate request fails verification.
How long should the timestamp tolerance be?
Five minutes (300 seconds) is a common default. It is tight enough to limit replays and loose enough to absorb normal clock drift and network delay.
Should I return 200 or an error when I receive a duplicate webhook?
Return 200. The event was already handled, and an error would just make the sender keep retrying a delivery that can never matter.
Do I still need signature checks if my webhook URL is hard to guess?
Yes. An obscure URL is not authentication, and URLs leak through logs, proxies and config files. The signature is what proves the request came from the sender.
Ready to build against a multi-carrier shipping API? Start your 30-day free trial on Starter or Growth, no card needed to sign up.