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
| Type | Sent when | data |
|---|---|---|
session.completed | The result is available. | { "status": "completed", "mode": "intake" | "ambient" } |
session.failed | Processing failed for good. | { "status": "failed", "error_code": "…" } |
session.deleted | A 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
{
"id": "evt_01JDKD0V8N",
"type": "session.completed",
"created_at": "2027-01-12T13:09:41Z",
"session": "ses_01JDK8Z3Q4",
"data": {
"status": "completed",
"mode": "intake"
}
}| Field | Description |
|---|---|
id | Event id, prefixed evt_. The same value as the webhook-id header, and the same on every retry. |
type | The event type. |
created_at | When the event occurred. |
session | The id of the session the event is about. |
data | A 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.
| Header | Content |
|---|---|
webhook-id | The event id. Stable across retries: use it to de-duplicate. |
webhook-timestamp | Unix seconds of this delivery attempt. It changes on every retry. |
webhook-signature | v1, 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.
- 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 aswhsec_...decodes to an empty key, and an empty key would make every forged signature computable. - Read the raw request body, exactly as received. Do not parse and re-serialise it.
- Build the signed content:
{webhook-id}.{webhook-timestamp}.{raw body}. - Compute HMAC-SHA256 of that content with the decoded key, and base64-encode it.
- Compare it, in constant time, with each
v1,signature in the header. One match is enough. - Reject the delivery if
webhook-timestampis 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. - De-duplicate by
webhook-id, as described under Idempotency and ordering. That is what makes a replay harmless.
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 Falseimport { createHmac, timingSafeEqual } from 'node:crypto';
const TOLERANCE_SECONDS = 5 * 60;
export interface WebhookHeaders {
id: string; // webhook-id
timestamp: string; // webhook-timestamp
signature: string; // webhook-signature
}
/**
* Decodes a signing secret of the form `whsec_<base64>` into the HMAC key.
* Throws 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.
*/
export function webhookKey(secret: string | undefined): Buffer {
const encoded = secret?.startsWith('whsec_') ? secret.slice('whsec_'.length) : '';
const key = Buffer.from(encoded, 'base64');
if (key.length === 0 || key.toString('base64') !== encoded) {
throw new Error('Webhook signing secret is missing or malformed; expected whsec_<base64>');
}
return key;
}
/**
* Returns true when the delivery was signed with your webhook secret.
* `rawBody` must be the exact bytes received, before any JSON parsing.
*/
export function verifyWebhook(
secret: string | undefined,
headers: WebhookHeaders,
rawBody: string | Buffer,
now: number = Math.floor(Date.now() / 1000),
): boolean {
const key = webhookKey(secret);
if (!/^\d+$/.test(headers.timestamp) || Math.abs(now - Number(headers.timestamp)) > TOLERANCE_SECONDS) {
return false;
}
const body = typeof rawBody === 'string' ? Buffer.from(rawBody, 'utf8') : rawBody;
const expected = createHmac('sha256', key)
.update(`${headers.id}.${headers.timestamp}.`)
.update(body)
.digest();
// During secret rotation the header carries two space-separated signatures.
return headers.signature.split(' ').some((candidate) => {
const [version, value] = candidate.split(',');
if (version !== 'v1' || !value) return false;
const received = Buffer.from(value, 'base64');
return received.length === expected.length && timingSafeEqual(received, expected);
});
}Test vector
Use this fixed example to check your implementation before you receive a real event.
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:
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)import assert from 'node:assert';
import { verifyWebhook } from './verify-webhook';
const body = '{"id":"evt_01JDKD0V8N","type":"session.completed","created_at":"2027-01-12T13:09:41Z","session":"ses_01JDK8Z3Q4","data":{"status":"completed","mode":"intake"}}';
const headers = {
id: 'evt_01JDKD0V8N',
timestamp: '1799759381',
signature: 'v1,muUt2xSSScYeqUcUU5QBZQxFupohoKCdKlPIboefNFg=',
};
// Pass the vector's own time as "now", so the 5-minute check does not reject it.
assert.ok(verifyWebhook('whsec_cGFydG5lci13ZWJob29rLXRlc3Qtc2VjcmV0LTAwMDE=', headers, body, 1799759381));
assert.ok(!verifyWebhook('whsec_cGFydG5lci13ZWJob29rLXRlc3Qtc2VjcmV0LTAwMDE=', headers, body + ' ', 1799759381));Responding
- Answer with any
2xxstatus 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.
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 "", 204import { createServer } from 'node:http';
import { verifyWebhook, webhookKey } from './verify-webhook'; // see the Webhooks guide
const secret = process.env.AIMEDINTAKE_WEBHOOK_SECRET;
webhookKey(secret); // refuse to start with a missing or malformed secret
createServer(async (request, response) => {
const chunks: Buffer[] = [];
for await (const chunk of request) chunks.push(chunk as Buffer);
const rawBody = Buffer.concat(chunks); // the raw bytes, not the parsed JSON
const ok = verifyWebhook(
secret,
{
id: String(request.headers['webhook-id'] ?? ''),
timestamp: String(request.headers['webhook-timestamp'] ?? ''),
signature: String(request.headers['webhook-signature'] ?? ''),
},
rawBody,
);
if (!ok) {
response.writeHead(400).end();
return;
}
const event = JSON.parse(rawBody.toString('utf8'));
// One atomic insert keyed by the event id: a duplicate delivery changes nothing.
await queue.insertIfAbsent(event.id, event);
response.writeHead(204).end();
}).listen(8080);Retries
A failed delivery is retried on this schedule, measured from the previous attempt:
| Retry | 1 | 2 | 3 | 4 | 5 | 6 | Later |
|---|---|---|---|---|---|---|---|
| Delay | 1 min | 5 min | 30 min | 2 h | 6 h | 12 h | every 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-idin 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:
GET /v1/sessions?updated_since=2027-01-12T00:00:00ZThe 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.