Receiving Events
Webhook delivery & signature verification
How UnifyPort delivers events to your endpoint over HTTP POST, the X-Device-* headers on every delivery, and how to verify the HMAC-SHA256 signature so you can trust the payload. Also covers the response we expect, retries, and idempotency. Доступ к событиям звонков определяется is_beta рабочего пространства. При доступе к тестированию *, пустой или отсутствующий subscribed_events включают события звонков; конкретный список включает только перечисленные события. Без доступа можно использовать wildcard, но события звонков не доставляются; их явная подписка возвращает 403 beta_feature_not_enabled. Право проверяется при каждой доставке, повторе и повторной обработке dead letter; ошибка проверки не даёт доступ. Обычные записи звонков message.* независимы.
Подтверждение и повторы
- 2xx
- Сохраните событие и ответьте любым 2xx для подтверждения доставки. Тело ответа не используется.
- 408 / 429 / 5xx
- Ошибки соединения и 408 / 429 / 5xx повторяются немедленно. retry_policy.max_attempts задаёт число повторов после первого запроса: по умолчанию 3, то есть максимум 4 запроса. Задержка backoff и Retry-After не используются.
- 4xx (≠ 408 / 429)
- Остальные 4xx прекращают автоматическую доставку и помечают событие как dead-letter. Исправьте настройки получателя; автоматического воспроизведения не будет.
Delivery headers
X-Device-Event-IdCorrelation id for the emitted event. It stays the same across retries of that event, but WhatsApp HistorySync batches must not be globally deduplicated by this header alone.
X-Device-Delivery-IdDelivery correlation id. It can fall back to X-Device-Event-Id and is therefore not guaranteed to be unique for each HTTP attempt.
X-Device-TimestampRFC 3339 UTC time the delivery was signed (e.g. 2026-06-08T12:34:56Z). It is part of the signed string and also lets you reject stale deliveries.
X-Device-SignatureHex-encoded HMAC-SHA256 of "<X-Device-Timestamp>" + "." + "<raw request body>". Present only when the endpoint has a signing_secret; omitted when signing is disabled.
Content-TypeAlways application/json.
Verify the signature
Node.js (Express)
import crypto from 'crypto';
import express from 'express';
const app = express();
const SECRET = process.env.WEBHOOK_SIGNING_SECRET;
// express.raw keeps the body as the exact bytes we signed — never re-serialize.
app.post('/webhook', express.raw({ type: 'application/json' }), (req, res) => {
let timestamp = req.get('X-Device-Timestamp');
if (!timestamp) {
timestamp = '';
}
let signature = req.get('X-Device-Signature');
if (!signature) {
signature = '';
}
const hmac = crypto.createHmac('sha256', SECRET);
hmac.update(timestamp + '.');
hmac.update(req.body); // raw Buffer
const expected = hmac.digest('hex');
const valid =
signature.length === expected.length &&
crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected));
if (!valid) return res.status(401).end();
const event = JSON.parse(req.body.toString('utf8'));
// handle event.type ...
res.status(200).end(); // any 2xx acknowledges the delivery
});Python (Flask)
import hmac, hashlib, os
from flask import Flask, request, abort
app = Flask(__name__)
SECRET = os.environ["WEBHOOK_SIGNING_SECRET"].encode()
@app.post("/webhook")
def webhook():
timestamp = request.headers.get("X-Device-Timestamp", "")
signature = request.headers.get("X-Device-Signature", "")
body = request.get_data() # raw bytes, exactly as delivered
expected = hmac.new(
SECRET, timestamp.encode() + b"." + body, hashlib.sha256
).hexdigest()
if not hmac.compare_digest(signature, expected):
abort(401)
event = request.get_json()
# handle event["type"] ...
return "", 200Примечания
- Delivery is at-least-once. For ordinary events, retries reuse X-Device-Event-Id and receivers should deduplicate idempotently. For conversation.history, do not globally deduplicate on the top-level event id alone; merge by provider, account_id, conversation.id, and messages[].id so later chunks are retained.
- Verify against the raw request bytes, before any JSON parse or re-serialize. Re-encoding the body changes the bytes and breaks the signature.
- Reject deliveries whose X-Device-Timestamp is too far from your clock to limit replay — the timestamp is covered by the signature.
- Signing is per-endpoint: set signing_secret on Create or Update webhook endpoint to enable it; leave it empty to disable and drop the X-Device-Signature header.
- Delivery order is not guaranteed — events from the same conversation can arrive out of order (a read receipt may land before the message it refers to). Order by occurred_at, with the event id as a tiebreaker, before applying state.
- UnifyPort has no REST API for reading message history and does not guarantee replay of missed payloads. Store events when they arrive. WhatsApp can emit limited best-effort conversation.history data after bootstrap or reconnect, but it is neither complete nor a durable archive.