Webhooks
Receive signed webhooks when a response arrives, a detractor is flagged or a ticket changes, and check the Sayvara-Signature header.
Sayvara can call your HTTPS URL when something happens, so your systems do not need to ask again and again. Every call is signed, so you can check it really came from Sayvara.
Subscribe
Subscribe a URL with the REST hooks operations and an API key or token that holds responses.read:
curl -X POST "https://api.sayvara.com/v1/automation/hooks" \
-H "Authorization: Bearer $SAYVARA_API_KEY" \
-H "Content-Type: application/json" \
-d '{ "event": "response.completed", "targetUrl": "https://example.com/webhooks/sayvara" }'The answer has a signingSecret that starts with whsec_. It is shown only once: store it safely. One subscription covers one event; subscribe once per event you need.
Your URL must use https:// and a public host name (no IP address, and no user name or password in the URL).
Events
Sayvara sends ten events: survey.sent, response.received, response.completed, detractor.flagged, ticket.opened, ticket.updated, ticket.closed, outcome.accepted, outcome.rejected and contact.opted_out. See Webhook events for when each is sent and for the published event catalogue, with a JSON Schema and an example body per event.
The request Sayvara sends
A POST to your URL with these headers:
| Header | Value |
|---|---|
Content-Type |
application/json |
User-Agent |
Sayvara-Webhooks/1 |
Sayvara-Event |
The event, for example response.completed. |
Sayvara-Delivery |
The id of this delivery. |
Sayvara-Test |
true on a test-mode event only (see below); not sent with real events. |
Sayvara-Signature |
t=<unix seconds>,v1=<signature>. See Check the signature. |
The body:
{
"id": "response.completed:7b1e4c2a-5f3d-4e8b-9a6c-2d1f0e3b4a5c",
"type": "response.completed",
"created_at": "2026-11-01T09:30:00.000Z",
"tenant_id": "3f6c1a2e-8b4d-4c7a-9e21-5d0b7f3a9c10",
"test": false,
"data": {
"responseId": "7b1e4c2a-5f3d-4e8b-9a6c-2d1f0e3b4a5c",
"surveyId": "c2a9e7d1-3b4f-4a5e-8c6d-1f2e3d4c5b6a",
"orgUnitId": null,
"channel": "whatsapp",
"lang": "ar",
"nps": 9,
"csat": null,
"ces": null,
"detractor": false,
"completedAt": "2026-11-01T09:30:00.000Z"
}
}| Field | Meaning |
|---|---|
id |
The event id: the event name and the id of the response or ticket event. It stays the same on every retry. |
type |
The event. |
created_at |
When it happened. |
tenant_id |
Your organisation's id. |
test |
false for real events. Samples from Get a sample event say true, and so do test-mode events: a trigger sent with a test key causes a survey.sent with true. An endpoint receives test-mode events only after it has been opted in to them; by default it never does. |
data |
Ids, scores, states and codes only. No contact name, phone number, email or comment, unless an owner or admin turned on contact details for the endpoint (then phone and email, never a name or comment). To get more, read it with the API, for example List completed responses. |
data for each event:
response.completedanddetractor.flagged:responseId,surveyId,orgUnitId,channel,lang,nps,csat,ces,detractorandcompletedAt.ticket.opened:ticketId,orgUnitId,status,priorityand, when set,assignmentReason.ticket.updated:ticketId,orgUnitId,changeandstatus; for an assignment alsoassignmentReason, for a status change alsofromandreason.ticket.closed:ticketId,orgUnitId,status,fromandreason.survey.sent,response.received,outcome.accepted,outcome.rejectedandcontact.opted_out: see Webhook events.
Response events always carry every field, with null when there is no value. surveyId is null for responses that came in without a survey (social posts, complaints, ticket intake). Ticket events leave out fields that have no value.
New responses are picked up about every 30 seconds, so a response event usually arrives within a minute.
Check the signature
The Sayvara-Signature header looks like this:
t=1793525400,v1=5f2b9c...e81atis the time Sayvara signed this try, in Unix seconds.v1is the hex HMAC-SHA256 of the text<t>.<raw body>, keyed with your signing secret (the wholewhsec_...string).- The header can carry more than one
v1, for example while a secret is being changed. Accept the request when any one of them matches.
To check a request:
- Read the raw body exactly as received, before any JSON parsing.
- Split the header on commas. Take
tand everyv1. - Refuse the request when
tis more than 5 minutes (300 seconds) away from your clock. This stops old requests being replayed. - Compute HMAC-SHA256 of
t, a dot and the raw body, with your secret as the key. - Compare it with each
v1in constant time. Accept on the first match; otherwise answer400.
Node.js
With Express.
import crypto from 'node:crypto';
import express from 'express';
const secret = process.env.SAYVARA_WEBHOOK_SECRET; // the signingSecret you stored
export function verifySayvara(rawBody, header, secret, toleranceSec = 300) {
if (!header) return false;
let t = NaN;
const signatures = [];
for (const part of header.split(',')) {
const i = part.indexOf('=');
const key = part.slice(0, i).trim();
const value = part.slice(i + 1).trim();
if (key === 't') t = Number(value);
else if (key === 'v1' && /^[0-9a-f]{64}$/.test(value)) signatures.push(value);
}
if (!Number.isInteger(t) || signatures.length === 0) return false;
if (Math.abs(Math.floor(Date.now() / 1000) - t) > toleranceSec) return false;
const expected = crypto.createHmac('sha256', secret).update(`${t}.`).update(rawBody).digest();
return signatures.some((s) => crypto.timingSafeEqual(expected, Buffer.from(s, 'hex')));
}
const app = express();
app.post('/webhooks/sayvara', express.raw({ type: 'application/json' }), (req, res) => {
if (!verifySayvara(req.body, req.get('Sayvara-Signature'), secret)) return res.sendStatus(400);
const event = JSON.parse(req.body.toString('utf8'));
// Skip event.id if you handled it before, then act on event.type.
res.sendStatus(200);
});
app.listen(3000);Python
For Python 3.10 or newer, with Flask.
import hashlib
import hmac
import os
import re
import time
from flask import Flask, abort, request
SECRET = os.environ["SAYVARA_WEBHOOK_SECRET"].encode() # the signingSecret you stored
app = Flask(__name__)
def verify_sayvara(raw_body: bytes, header: str | None, tolerance: int = 300) -> bool:
if not header:
return False
t, signatures = None, []
for part in header.split(","):
key, _, value = part.strip().partition("=")
if key == "t" and value.isdigit():
t = int(value)
elif key == "v1" and re.fullmatch(r"[0-9a-f]{64}", value):
signatures.append(value)
if t is None or not signatures or abs(time.time() - t) > tolerance:
return False
expected = hmac.new(SECRET, f"{t}.".encode() + raw_body, hashlib.sha256).hexdigest()
return any(hmac.compare_digest(expected, s) for s in signatures)
@app.post("/webhooks/sayvara")
def sayvara_webhook():
if not verify_sayvara(request.get_data(), request.headers.get("Sayvara-Signature")):
abort(400)
event = request.get_json()
# Skip event["id"] if you handled it before, then act on event["type"].
return "", 200C#
An ASP.NET Core minimal API, for .NET 6 or newer.
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
var app = WebApplication.CreateBuilder(args).Build();
var secret = Environment.GetEnvironmentVariable("SAYVARA_WEBHOOK_SECRET")!; // the signingSecret you stored
app.MapPost("/webhooks/sayvara", async (HttpRequest request) =>
{
using var reader = new StreamReader(request.Body, Encoding.UTF8);
var rawBody = await reader.ReadToEndAsync();
if (!SayvaraSignature.Verify(rawBody, request.Headers["Sayvara-Signature"], secret))
return Results.BadRequest();
using var doc = JsonDocument.Parse(rawBody);
// Skip doc.RootElement.GetProperty("id") if you handled it before, then act on "type".
return Results.Ok();
});
app.Run();
static class SayvaraSignature
{
public static bool Verify(string rawBody, string? header, string secret, int toleranceSeconds = 300)
{
if (string.IsNullOrEmpty(header)) return false;
long? t = null;
var signatures = new List<byte[]>();
foreach (var part in header.Split(','))
{
var i = part.IndexOf('=');
if (i < 0) continue;
var key = part[..i].Trim();
var value = part[(i + 1)..].Trim();
if (key == "t" && long.TryParse(value, out var ts)) t = ts;
else if (key == "v1" && Regex.IsMatch(value, "^[0-9a-f]{64}$")) signatures.Add(Convert.FromHexString(value));
}
if (t is null || signatures.Count == 0) return false;
if (Math.Abs(DateTimeOffset.UtcNow.ToUnixTimeSeconds() - t.Value) > toleranceSeconds) return false;
using var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(secret));
var expected = hmac.ComputeHash(Encoding.UTF8.GetBytes($"{t}.{rawBody}"));
return signatures.Any(s => CryptographicOperations.FixedTimeEquals(expected, s));
}
}Test your check
Sign the event catalogue's example body yourself and send it to your handler, with curl, jq and openssl. Keep your signing secret in a file, not in your shell history:
secret="$(cat signing-secret.txt)" # the signingSecret you stored
body="$(curl -s "https://api.sayvara.com/v1/automation/events/response.completed" | jq -c .example)"
send() { # $1 = the t to sign with
sig="$(printf '%s.%s' "$1" "$body" | openssl dgst -sha256 -hmac "$secret" -hex | sed 's/^.* //')"
curl -s -o /dev/null -w '%{http_code}\n' -X POST "https://example.com/webhooks/sayvara" \
-H "Content-Type: application/json" -H "Sayvara-Signature: t=$1,v1=$sig" --data-raw "$body"
}
send "$(date +%s)" # expect 200
send "$(( $(date +%s) - 600 ))" # 10 minutes old: expect 400The first call must be accepted and the second refused, because its t is outside the 300-second window. The example is marked "test": true, so your handler can skip any work for it.
Answer quickly with a 2xx
Any 2xx status means delivered. Anything else is a failed try: a 3xx (redirects are not followed), 4xx, 5xx, or no answer at all. Answer first, then do slow work in the background.
Retries and backoff
A failed delivery is tried again, up to 10 tries in all. The waits between tries are 1, 2, 4, 8, 16, 32, 64, 128 and 256 minutes, each plus up to 10 % random jitter. So the last try comes about 8.5 hours after the first. Each try is signed again with a fresh t; the body stays byte for byte the same.
After the tenth failed try the delivery is dead-lettered. When 50 deliveries in a row are dead-lettered, Sayvara switches the hook off. List REST hooks then shows status: "disabled" and disabledReason: "failing". One accepted delivery resets the count. A switched-off hook does not start again by itself: fix your URL, then turn it back on in its delivery log (see below), or unsubscribe and subscribe again.
Admins can see every REST hook of the organisation, with its health, and remove it under Settings > API access.
Owners and admins can see each delivery of a hook, send one again and turn a switched-off hook back on in its delivery log: Integrations > Webhooks > Delivery log.
If your URL answers 410 Gone, Sayvara removes that REST hook at once and does not retry.
Duplicates and order
The same event can arrive more than once, for example after a timeout on your side, and events can arrive out of order. Make your handler idempotent:
- Store the
idof each event you handle. If anidcomes again, answer200and do nothing. - Use
created_atand the ids indata, not the arrival order, to decide what is newest.
Was this page helpful?
Thanks. Need more help? Email support@sayvara.com