Skip to content

Guides

Webhooks

Events, payloads, signature verification with a test vector, retries, idempotency and ordering.

Webhooks notify your server when a session reaches a final state, so you never have to wait on a request or ask repeatedly. Events are small and signed, and they carry no transcript or result text: they tell you which session changed, and you fetch the details with your key.

Events

Webhook events
TypeSent whendata
session.completedThe result is available.{ "status": "completed", "mode": "intake" | "ambient" }
session.failedProcessing failed for good.{ "status": "failed", "error_code": "…" }
session.deletedA DELETE request was accepted.{ "status": "deleted", "reason": "erasure" }

error_code is one of the session error codes. Two changes send no event: a session that expires without a transcript, and a retention purge. Both are visible through listing. New event types may be added; ignore types you do not handle and still answer 2xx.

Payload

session.completed
{
  "id": "evt_01JDKD0V8N",
  "type": "session.completed",
  "created_at": "2027-01-12T13:09:41Z",
  "session": "ses_01JDK8Z3Q4",
  "data": {
    "status": "completed",
    "mode": "intake"
  }
}
Event fields
FieldDescription
idEvent id, prefixed evt_. The same value as the webhook-id header, and the same on every retry.
typeThe event type.
created_atWhen the event occurred.
sessionThe id of the session the event is about.
dataA small object that depends on the type, shown above.

Events contain no transcript or result text, and they do not contain your external_ref. What they do reveal is: the session id, the event type and a time; for a completed session its mode (intake or ambient); for a failed session the failure code; and for a deletion the fact that the data was erased at your request. A party that receives an event by mistake, and can link that session id to a person, learns those things about that person’s session. To act on an event, fetch the session or its result with your key.

Headers

Deliveries follow the Standard Webhooks conventions.

Webhook headers
HeaderContent
webhook-idThe event id. Stable across retries: use it to de-duplicate.
webhook-timestampUnix seconds of this delivery attempt. It changes on every retry.
webhook-signaturev1, followed by the base64 signature. During secret rotation it holds two signatures separated by a space.

Verifying signatures

Verify every delivery before you trust it. Your signing secret has the form whsec_<base64>; the key is the decoded part after the prefix.

  1. At startup, decode the secret and refuse to start if it is missing, lacks the whsec_ prefix, is not valid base64 or decodes to nothing. A placeholder such as whsec_... decodes to an empty key, and an empty key would make every forged signature computable.
  2. Read the raw request body, exactly as received. Do not parse and re-serialise it.
  3. Build the signed content: {webhook-id}.{webhook-timestamp}.{raw body}.
  4. Compute HMAC-SHA256 of that content with the decoded key, and base64-encode it.
  5. Compare it, in constant time, with each v1, signature in the header. One match is enough.
  6. Reject the delivery if webhook-timestamp is more than 5 minutes from your clock. This bounds how old a replayed delivery can be; it does not stop a replay inside that window.
  7. De-duplicate by webhook-id, as described under Idempotency and ordering. That is what makes a replay harmless.
Verify a delivery
import base64
import binascii
import hashlib
import hmac
import time

TOLERANCE_SECONDS = 5 * 60


def webhook_key(secret):
    """Decode a signing secret of the form whsec_<base64> into the HMAC key.

    Raises ValueError when the secret is missing, a placeholder or not valid
    base64, so a misconfigured receiver stops at startup instead of verifying
    with an empty key.
    """
    error = ValueError("Webhook signing secret is missing or malformed; expected whsec_<base64>")
    if not secret or not secret.startswith("whsec_"):
        raise error
    encoded = secret.removeprefix("whsec_")
    try:
        key = base64.b64decode(encoded, validate=True)
    except (binascii.Error, ValueError):
        raise error from None
    if not key or base64.b64encode(key).decode() != encoded:
        raise error
    return key


def verify_webhook(secret, webhook_id, timestamp, signature_header, raw_body, now=None):
    """Return True when the delivery was signed with your webhook secret.

    raw_body must be the exact bytes received, before any JSON parsing.
    """
    key = webhook_key(secret)
    now = int(time.time()) if now is None else now
    if not (timestamp.isascii() and timestamp.isdigit()):
        return False
    if abs(now - int(timestamp)) > TOLERANCE_SECONDS:
        return False

    signed = f"{webhook_id}.{timestamp}.".encode() + raw_body
    expected = hmac.new(key, signed, hashlib.sha256).digest()

    # During secret rotation the header carries two space-separated signatures.
    for candidate in signature_header.split(" "):
        version, _, value = candidate.partition(",")
        if version != "v1" or not value:
            continue
        try:
            received = base64.b64decode(value, validate=True)
        except (binascii.Error, ValueError):
            continue
        if hmac.compare_digest(received, expected):
            return True
    return False

Test vector

Use this fixed example to check your implementation before you receive a real event.

Test vector
secret:            whsec_cGFydG5lci13ZWJob29rLXRlc3Qtc2VjcmV0LTAwMDE=
webhook-id:        evt_01JDKD0V8N
webhook-timestamp: 1799759381
body:              {"id":"evt_01JDKD0V8N","type":"session.completed","created_at":"2027-01-12T13:09:41Z","session":"ses_01JDK8Z3Q4","data":{"status":"completed","mode":"intake"}}

signed content:    evt_01JDKD0V8N.1799759381.<body>
signature:         v1,muUt2xSSScYeqUcUU5QBZQxFupohoKCdKlPIboefNFg=

Both functions above verify it. The vector’s timestamp is fixed, so supply it as the current time:

Check the test vector
from verify_webhook import verify_webhook

body = b'{"id":"evt_01JDKD0V8N","type":"session.completed","created_at":"2027-01-12T13:09:41Z","session":"ses_01JDK8Z3Q4","data":{"status":"completed","mode":"intake"}}'
args = ("evt_01JDKD0V8N", "1799759381", "v1,muUt2xSSScYeqUcUU5QBZQxFupohoKCdKlPIboefNFg=")

# Pass the vector's own time as "now", so the 5-minute check does not reject it.
assert verify_webhook("whsec_cGFydG5lci13ZWJob29rLXRlc3Qtc2VjcmV0LTAwMDE=", *args, body, now=1799759381)
assert not verify_webhook("whsec_cGFydG5lci13ZWJob29rLXRlc3Qtc2VjcmV0LTAwMDE=", *args, body + b" ", now=1799759381)

Responding

  • Answer with any 2xx status within 10 seconds. Anything else, or a timeout, counts as a failure and is retried.
  • Acknowledge first, work later: store the event durably, answer, and process it from your own queue. Do not fetch the result inside the request.
  • Redirects are not followed. Register the final URL.
  • The response body is ignored.
Webhook receiver
import os
from flask import Flask, request

from verify_webhook import verify_webhook, webhook_key  # see the Webhooks guide

SECRET = os.environ.get("AIMEDINTAKE_WEBHOOK_SECRET")
webhook_key(SECRET)  # refuse to start with a missing or malformed secret

app = Flask(__name__)


@app.post("/webhooks/aimedintake")
def receive():
    ok = verify_webhook(
        SECRET,
        request.headers.get("webhook-id", ""),
        request.headers.get("webhook-timestamp", ""),
        request.headers.get("webhook-signature", ""),
        request.get_data(),  # the raw bytes, not the parsed JSON
    )
    if not ok:
        return "", 400

    event = request.get_json()
    # One atomic insert keyed by the event id: a duplicate delivery changes nothing.
    queue.insert_if_absent(event["id"], event)
    return "", 204

Retries

A failed delivery is retried on this schedule, measured from the previous attempt:

Retry schedule
Retry123456Later
Delay1 min5 min30 min2 h6 h12 hevery 24 h

Retries stop 72 hours after the event was created. Each attempt is signed again with a fresh webhook-timestamp, so a retried delivery always passes the 5-minute check, while webhook-id stays the same.

Idempotency and ordering

  • Expect duplicates. Delivery is at least once. Record each webhook-id in durable storage with one atomic insert-if-absent, in the same step that queues the event, and skip ids that are already there. Keep the records for at least 7 days.
  • Do not rely on order. Events for different sessions, and retries, can arrive in any order. Treat an event as a signal to read the current state: fetch the session and act on its status.
  • Make handlers repeatable. Fetching and storing a result twice should leave your system in the same state.

Recovering missed events

If your endpoint was unavailable for longer than the 72-hour retry window, or you want certainty, reconcile with the list endpoint. Ask for everything that changed since your last successful sync:

HTTP
GET /v1/sessions?updated_since=2027-01-12T00:00:00Z

The incremental sync loop does exactly this, and running it on a schedule behind your webhook handler turns most missed events into a delay. It has limits: a result can only be fetched until the session is purged or deleted, and a deletion is only visible for 90 days. Recovery windows sets them out.

Endpoint requirements

  • HTTPS only, with a valid certificate.
  • Publicly reachable. The hostname must resolve to a public address. This is checked when the endpoint is registered and again before each delivery; private and internal addresses are refused.
  • One endpoint per organization. Your test organization has its own endpoint and its own secret.

Your endpoint and signing secret are registered through your AI Medical Intake contact. To rotate the secret, ask for a new one: for the overlap period every delivery carries two signatures, one from each secret, so both old and new verifiers accept it. Switch your verifier to the new secret, then ask us to retire the old one.