Webhooks
sms.webhooks registers the HTTPS endpoints SMSFabric calls when something happens, lists their delivery attempts, and verifies the signature on the events your server receives. Managing endpoints needs the webhooks:manage scope. Events, payloads and retries are described in Webhooks.
| Method | HTTP | Returns |
|---|---|---|
list() |
GET /v1/webhooks |
Webhook[] |
create(params, options?) |
POST /v1/webhooks |
CreatedWebhook |
update(id, params) |
PATCH /v1/webhooks/:id |
Webhook |
delete(id) |
DELETE /v1/webhooks/:id |
void |
deliveries(id, params?) |
GET /v1/webhooks/:id/deliveries |
Paginated<WebhookDelivery> |
deliveriesAll(id, params?) |
GET /v1/webhooks/:id/deliveries (every page) |
AsyncGenerator<WebhookDelivery> |
replay(id, deliveryId) |
POST /v1/webhooks/:id/deliveries/:deliveryId/replay |
WebhookDelivery |
test(id) |
POST /v1/webhooks/:id/test |
WebhookDelivery |
listen(options?) |
GET /v1/webhooks/listen |
AsyncGenerator<ListenedEvent> |
verifySignature(rawBody, header, secret, options?) |
none (local) | boolean |
constructEvent(rawBody, header, secret, options?) |
none (local) | WebhookPayload |
listen(options?) |
GET /v1/webhooks/listen (stream) |
AsyncGenerator<ListenedEvent> |
verifySignature and constructEvent are also exported on their own, import { verifySignature, constructEvent } from '@smsfabric/sdk'. They need no client and no API key, so a webhook receiver doesn’t have to hold one. sms.webhooks.verifySignature and sms.webhooks.constructEvent call the same functions.
Every endpoint of your organization. The signing secret is never included.
import { SMSFabric } from '@smsfabric/sdk';
const sms = new SMSFabric({ apiKey: process.env.SMSFABRIC_API_KEY });
for (const w of await sms.webhooks.list()) console.log(w.id, w.url, w.enabled, w.events.join(', '));create
Section titled “create”Registers an endpoint for a list of events. The URL must be https in production; SMSFabric refuses hosts that resolve to private, loopback or link-local addresses. The result carries signingSecret (whsec_…), returned only this once: store it in your secret manager.
import { SMSFabric } from '@smsfabric/sdk';
const sms = new SMSFabric({ apiKey: process.env.SMSFABRIC_API_KEY });
const webhook = await sms.webhooks.create({ url: 'https://acme.example/hooks/smsfabric', events: ['message.delivered', 'message.failed', 'message.received'], description: 'Order notifications',});console.log(webhook.id);// Save webhook.signingSecret now: it is not shown again.update
Section titled “update”Changes the url, the events, enabled or the description. Turn an endpoint off with enabled: false instead of deleting it while you fix your server.
import { SMSFabric } from '@smsfabric/sdk';
const sms = new SMSFabric({ apiKey: process.env.SMSFABRIC_API_KEY });
await sms.webhooks.update('whk_…', { events: ['message.delivered', 'message.failed', 'campaign.completed'] });await sms.webhooks.update('whk_…', { enabled: false });delete
Section titled “delete”Removes the endpoint. SMSFabric sends it no new events.
import { SMSFabric } from '@smsfabric/sdk';
const sms = new SMSFabric({ apiKey: process.env.SMSFABRIC_API_KEY });
await sms.webhooks.delete('whk_…');deliveries and deliveriesAll
Section titled “deliveries and deliveriesAll”Delivery attempts for one endpoint, newest first: event type, status (pending, succeeded, failed), number of attempts, the last HTTP status and error, and when the next attempt runs.
import { SMSFabric } from '@smsfabric/sdk';
const sms = new SMSFabric({ apiKey: process.env.SMSFABRIC_API_KEY });
for await (const d of sms.webhooks.deliveriesAll('whk_…')) { if (d.status === 'failed') console.log(d.id, d.eventType, d.lastStatusCode, d.lastError);}replay
Section titled “replay”Queues the same event again for that endpoint, for example after you fixed a bug that made your server answer 500.
import { SMSFabric } from '@smsfabric/sdk';
const sms = new SMSFabric({ apiKey: process.env.SMSFABRIC_API_KEY });const webhookId = 'whk_…';
for await (const d of sms.webhooks.deliveriesAll(webhookId)) { if (d.status === 'failed') await sms.webhooks.replay(webhookId, d.id);}Sends a webhook.test event to the endpoint, so you can check that your server receives and verifies it.
import { SMSFabric } from '@smsfabric/sdk';
const sms = new SMSFabric({ apiKey: process.env.SMSFABRIC_API_KEY });
const delivery = await sms.webhooks.test('whk_…');console.log(delivery.id, delivery.status); // dlv_… pendinglisten
Section titled “listen”Yields your organization’s webhook events as they happen, over one outbound connection, so a laptop with no public URL can receive them. It is made for development: the CLI’s smsfabric listen is built on it. Needs the webhooks:manage scope.
| Option | Type | Notes |
|---|---|---|
events |
string[] |
Event types to receive, such as message.delivered. Default: every event. |
signal |
AbortSignal |
Abort it to stop listening; the loop then ends without an error. |
onStatus |
(status: ListenStatus) => void |
Called with { state: 'connected', listenerId, expiresAt } when a stream is ready, and with { state: 'reconnecting', reason, retryInMs } when it was lost. |
Each ListenedEvent has id (the event id), type, payload (the parsed WebhookPayload) and rawBody, the exact JSON an endpoint would receive. To forward an event to a handler that checks signatures, sign and send rawBody, not a re-serialised copy.
import { SMSFabric, SMSFabricError } from '@smsfabric/sdk';
const sms = new SMSFabric({ apiKey: process.env.SMSFABRIC_API_KEY });
// Stop on Ctrl+C, or after ten minutes.const stop = new AbortController();process.once('SIGINT', () => stop.abort());setTimeout(() => stop.abort(), 10 * 60_000).unref();
try { const events = sms.webhooks.listen({ events: ['message.delivered', 'message.failed', 'message.received'], signal: stop.signal, onStatus: (status) => { if (status.state === 'connected') console.error(`Listening (${status.listenerId})`); else console.error(`Connection lost: ${status.reason}. Retrying in ${status.retryInMs} ms`); }, }); for await (const event of events) { console.log(event.type, event.id, event.payload.data); }} catch (err) { // 400, 401, 403 and 404 end the stream: a bad event type, key or scope. if (err instanceof SMSFabricError) console.error(err.status, err.code, err.detail); else throw err;}The SDK handles the stream’s lifecycle for you:
- The server ends each stream after 5 minutes. The SDK opens the next one when the old one sends
rotate, so no event is lost at the change, and yields an event seen on both streams once. - After a dropped connection, or
429 too_many_listeners, it reconnects with backoff and reports it throughonStatus. Events published while it was disconnected are not replayed. 400,401,403and404are not retried: the loop throws anSMSFabricError.
verifySignature
Section titled “verifySignature”Returns true when the SMSFabric-Signature header matches the raw request body and your signing secret. The header is t=<unix seconds>,v1=<hex>, where v1 is the HMAC-SHA256 of <t>.<raw body>. The comparison runs in constant time, and a signature older than 300 seconds fails, so a captured request cannot be replayed later.
| Argument | Type | Notes |
|---|---|---|
rawBody |
RawBody (string | Buffer | Uint8Array) |
The body exactly as received. Parsing and re-serialising the JSON changes the bytes and breaks the signature. A Uint8Array from await request.arrayBuffer() works as is. |
header |
string | null | undefined |
The SMSFabric-Signature header. A missing header returns false. |
secret |
string |
The endpoint’s signingSecret. |
options.toleranceSec |
number |
Maximum age in seconds. Default 300; 0 turns the check off. |
options.now |
number |
The current time in unix seconds, for tests. |
import { verifySignature } from '@smsfabric/sdk';
const secret = process.env.SMSFABRIC_WEBHOOK_SECRET ?? '';
export function isFromSmsFabric(rawBody: Buffer, signature: string | undefined): boolean { return verifySignature(rawBody, signature, secret);}import { constructEvent, SignatureVerificationError, type RawBody } from '@smsfabric/sdk';
// A Fetch API handler (Next.js route, Hono, Bun, Deno): the body arrives as bytes.export async function POST(request: Request): Promise<Response> { const rawBody: RawBody = new Uint8Array(await request.arrayBuffer()); try { const event = constructEvent(rawBody, request.headers.get('smsfabric-signature'), process.env.SMSFABRIC_WEBHOOK_SECRET ?? ''); console.log(event.id, event.type); return new Response(null, { status: 200 }); } catch (err) { if (err instanceof SignatureVerificationError) return new Response(null, { status: 400 }); throw err; }}Verifying never calls the API and needs no client, so the receiver above holds only the signing secret. With the Fetch API the body arrives as bytes; pass them as a Uint8Array:
constructEvent
Section titled “constructEvent”Verifies the signature and returns the parsed event { id, type, createdAt, orgId, data }. It throws SignatureVerificationError when the header is missing or malformed, the signature does not match or is too old, or the signed body is not a JSON object. Answer 400 in that case and don’t process the body.
This receiver uses only node:http. It reads the raw body, caps it at 1 MB, verifies it, answers 200 at once and handles the event afterwards:
import { createServer, type IncomingMessage } from 'node:http';import { constructEvent, SignatureVerificationError, type WebhookPayload } from '@smsfabric/sdk';
const secret = process.env.SMSFABRIC_WEBHOOK_SECRET ?? '';const MAX_BODY = 1024 * 1024;
async function readRawBody(req: IncomingMessage): Promise<Buffer> { const chunks: Buffer[] = []; let size = 0; for await (const chunk of req) { const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)); size += buf.length; if (size > MAX_BODY) throw new Error('body too large'); chunks.push(buf); } return Buffer.concat(chunks);}
async function handle(event: WebhookPayload): Promise<void> { // Deliveries can repeat: skip an event.id you have already processed. console.log(event.id, event.type, event.data);}
createServer(async (req, res) => { if (req.method !== 'POST' || req.url !== '/hooks/smsfabric') { res.writeHead(404).end(); return; } let event: WebhookPayload; try { const header = req.headers['smsfabric-signature']; event = constructEvent(await readRawBody(req), typeof header === 'string' ? header : undefined, secret); } catch (err) { res.writeHead(err instanceof SignatureVerificationError ? 400 : 413).end(); return; } res.writeHead(200).end(); handle(event).catch((err: unknown) => console.error('webhook handler failed', err));}).listen(3000);With Express, mount express.raw on the webhook route so req.body stays a Buffer. A global express.json() parses the body before your handler sees it, and the signature no longer matches.
import express from 'express';import { constructEvent, SignatureVerificationError } from '@smsfabric/sdk';
const secret = process.env.SMSFABRIC_WEBHOOK_SECRET ?? '';const app = express();
app.post('/hooks/smsfabric', express.raw({ type: 'application/json', limit: '1mb' }), (req, res) => { let event; try { event = constructEvent(req.body, req.header('SMSFabric-Signature'), secret); } catch (err) { if (err instanceof SignatureVerificationError) return res.sendStatus(400); throw err; } res.sendStatus(200); console.log(event.id, event.type);});
app.use(express.json()); // other routes may parse JSON; the webhook route is registered first
app.listen(3000);listen
Section titled “listen”Yields the organization’s webhook events as they happen, over one outbound connection, so a development machine needs no public URL. Needs webhooks:manage. Options: events (event types; default every event), signal (abort to stop) and onStatus (connection changes). The stream reconnects by itself; events that happen while it is down are not replayed. In production, register an endpoint instead.
import { SMSFabric } from '@smsfabric/sdk';
const sms = new SMSFabric({ apiKey: process.env.SMSFABRIC_API_KEY });const stop = new AbortController();
for await (const event of sms.webhooks.listen({ events: ['message.delivered', 'message.failed'], signal: stop.signal })) { console.log(event.type, event.id);}event.rawBody is the exact JSON an endpoint would receive; event.payload is the same thing parsed.