Webhooks
Receive Platica events on your server. Use the SDK to verify the POST signature and get the event with its type.
Register the webhook
Give the webhook a signing secret. Without one, deliveries are not signed.
await platic.webhooks.create({
name: "Orders app",
url: "https://example.com/webhooks/platica",
events: ["message.created", "conversation.status.updated"],
secret: process.env.PLATIC_WEBHOOK_SECRET,
}); Platica checks the URL with a HEAD request before it activates the webhook. Any answer below 500 passes. See Create a webhook and Webhook events.
Verify a delivery
Each signed delivery includes X-Webhook-Signature: sha256=<hex>, the HMAC-SHA256 signature of the raw body calculated with your secret. parseWebhookEvent compares the signature in constant time and returns the verified event. Process the event after that verification.
import { parseWebhookEvent, WebhookVerificationError } from "platic-sdk";
async function handleWebhook(request: Request): Promise<Response> {
try {
const event = await parseWebhookEvent({
payload: await request.text(), // the raw body, not a parsed object
signature: request.headers.get("x-webhook-signature"),
secret: process.env.PLATIC_WEBHOOK_SECRET!,
});
if (event.event === "message.created") console.log(event.data.message.content);
return new Response(null, { status: 200 });
} catch (error) {
if (error instanceof WebhookVerificationError) return new Response(null, { status: 401 });
throw error;
}
} | Function | Returns | Throws |
|---|---|---|
parseWebhookEvent({ payload, signature, secret }) | The event, typed by event.event (PlaticaWebhookEvent) | WebhookVerificationError with a reason |
verifyWebhookSignature({ payload, signature, secret }) | true or false | PlaticUsageError only for a programming error |
payload is a string, Buffer, Uint8Array or ArrayBuffer. signature is the header value. WEBHOOK_SIGNATURE_HEADER is "x-webhook-signature", the header name as Node's req.headers spells it.
Check reason to find out why verification failed:
reason | Meaning |
|---|---|
missing_signature | No X-Webhook-Signature header: the webhook has no signing secret, or the request is not from Platica. |
malformed_signature | The header is not sha256= followed by 64 hex characters. |
signature_mismatch | The secret is not this webhook's, or the body changed before you verified it. |
invalid_payload | The signed body is not a Platica event (JSON with id, event and workspaceId). |
Answer 401 to a delivery that fails and do not act on it. See Webhook signatures.
Verify the raw body. Parsing the JSON and serializing it again changes the bytes, and the signature no longer matches. Passing a parsed object throws PlaticUsageError.
Express
Put express.raw on the webhook route, before any JSON parser, so req.body is a Buffer.
import express from "express";
import { parseWebhookEvent, WEBHOOK_SIGNATURE_HEADER, WebhookVerificationError } from "platic-sdk";
const app = express();
const seen = new Set<string>();
app.post("/webhooks/platica", express.raw({ type: "application/json" }), async (req, res) => {
let event;
try {
event = await parseWebhookEvent({
payload: req.body, // a Buffer
signature: req.headers[WEBHOOK_SIGNATURE_HEADER],
secret: process.env.PLATIC_WEBHOOK_SECRET!,
});
} catch (error) {
if (error instanceof WebhookVerificationError) return res.sendStatus(401);
throw error;
}
// Answer first, then do the slow work.
res.sendStatus(200);
if (seen.has(event.id)) return;
seen.add(event.id);
if (event.event === "message.created") {
console.log(`message in conversation ${event.data.conversation.id}`);
}
});
app.listen(3000); For a full Node.js server with no framework, see the webhook server example.
Deduplicate
The signature has no timestamp, so a captured delivery could be sent again. You may also receive the same event more than once. Save its event.id and skip events you have already processed. Use a Set for one process or a database for several.
Narrow an event
Use WebhookEventOf to declare an event type. Checking event.event lets TypeScript recognize that event's fields:
import type { WebhookEventOf } from "platic-sdk";
function onMessage(event: WebhookEventOf<"message.created">) {
console.log(event.data.message.direction);
} Platica may add events. Handle the ones you need and accept the rest with a 200. Every event carries id, event, workspaceId and timestamp.
When a delivery fails
A delivery fails if your server responds with 5xx, takes more than 15 seconds or cannot be reached. A 4xx response counts as delivered. By default, the webhook pauses after 5 consecutive failures. Use autoPause to change that behavior:
// After 50 failed deliveries in a row (5 to 1000)
await platic.webhooks.update("wh_123", { autoPause: { mode: "failures", failures: 50 } });
// Or keep sending and pause after 24 hours without a successful delivery (1 to 168)
await platic.webhooks.update("wh_123", { autoPause: { mode: "time", hours: 24 } });
// Back to the default
await platic.webhooks.update("wh_123", { autoPause: null });