Webhooks
When a document reaches succeeded or failed, Sonic Docs can send one notification to your HTTPS endpoint. Webhooks report terminal outcomes only; use events for progress.
The notification
Section titled “The notification”Sonic Docs sends a POST with a JSON body:
{ "type": "document.succeeded", "document_id": "a~d17", "delivery_id": "wh_82", "sequence": 10, "occurred_at": "2026-11-30T20:00:10Z", "status_url": "https://docs.example/documents/a~d17", "result_url": "https://docs.example/documents/a~d17/result", "failure": null}type |
result_url |
failure |
|---|---|---|
document.succeeded |
The result manifest URL | null |
document.failed |
null |
The same failure object as the snapshot |
sequence and occurred_at identify the terminal event in the document’s event log.
Verify the signature
Section titled “Verify the signature”Notifications follow the Standard Webhooks specification. Three headers accompany each request:
| Header | Contents |
|---|---|
webhook-id |
The delivery ID; equal to delivery_id in the body |
webhook-timestamp |
Unix time of this attempt, in seconds |
webhook-signature |
One or more space-separated v1,<base64 signature> values |
To verify a request:
- Take the raw request body bytes exactly as received, before any JSON parsing.
- Build the signed content:
webhook-id+.+webhook-timestamp+.+ body. - Compute HMAC-SHA256 over it, using the base64-decoded part of your secret after the
whsec_prefix. - Compare the result with each
v1signature in constant time. Accept if any matches. - Reject the request if the timestamp is more than five minutes from your clock.
Deduplicate and acknowledge
Section titled “Deduplicate and acknowledge”Any 2xx response acknowledges the delivery. Retries reuse the same webhook-id and body, with a fresh timestamp and signature, so record delivery IDs and acknowledge duplicates without processing them again. Keep your handler fast: do the work after responding, or queue it.
Retries
Section titled “Retries”A delivery attempt times out after 10 seconds. A timeout, a connection error or a non-2xx status consumes the attempt. Attempts are made at 0, 5, 30, 120, 600 and 3600 seconds after processing ends; then the delivery is marked exhausted. Redirects are not followed. Delivery problems never change the document’s processing result. The snapshot’s webhook field shows each attempt’s outcome and HTTP status.
Destinations must be public HTTPS addresses. Loopback, private, link-local and cloud metadata addresses are refused, and the address is checked on every attempt.
Example receivers
Section titled “Example receivers”// Sonic Docs contract example: receive and verify signed terminal webhooks (Standard Webhooks).// Written against the planned v1 contract; not yet run against a live API.// Usage: SONIC_WEBHOOK_SECRET=whsec_... PORT=8000 node webhook-receiver.mjsimport { createHmac, timingSafeEqual } from 'node:crypto';import { createServer } from 'node:http';
const secret = process.env.SONIC_WEBHOOK_SECRET;if (!secret?.startsWith('whsec_')) throw new Error('Set SONIC_WEBHOOK_SECRET (whsec_...)');const key = Buffer.from(secret.slice('whsec_'.length), 'base64');const TOLERANCE_SECONDS = 5 * 60;const seen = new Set(); // Use a durable store in production; retries reuse the delivery ID.
function verify(headers, body, now = Date.now() / 1000) { const id = headers['webhook-id']; const timestamp = headers['webhook-timestamp']; const signatures = headers['webhook-signature']; if (!id || !/^\d+$/.test(timestamp ?? '') || !signatures) return false; if (Math.abs(now - Number(timestamp)) > TOLERANCE_SECONDS) return false; const expected = createHmac('sha256', key).update(`${id}.${timestamp}.`).update(body).digest(); return signatures.split(' ').some((entry) => { const [version, value] = entry.split(','); const candidate = Buffer.from(value ?? '', 'base64'); return version === 'v1' && candidate.length === expected.length && timingSafeEqual(candidate, expected); });}
createServer((request, response) => { const chunks = []; request.on('data', (chunk) => chunks.push(chunk)); request.on('end', () => { const body = Buffer.concat(chunks); // Verify the exact bytes before parsing. if (request.method !== 'POST' || !verify(request.headers, body)) { response.writeHead(401).end(); return; } const event = JSON.parse(body); if (!seen.has(event.delivery_id)) { seen.add(event.delivery_id); console.log(event.type, event.document_id, event.result_url ?? event.failure?.code); } response.writeHead(204).end(); // Any 2xx acknowledges, including for duplicates. });}).listen(Number(process.env.PORT ?? 8000), () => console.log('Listening for Sonic Docs webhooks'));"""Sonic Docs contract example: receive and verify signed terminal webhooks (Standard Webhooks).
Written against the planned v1 contract; not yet run against a live API.Usage: SONIC_WEBHOOK_SECRET=whsec_... PORT=8000 python webhook_receiver.py"""import base64import hashlibimport hmacimport jsonimport osimport timefrom http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
SECRET = os.environ["SONIC_WEBHOOK_SECRET"]KEY = base64.b64decode(SECRET.removeprefix("whsec_"))TOLERANCE_SECONDS = 5 * 60seen = set() # Use a durable store in production; retries reuse the delivery ID.
def verify(headers, body, now=None): msg_id = headers.get("webhook-id") timestamp = headers.get("webhook-timestamp", "") signatures = headers.get("webhook-signature") if not msg_id or not timestamp.isdigit() or not signatures: return False if abs((now or time.time()) - int(timestamp)) > TOLERANCE_SECONDS: return False expected = hmac.new(KEY, f"{msg_id}.{timestamp}.".encode() + body, hashlib.sha256).digest() for entry in signatures.split(" "): version, _, value = entry.partition(",") try: candidate = base64.b64decode(value) except ValueError: continue if version == "v1" and hmac.compare_digest(candidate, expected): return True return False
class Receiver(BaseHTTPRequestHandler): def do_POST(self): body = self.rfile.read(int(self.headers.get("Content-Length", 0))) # Verify exact bytes. if not verify(self.headers, body): self.send_response(401) self.end_headers() return event = json.loads(body) if event["delivery_id"] not in seen: seen.add(event["delivery_id"]) print(event["type"], event["document_id"], event["result_url"] or event["failure"]["code"], flush=True) self.send_response(204) # Any 2xx acknowledges, including for duplicates. self.end_headers()
if __name__ == "__main__": server = ThreadingHTTPServer(("", int(os.environ.get("PORT", "8000"))), Receiver) print("Listening for Sonic Docs webhooks", flush=True) server.serve_forever()