Verifying signatures

Every request we send is signed with the endpoint’s secret. Checking the signature proves the request came from APISync and that nobody changed the body on the way.

What gets signed#

The signature is an HMAC-SHA256, written as lowercase hex. The key is the endpoint secret. The message is three values joined by dots:

{APISync-Delivery-Id}.{APISync-Timestamp}.{raw request body}

The key is the secret string exactly as we gave it to you, whsec_ prefix included, as UTF-8 bytes. Don’t strip the prefix and don’t base64-decode anything. This trips up roughly one new customer a month, because a few other webhook schemes do decode their secrets.

The delivery id is in the signed message so that a captured request can’t be replayed with a different id to get past your deduplication. The timestamp is there so you can reject old requests.

The signature header#

POST /hooks/apisync HTTP/1.1
Host: shop.example.com
Content-Type: application/json
APISync-Delivery-Id: dlv_9cXr2TfB0wLq6nPe
APISync-Timestamp: 1793715611
APISync-Signature: v1=34a0b89c0b2638cc03406d8e0ac506d48f6820d15f02104dbd802dbda9302ede

APISync-Signature holds one or more space-separated v1=<hex> values. Usually there is one. During a secret rotation there are two, one per secret, and a request is valid if any of them matches. Ignore values with a version you don’t know; we’ll announce a v2 in the changelog long before relying on it.

Step by step#

  1. Read the body as raw bytes, before any JSON parsing.
  2. Read APISync-Delivery-Id and APISync-Timestamp. Reject the request if either is missing.
  3. Reject it if the timestamp is more than 5 minutes away from your clock, in either direction.
  4. Compute HMAC-SHA256 over id + "." + timestamp + "." + body with the secret as key.
  5. Compare it with each v1= value using a constant-time comparison. Accept if one matches.

Code#

Complete, runnable handlers. They use Express 4, Flask 2 and the Go standard library (1.22 or newer); the verify function itself has no dependencies beyond the standard library in all three.

const crypto = require('node:crypto');
const express = require('express');

const SECRET = process.env.APISYNC_SECRET; // the whole whsec_... string
const TOLERANCE = 300; // seconds

function verify(rawBody, headers, now = Date.now() / 1000) {
  const id = headers['apisync-delivery-id'];
  const tsHeader = headers['apisync-timestamp'];
  const ts = Number(tsHeader);
  if (!id || !Number.isInteger(ts) || Math.abs(now - ts) > TOLERANCE) {
    return false;
  }
  const expected = crypto
    .createHmac('sha256', SECRET)
    .update(`${id}.${tsHeader}.`)
    .update(rawBody)
    .digest();

  return String(headers['apisync-signature'] || '')
    .split(' ')
    .some((part) => {
      if (!part.startsWith('v1=')) return false;
      const given = Buffer.from(part.slice(3), 'hex');
      return given.length === expected.length && crypto.timingSafeEqual(given, expected);
    });
}

const app = express();

// express.raw keeps the body as a Buffer. Do not put express.json() in front of this route.
app.post('/webhooks/apisync', express.raw({ type: '*/*' }), (req, res) => {
  if (!verify(req.body, req.headers)) {
    return res.status(400).send('bad signature');
  }
  const event = JSON.parse(req.body);
  console.log(req.headers['apisync-event-type'], event.id);
  res.sendStatus(204);
});

app.listen(3000);
import hashlib
import hmac
import os
import time

from flask import Flask, abort, request

SECRET = os.environ["APISYNC_SECRET"].encode()  # the whole whsec_... string
TOLERANCE = 300  # seconds


def verify(raw_body: bytes, headers, now=None) -> bool:
    delivery_id = headers.get("APISync-Delivery-Id", "")
    ts = headers.get("APISync-Timestamp", "")
    if not delivery_id or not ts.isdigit():
        return False
    now = time.time() if now is None else now
    if abs(now - int(ts)) > TOLERANCE:
        return False
    signed = f"{delivery_id}.{ts}.".encode() + raw_body
    expected = hmac.new(SECRET, signed, hashlib.sha256).hexdigest().encode()
    for part in headers.get("APISync-Signature", "").split():
        version, _, sig = part.partition("=")
        if version == "v1" and hmac.compare_digest(sig.encode(), expected):
            return True
    return False


app = Flask(__name__)


@app.post("/webhooks/apisync")
def apisync_webhook():
    # get_data() returns the raw bytes; request.json would re-encode them
    if not verify(request.get_data(), request.headers):
        abort(400)
    event = request.get_json()
    print(request.headers["APISync-Event-Type"], event["id"])
    return "", 204
package main

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"io"
	"log"
	"net/http"
	"os"
	"strconv"
	"strings"
	"time"
)

const tolerance = 300 * time.Second

func verify(secret, body []byte, h http.Header, now time.Time) bool {
	id := h.Get("APISync-Delivery-Id")
	ts := h.Get("APISync-Timestamp")
	sec, err := strconv.ParseInt(ts, 10, 64)
	if id == "" || err != nil {
		return false
	}
	if d := now.Sub(time.Unix(sec, 0)); d > tolerance || d < -tolerance {
		return false
	}
	mac := hmac.New(sha256.New, secret)
	mac.Write([]byte(id + "." + ts + "."))
	mac.Write(body)
	expected := mac.Sum(nil)

	for _, part := range strings.Fields(h.Get("APISync-Signature")) {
		hexSig, ok := strings.CutPrefix(part, "v1=")
		if !ok {
			continue
		}
		sig, err := hex.DecodeString(hexSig)
		if err == nil && hmac.Equal(sig, expected) {
			return true
		}
	}
	return false
}

func main() {
	secret := []byte(os.Getenv("APISYNC_SECRET")) // the whole whsec_... string

	// Method patterns in ServeMux need Go 1.22 or newer.
	http.HandleFunc("POST /webhooks/apisync", func(w http.ResponseWriter, r *http.Request) {
		body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20))
		if err != nil || !verify(secret, body, r.Header, time.Now()) {
			http.Error(w, "bad signature", http.StatusBadRequest)
			return
		}
		log.Printf("%s %s", r.Header.Get("APISync-Event-Type"), r.Header.Get("APISync-Event-Id"))
		w.WriteHeader(http.StatusNoContent)
	})
	log.Fatal(http.ListenAndServe(":3000", nil))
}

Test vector#

Use these values in a unit test. Turn the timestamp check off for the test, or pass a fixed now as the code above allows; the timestamp is from 3 Nov 2026.

InputValue
Secretwhsec_Zq3v8TnR1xKc6pLm0Wb4yJf2
APISync-Delivery-Iddlv_9cXr2TfB0wLq6nPe
APISync-Timestamp1793715611
Body{"id":"evt_5Jm1Rk8vQs2Hx7Ta","type":"invoice.paid","source":"src_7Hq2Lw9xVb3e","data":{"invoice":"in_1042","amount":4900,"currency":"eur"}}

The signed message, then the expected header:

dlv_9cXr2TfB0wLq6nPe.1793715611.{"id":"evt_5Jm1Rk8vQs2Hx7Ta","type":"invoice.paid","source":"src_7Hq2Lw9xVb3e","data":{"invoice":"in_1042","amount":4900,"currency":"eur"}}
APISync-Signature: v1=34a0b89c0b2638cc03406d8e0ac506d48f6820d15f02104dbd802dbda9302ede

If you get a different value, check for a trailing newline in the body or the secret. Copying from a terminal adds one more often than you’d think.

Rotating the secret#

POST /endpoints/{id}/rotate_secret creates a new secret and returns it. The old secret stays valid for 24 hours by default (expire_old_in, up to 7 days). During that window, every request carries two v1= values, so the code above keeps working whichever secret your servers have. Deploy the new secret, wait for it to reach every instance, and the old one simply expires.

If a secret has leaked, rotate with "expire_old_in": 0. Requests in flight signed with the old secret will then fail verification and be retried with the new one.

Common mistakes#

  • Verifying parsed JSON. JSON.stringify(req.body) after express.json() doesn’t give you the same bytes: key order, spacing and number formatting can all change. Use express.raw() on the webhook route, request.get_data() in Flask, request.body in Django.
  • Comparing with ==. It works, but leaks timing. Use crypto.timingSafeEqual, hmac.compare_digest or hmac.Equal.
  • Splitting the header on commas. Values are separated by spaces.
  • A clock that is off. Containers without NTP drift. If verification fails only on some hosts, compare their clocks before anything else.
  • Middleware that rewrites the body. Some API gateways re-encode JSON or change line endings. Verify as close to the edge as you can, or have the gateway pass the body through untouched.

The original provider signature#

In raw format the body is byte-for-byte what the provider sent, and headers such as Stripe-Signature or X-Hub-Signature-256 are passed through. Their signatures will still verify, as long as you check them inside the provider’s own tolerance window. Stripe’s libraries default to 5 minutes, so a delivery that succeeds on its fourth attempt, 12 minutes later, fails a Stripe check. Verify ours instead, and let APISync check the provider’s signature at ingest by setting verify_secret on the source.

Last updated 20 Oct 2026