Webhooks
We call your server when something happens, for example when an invoice is paid or a receipt is issued, so you do not have to ask.
Set up an endpoint
Add an endpoint under Settings, Developers, Webhooks, or with the API. Give it the address and the events you want. The signing secret (whsec_…) is shown once. Store it next to your other secrets.
curl -X POST https://api.invoicing.respiresoft.com/v1/webhook_endpoints \
-H "Authorization: Bearer $RESPIRESOFT_KEY" \
-H "Idempotency-Key: $(uuidgen)" \
-H "Content-Type: application/json" \
-d '{"url":"https://example.com/webhooks/respiresoft","events":["invoice.paid","receipt.issued"]}'const res = await fetch("https://api.invoicing.respiresoft.com/v1/webhook_endpoints", {
method: "POST",
headers: { Authorization: `Bearer ${process.env.RESPIRESOFT_KEY}`, "Idempotency-Key": crypto.randomUUID(), "Content-Type": "application/json" },
body: JSON.stringify({ url: "https://example.com/webhooks/respiresoft", events: ["invoice.paid", "receipt.issued"] }),
})
const { id, secret } = await res.json() // secret is shown only now$ch = curl_init("https://api.invoicing.respiresoft.com/v1/webhook_endpoints");
curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true,
CURLOPT_HTTPHEADER => ["Authorization: Bearer " . getenv("RESPIRESOFT_KEY"), "Idempotency-Key: " . bin2hex(random_bytes(16)), "Content-Type: application/json"],
CURLOPT_POSTFIELDS => json_encode(["url" => "https://example.com/webhooks/respiresoft", "events" => ["invoice.paid", "receipt.issued"]])]);
$endpoint = json_decode(curl_exec($ch), true); // $endpoint["secret"] is shown only nowimport os, uuid, requests
r = requests.post("https://api.invoicing.respiresoft.com/v1/webhook_endpoints",
headers={"Authorization": "Bearer " + os.environ["RESPIRESOFT_KEY"], "Idempotency-Key": str(uuid.uuid4())},
json={"url": "https://example.com/webhooks/respiresoft", "events": ["invoice.paid", "receipt.issued"]})
secret = r.json()["secret"] # shown only nowRules for the address:
- In live mode it must start with
https://. Test endpoints (made with a test key) may usehttp://. - It must point to a public address. We refuse addresses that resolve to loopback, private, link-local or other reserved ranges, and we check again before every delivery.
- We do not follow redirects. Answer with a
2xxat the address you gave us. - The port is 443, 80 or 1024 and up. No user name or password in the address.
What we send
A POST with a JSON body, which is the event document, and three headers in the Standard Webhooks format.
| Header | Meaning |
|---|---|
webhook-id | The event id (evt_…). The same on every retry and replay: use it to ignore duplicates. |
webhook-timestamp | Unix time in seconds of this attempt. |
webhook-signature | v1,<signature>. During a secret rotation there are two, separated by a space. |
The signature is base64( HMAC-SHA256( key, webhook-id + "." + webhook-timestamp + "." + raw body ) ), where key is the base64 decoding of the secret after the whsec_ prefix.
Verify every call
- Read the raw body. Do not parse and re-encode it first.
- Reject the call when
webhook-timestampis more than 5 minutes from your clock. - Compute the signature and compare it, in constant time, with each
v1,value in the header. One match is enough. - Answer
2xxquickly (we wait 10 seconds), then do the slow work in a queue.
# Check a saved call by hand (bash, openssl and xxd). BODY is the raw body, exactly as received.
SECRET="whsec_…"
HEX=$(printf '%s' "${SECRET#whsec_}" | base64 -d | xxd -p -c 256)
printf '%s.%s.%s' "$WEBHOOK_ID" "$WEBHOOK_TIMESTAMP" "$BODY" \
| openssl dgst -sha256 -mac HMAC -macopt hexkey:"$HEX" -binary | base64
# The result must equal one of the values after "v1," in the webhook-signature header.import crypto from "node:crypto"
export function verify(secret, headers, rawBody) {
const id = headers["webhook-id"], ts = headers["webhook-timestamp"], sigs = headers["webhook-signature"]
if (!id || !ts || !sigs) throw new Error("missing headers")
if (Math.abs(Date.now() / 1000 - Number(ts)) > 300) throw new Error("timestamp too old")
const key = Buffer.from(secret.replace(/^whsec_/, ""), "base64")
const expected = crypto.createHmac("sha256", key).update(`${id}.${ts}.${rawBody}`).digest()
const ok = sigs.split(" ").some((s) => {
const [version, value] = s.split(",")
const got = Buffer.from(value ?? "", "base64")
return version === "v1" && got.length === expected.length && crypto.timingSafeEqual(got, expected)
})
if (!ok) throw new Error("bad signature")
return JSON.parse(rawBody)
}
// Express: app.post("/webhooks/respiresoft", express.raw({ type: "application/json" }), (req, res) => {
// const event = verify(process.env.WHSEC, req.headers, req.body.toString("utf8")); res.sendStatus(200) })function verify_webhook(string $secret, array $headers, string $rawBody): array {
$id = $headers['webhook-id'] ?? ''; $ts = $headers['webhook-timestamp'] ?? ''; $sigs = $headers['webhook-signature'] ?? '';
if ($id === '' || $ts === '' || $sigs === '') throw new RuntimeException('missing headers');
if (abs(time() - (int) $ts) > 300) throw new RuntimeException('timestamp too old');
$key = base64_decode(preg_replace('/^whsec_/', '', $secret));
$expected = base64_encode(hash_hmac('sha256', "$id.$ts.$rawBody", $key, true));
foreach (explode(' ', $sigs) as $s) {
[$version, $value] = array_pad(explode(',', $s, 2), 2, '');
if ($version === 'v1' && hash_equals($expected, $value)) return json_decode($rawBody, true);
}
throw new RuntimeException('bad signature');
}
// $event = verify_webhook(getenv('WHSEC'), array_change_key_case(getallheaders()), file_get_contents('php://input'));import base64, hashlib, hmac, json, time
def verify(secret: str, headers: dict, raw_body: bytes) -> dict:
wid, ts, sigs = headers.get("webhook-id"), headers.get("webhook-timestamp"), headers.get("webhook-signature")
if not (wid and ts and sigs):
raise ValueError("missing headers")
if abs(time.time() - int(ts)) > 300:
raise ValueError("timestamp too old")
key = base64.b64decode(secret.removeprefix("whsec_"))
expected = base64.b64encode(hmac.new(key, f"{wid}.{ts}.".encode() + raw_body, hashlib.sha256).digest()).decode()
for s in sigs.split(" "):
version, _, value = s.partition(",")
if version == "v1" and hmac.compare_digest(expected, value):
return json.loads(raw_body)
raise ValueError("bad signature")Retries, dead letter and replay
Delivery is at least once: you may get the same event twice, so deduplicate on webhook-id. Events of one kind can arrive out of order; fetch the object when order matters.
- A
2xxanswer means delivered. Anything else, a timeout or a connection error is a failure. - We retry after 10 seconds, 30 seconds, 90 seconds, 5 minutes, 15 minutes, 1 hour, 2 hours, 4 hours and then every 6 hours, until 24 hours after the event.
- After that the delivery is dead. It stays in the list for 30 days. Fix your server, then replay it from the app, or with
POST /v1/webhook_deliveries/{id}/replay, or replay all dead ones withPOST /v1/webhook_endpoints/{id}/replay. A replay sends the same event with the samewebhook-id. - If an endpoint keeps failing for more than a day (40 failed attempts in a row and no delivery) we switch it off and email the business. Switch it on again in the app after the fix.
- Test sends a
webhook.testevent now and shows the answer. It is tried once.
Rotate the secret
POST /v1/webhook_endpoints/{id}/rotate_secret returns a new secret, once. For 24 hours by default (0 to 168 hours) every call is signed with both secrets, so you can deploy the new secret and nothing is rejected. Your verification must accept any matching signature in the header, as the code above does.
Good habits
- Keep the endpoint fast. Save the event, answer
200, work later. - Ask only for the events you use.
- Use
GET /v1/events?after=once at start-up to catch up on anything you missed while you were down.