Configure and secure a webhook
Create an endpoint and verify authenticity.
Build an HTTPS receiver that verifies the exact request bytes, durably accepts each event, and handles repeated or out-of-order delivery. Register it through Webhook configuration.
Endpoint requirements
Unidy sends an HTTP POST with Content-Type: application/json. Return a 2xx response only after durable acceptance. Use a queue or inbox for subsequent processing; acknowledging before persistence can lose an event even though Unidy records a successful delivery.
Requests allow up to 5 seconds to connect and a 10-second request timeout. Keep acceptance quick and perform business work asynchronously.
Older integration guidance asked receivers to acknowledge within two seconds. That remains a useful acceptance target, but it is not the current sender's timeout. Likewise, the old seven-to-fifteen-minute retry estimate is not a delivery deadline; queue delays and the retry backoff affect elapsed time.
Register the final HTTPS URL. Unidy may follow one 307 or 308 redirect if the target uses HTTPS, has no URL credentials, and resolves only to public addresses. Other redirects, an unsafe target, a second hop, and non-2xx final responses fail the delivery. Basic Auth and custom headers are stripped on a cross-origin redirect; signed webhook headers and the body are still sent.
Request headers
Read header names case-insensitively.
| Header | Meaning |
|---|---|
UNIDY-WEBHOOK-VERSION | Signing scheme: v2 by default for new registrations; v1 for legacy signing. It is not a version of each resource schema. |
UNIDY-WEBHOOK-TIMESTAMP | In v2, integer Unix seconds, included in the signature. Not sent in v1. |
UNIDY-WEBHOOK-SIGNATURE | Hex-encoded signature calculated as described below. |
UNIDY-WEBHOOK-DELIVERY-ID | UUID of the event/subscription delivery, stable across its retries. |
UNIDY-WEBHOOK-DELIVERY-ATTEMPT | Attempt number, beginning at 1. |
Authorization | Basic Auth when both username and password are configured. |
| Custom headers | Additional configured headers, subject to reserved-name restrictions and redirect handling. |
The signature authenticates the body and, in v2, timestamp. Do not assume it independently signs the delivery ID, attempt number, or other headers. Use the signed event_id when deduplicating the same business event across delivery IDs.
Verify authenticity
Configure the expected signing scheme from the registration. Reject an unknown or unexpected version rather than falling back to a weaker scheme. Read the raw body before JSON parsing, verify it, and only then use the payload.
V2: timestamped HMAC
New registrations have legacy signing switched off and use:
signature = hex(HMAC-SHA256(secret, timestamp + "." + raw_request_body))Validate the timestamp as an integer and enforce a receiver-side tolerance, such as five minutes in either direction. Keep clocks synchronized. The timestamp is generated for the outgoing attempt, so a later retry can carry a fresh timestamp and signature.
Compare the decoded signature with the expected value in constant time, after validating its format and length. A timestamp window limits replay age; duplicate-safe acceptance is still required within that window.
V1: legacy compatibility
Existing registrations may have legacy signing enabled:
signature = hex(SHA256(secret + raw_request_body))V1 is a concatenated SHA-256 digest, not HMAC, and has no signed timestamp. Enable it in a receiver only for a registration that still requires it. To migrate, prepare v2 verification, coordinate the registration change with the receiver, verify a test event, and remove any temporary v1 acceptance. Do not use the request's version header alone to decide which schemes your endpoint trusts.
Runnable receiver example
This Node.js example uses the built-in node:sqlite module as a durable inbox. It serves one registration on 127.0.0.1:3000; put it behind your HTTPS reverse proxy and register the public /webhooks/unidy URL. Use a Node.js release that provides node:sqlite.
Save this as receiver.mjs. Set UNIDY_WEBHOOK_SECRET through your secret-management system, choose UNIDY_WEBHOOK_VERSION=v2 (or explicitly v1 for a legacy registration), then run node receiver.mjs.
The example limits each body to 1 MiB; size this deliberately for the payloads your integration receives. Keep the database on persistent storage with restricted access because event bodies may contain personal data.
import { createServer } from 'node:http';
import { createHash, createHmac, timingSafeEqual } from 'node:crypto';
import { DatabaseSync } from 'node:sqlite';
const secret = process.env.UNIDY_WEBHOOK_SECRET;
const expectedVersion = process.env.UNIDY_WEBHOOK_VERSION ?? 'v2';
if (!secret || !['v1', 'v2'].includes(expectedVersion)) {
throw new Error('Set a secret and choose the registration signing version');
}
const db = new DatabaseSync(process.env.WEBHOOK_DB ?? './webhooks.sqlite');
db.exec(`
PRAGMA journal_mode = WAL;
PRAGMA synchronous = FULL;
PRAGMA busy_timeout = 5000;
CREATE TABLE IF NOT EXISTS inbox (
event_id TEXT PRIMARY KEY NOT NULL,
delivery_id TEXT NOT NULL,
received_at INTEGER NOT NULL,
payload BLOB NOT NULL,
state TEXT NOT NULL DEFAULT 'pending'
);
`);
const accept = db.prepare(`
INSERT INTO inbox (delivery_id, event_id, received_at, payload)
VALUES (?, ?, ?, ?) ON CONFLICT (event_id) DO NOTHING
`);
function verified(raw, headers) {
if (headers['unidy-webhook-version'] !== expectedVersion) return false;
const signature = headers['unidy-webhook-signature'];
if (typeof signature !== 'string' || !/^[a-f0-9]{64}$/i.test(signature)) {
return false;
}
let expected;
if (expectedVersion === 'v2') {
const timestamp = headers['unidy-webhook-timestamp'];
if (typeof timestamp !== 'string' || !/^\d+$/.test(timestamp)) return false;
const seconds = Number(timestamp);
if (!Number.isSafeInteger(seconds) ||
Math.abs(Math.floor(Date.now() / 1000) - seconds) > 300) return false;
expected = createHmac('sha256', secret)
.update(`${timestamp}.`, 'utf8').update(raw).digest();
} else {
expected = createHash('sha256').update(secret, 'utf8').update(raw).digest();
}
return timingSafeEqual(expected, Buffer.from(signature, 'hex'));
}
const uuid = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i;
const server = createServer(async (req, res) => {
const reply = (status) => { res.writeHead(status); res.end(); };
if (req.method !== 'POST' || req.url !== '/webhooks/unidy') return reply(404);
const contentType = req.headers['content-type']?.split(';')[0].trim();
if (contentType !== 'application/json') return reply(415);
try {
const chunks = [];
let size = 0;
for await (const chunk of req) {
size += chunk.length;
if (size <= 1024 * 1024) chunks.push(chunk);
}
if (size > 1024 * 1024) return reply(413);
const raw = Buffer.concat(chunks);
if (!verified(raw, req.headers)) return reply(401);
const deliveryId = req.headers['unidy-webhook-delivery-id'];
let event;
try { event = JSON.parse(raw.toString('utf8')); }
catch { return reply(400); }
if (typeof deliveryId !== 'string' || !uuid.test(deliveryId) ||
!event || typeof event !== 'object' ||
typeof event.event_id !== 'string' || !uuid.test(event.event_id) ||
typeof event.event_type !== 'string') return reply(400);
// Deduplicate only the signed event ID; delivery IDs are unsigned metadata.
// This endpoint processes each signed event once across its subscriptions.
accept.run(deliveryId, event.event_id, Date.now(), raw);
return reply(202);
} catch {
// No success response when durable storage is unavailable.
return reply(503);
}
});
server.requestTimeout = 30_000;
server.headersTimeout = 10_000;
server.listen(Number(process.env.PORT ?? 3000), '127.0.0.1');A worker must process the inbox's pending rows, retry its own failures, and retain a deduplication record for the recovery period you support. Commit local business changes and the processed marker together where possible; use an idempotency key for external side effects. This example supplies durable acceptance, not a worker or an exactly-once guarantee across external systems.
Its primary key is the signed event_id, which intentionally collapses multiple deliveries of the same event into one processing job. The unsigned delivery ID is nonunique correlation metadata: reusing that header must not suppress a different signed event. If subscriptions require separate business handling, model that explicitly using an event ID plus a trusted consumer identity. Do not replace the database uniqueness check with an in-memory set or a read-then-write race.
Delivery, retries, and ordering
A delivery pairs one event with one subscription. It has one UUID and accumulates send attempts.
| State | Meaning |
|---|---|
pending | Created; no attempt has been recorded. |
finished | An attempt received 2xx. |
failed | The latest attempt failed; a retry normally follows while attempts remain. |
failed_permanently | Automatic retries were exhausted. |
Normal failure handling allows one initial attempt and up to five retries with increasing backoff. Requests may repeat, and successful delivery is not guaranteed. Queue delays, scheduling, and request time affect the elapsed retry window; it is not a fixed ten minutes.
If a registration or subscription is disabled before a queued attempt, that job can be skipped without advancing the state or re-enqueuing it. Re-enabling does not restart the skipped delivery. See deliveries that stop moving.
Arrival order is not guaranteed. Payloads are constructed during dispatch, which can happen after the original change and observe later record state. occurred_at is therefore not a record revision or a reliable last-writer-wins ordering key. For a current-state projection, treat the event as a prompt to reconcile from the REST API where the record remains available.
Handle duplicates
A receiver can commit its work and then time out before Unidy sees its response. The next attempt must be safe even though the first attempt already took effect.
Use the stable delivery UUID to correlate attempts, and the signed payload's event_id to deduplicate a business event across subscriptions where that is the intended behavior. Persist the inbox entry and duplicate key atomically. If an already accepted event arrives again, return 2xx without repeating its business side effects.
Monitor both HTTP acceptance and worker completion. A finished delivery only confirms a 2xx from the receiver; it cannot prove downstream processing succeeded.
Payloads and scope
The event reference documents the 23 event types, envelope, resource fields, and deletion shapes. Payloads share fields such as event_type, event_id, occurred_at, source, tenant_id, and nullable brand_id. Resource sections vary: a plugin-link event, for example, has both user and top-level plugin_data.
The same event need not produce byte-identical bodies for every registration. Opting into plugin data controls optional user.plugins_data on supported events. The dashboard's stored Raw JSON is useful for inspection, but it may include fields stripped from a particular registration's request and is not the original HTTP byte stream for signature verification.
When brand context is absent, subscription matching skips the brand filter. A null brand_id is not a trustworthy brand assignment. Resolve strict isolation requirements before receiving such events; see subscription matching.
Review actual user payload fields before forwarding or storing them in another system. Do not treat a custom attribute's API-accessible setting as a documented webhook filtering boundary.
Change secrets and signing mode
Rotate secret generates and saves a new secret immediately; it does not reveal the next value beforehand or provide an overlap window. Coordinate rotation and receiver configuration with its owner. Verify a fresh event afterward and reconcile failures whose retries ended during the transition.
For an agreed custom secret, prepare the receiver's controlled transition before saving the secret in the registration. Keep any temporary old-secret or old-scheme acceptance time-limited and remove it once verified. Basic Auth and custom headers can provide additional gateway controls, but do not replace raw-body signature verification.
Recovery and monitoring
There is no dashboard redeliver action for a permanently failed delivery. The event payload remains available until scheduled retention cleanup after two calendar months; exhausting retries does not immediately erase it.
A fresh-event trigger uses current record state and can notify all matching subscribers and connected integrations. REST reconciliation can restore current state of existing records, but cannot reconstruct every intermediate event or fetch a record that has been deleted. Follow the recovery matrix before choosing a bulk recovery action.
Track request failures, signature failures, inbox depth, worker retries, processing lag, and gaps in expected traffic. Correlate delivery and event IDs, and avoid logging secrets or returning personal data in HTTP error bodies: delivery responses are visible to authorized dashboard administrators.