RespireSoft InvoicingAPI docsReferenceWebhooks

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
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"]}'
Node
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
PHP
$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 now
Python
import 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 now

Rules for the address:

What we send

A POST with a JSON body, which is the event document, and three headers in the Standard Webhooks format.

HeaderMeaning
webhook-idThe event id (evt_…). The same on every retry and replay: use it to ignore duplicates.
webhook-timestampUnix time in seconds of this attempt.
webhook-signaturev1,<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

  1. Read the raw body. Do not parse and re-encode it first.
  2. Reject the call when webhook-timestamp is more than 5 minutes from your clock.
  3. Compute the signature and compare it, in constant time, with each v1, value in the header. One match is enough.
  4. Answer 2xx quickly (we wait 10 seconds), then do the slow work in a queue.
curl
# 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.
Node
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) })
PHP
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'));
Python
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.

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