Webhooks
A webhook is an HTTPS endpoint on your server that SMSFabric calls when something happens: a message is delivered, an SMS arrives, a phone goes offline. Webhooks replace polling, and they are the only way to learn about events you didn’t start, such as inbound messages.
Set up an endpoint
Section titled “Set up an endpoint”- Build a route that accepts
POSTwith a JSON body and answers2xxwithin 10 seconds. Do slow work after you answer, in a queue. - Register it under Developers → Webhooks in the portal (walkthrough), or with
POST /v1/webhooks. The key needswebhooks:manage. - Store the
signingSecretfrom the response. It starts withwhsec_and is shown only once. - Send a test event with
POST /v1/webhooks/:id/testand check that your endpoint verifies it.
curl https://api.smsfabric.com/v1/webhooks \ -H "X-Api-Key: $SMSFABRIC_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "url": "https://acme.example/hooks/smsfabric", "events": ["message.delivered", "message.failed", "message.received"], "description": "Order notifications" }'The URL must be https. SMSFabric resolves its host name and refuses addresses in private, loopback and link-local ranges with 400 ssrf_blocked, both when you save it and on every delivery.
Events
Section titled “Events”| Event | Sent when | data |
|---|---|---|
message.queued |
A message is accepted | The message |
message.sent |
The carrier accepted a message | The message |
message.delivered |
The handset confirmed delivery | The message |
message.failed |
A message could not be sent | The message, with errorCode |
message.received |
An SMS arrived on one of your SIMs | The inbound message |
device.online |
A phone came online | The phone (id, name, status, battery, sims…) |
device.offline |
A phone stopped checking in | The phone |
verification.approved |
A Verify code matched | The verification (number masked) |
verification.expired |
A Verify code expired unused | The verification |
verification.blocked |
Pumping protection refused a send | reason, masked to, country, prefix, blockId, createdAt |
campaign.started |
A campaign began sending | id, name, status, timestamps, estimatedDurationMs, progress |
campaign.completed |
A campaign completed or was canceled (see status) |
Same as campaign.started |
webhook.test |
You called POST /v1/webhooks/:id/test |
{ "message": "This is a test event from SMSFabric." } |
You can’t subscribe to webhook.test; it goes only to the endpoint you test. Message data has the same fields as GET /v1/messages/:id without events, and verification codes always show as [verification code hidden].
Payload and headers
Section titled “Payload and headers”Every delivery is a POST with Content-Type: application/json:
POST /hooks/smsfabric HTTP/1.1Content-Type: application/jsonUser-Agent: SMSFabric-Webhooks/1.0SMSFabric-Signature: t=1795086909,v1=5f0c3a8e9b1d4c7e2a6f8b0d3e5c7a9f1b3d5e7f9a1c3e5b7d9f1a3c5e7b9d1fSMSFabric-Event-Id: evt_c7e9g2i4k6m8o1q3s5u7w9y2
{"id":"evt_c7e9g2i4k6m8o1q3s5u7w9y2","type":"message.delivered","createdAt":"2026-11-19T10:15:09.455Z","orgId":"org_n5q8t1w4z7c0f3i6l9o2r5u8","data":{"id":"msg_q8v2k4n6p1r3t5w7y9z0b2c4","status":"delivered","to":"+201001234567","metadata":{"orderId":"1042"}}}| Field | Meaning |
|---|---|
id |
The event id (evt_…). Same as the SMSFabric-Event-Id header. |
type |
One of the events above. |
createdAt |
When the event happened, ISO 8601 UTC. |
orgId |
Your organization. |
data |
The object the event is about. |
Verify signatures
Section titled “Verify signatures”Anyone can post to a public URL. Before you act on a delivery, check that SMSFabric sent it and that it wasn’t replayed later.
The SMSFabric-Signature header is t=<unix seconds>,v1=<hex>, where v1 is the HMAC-SHA256 of <t>.<raw body> keyed with your signing secret. To verify:
- Read the raw request body, exactly as received. Parsing and re-serializing the JSON changes the bytes and breaks the signature.
- Split the header on
,and taketand everyv1. - Reject the delivery if
tis more than 300 seconds from your clock. - Compute
HMAC-SHA256(secret, t + "." + rawBody)as hex and compare it tov1with a constant-time comparison. - Answer
400(or401) if it doesn’t match, and don’t process the event.
Each retry is signed again with a fresh t, so a slow retry still passes the 300-second window.
import express from 'express';import { SMSFabric, SignatureVerificationError } from '@smsfabric/sdk';
const sf = new SMSFabric({ apiKey: process.env.SMSFABRIC_API_KEY });const secret = process.env.SMSFABRIC_WEBHOOK_SECRET ?? '';const app = express();
// express.raw keeps the body as a Buffer: verify the bytes as received.app.post('/hooks/smsfabric', express.raw({ type: 'application/json' }), (req, res) => { try { const event = sf.webhooks.constructEvent(req.body, req.header('SMSFabric-Signature'), secret); res.sendStatus(200); void handle(event.id, event.type, event.data); // do the work after answering } catch (err) { if (err instanceof SignatureVerificationError) return res.sendStatus(400); throw err; }});
async function handle(id: string, type: string, data: unknown): Promise<void> { console.log(id, type, data);}
app.listen(3000);import { createHmac, timingSafeEqual } from 'node:crypto';import express from 'express';
const secret = process.env.SMSFABRIC_WEBHOOK_SECRET ?? '';const TOLERANCE_SEC = 300;
function verify(rawBody: Buffer, header: string | undefined): boolean { if (!header) return false; let t = NaN; const sigs: string[] = []; for (const part of header.split(',')) { const [key, value] = part.split('=', 2); if (key === 't') t = Number(value); if (key === 'v1' && value) sigs.push(value); } if (!Number.isInteger(t) || Math.abs(Date.now() / 1000 - t) > TOLERANCE_SEC) return false; const expected = createHmac('sha256', secret).update(`${t}.`).update(rawBody).digest(); return sigs.some((sig) => { const given = Buffer.from(sig, 'hex'); return given.length === expected.length && timingSafeEqual(given, expected); });}
const app = express();app.post('/hooks/smsfabric', express.raw({ type: 'application/json' }), (req, res) => { if (!verify(req.body as Buffer, req.header('SMSFabric-Signature'))) return res.sendStatus(400); const event = JSON.parse((req.body as Buffer).toString('utf8')); res.sendStatus(200); console.log(event.id, event.type);});app.listen(3000);import hashlibimport hmacimport jsonimport osimport time
from flask import Flask, abort, request
SECRET = os.environ["SMSFABRIC_WEBHOOK_SECRET"].encode()TOLERANCE_SEC = 300app = Flask(__name__)
def verify(raw_body: bytes, header: str | None) -> bool: if not header: return False t, sigs = None, [] for part in header.split(","): key, _, value = part.partition("=") if key == "t" and value.isdigit(): t = int(value) elif key == "v1": sigs.append(value) if t is None or abs(time.time() - t) > TOLERANCE_SEC: return False expected = hmac.new(SECRET, f"{t}.".encode() + raw_body, hashlib.sha256).hexdigest() return any(hmac.compare_digest(expected, sig) for sig in sigs)
@app.post("/hooks/smsfabric")def smsfabric_hook(): raw = request.get_data() # the raw bytes, before any JSON parsing if not verify(raw, request.headers.get("SMSFabric-Signature")): abort(400) event = json.loads(raw) print(event["id"], event["type"]) return "", 200<?php$secret = getenv('SMSFABRIC_WEBHOOK_SECRET');$tolerance = 300;
$raw = file_get_contents('php://input'); // the raw body, before json_decode$header = $_SERVER['HTTP_SMSFABRIC_SIGNATURE'] ?? '';
$t = null;$sigs = [];foreach (explode(',', $header) as $part) { [$key, $value] = array_pad(explode('=', $part, 2), 2, ''); if ($key === 't' && ctype_digit($value)) { $t = (int) $value; } elseif ($key === 'v1') { $sigs[] = $value; }}
$expected = $t === null ? '' : hash_hmac('sha256', $t . '.' . $raw, $secret);$valid = $t !== null && abs(time() - $t) <= $tolerance;$matched = false;foreach ($sigs as $sig) { $matched = $matched || hash_equals($expected, $sig);}
if (!$valid || !$matched) { http_response_code(400); exit;}
$event = json_decode($raw, true);http_response_code(200);error_log($event['id'] . ' ' . $event['type']);The SDK also has sf.webhooks.verifySignature(rawBody, header, secret), which returns true or false instead of throwing. Both take an optional { toleranceSec }.
Test webhooks on your machine
Section titled “Test webhooks on your machine”An endpoint needs a public HTTPS URL, which your laptop doesn’t have. During development, run smsfabric listen instead. It opens one connection from your machine to SMSFabric and posts every event to your local server, signed with the same SMSFabric-Signature and SMSFabric-Event-Id headers. Your verification code runs unchanged.
export SMSFABRIC_WEBHOOK_SECRET="whsec_…" # the secret your handler verifies withsmsfabric listen --forward-to http://localhost:3000/hooks/smslisten doesn’t replay events it missed and doesn’t retry a failed forward, so use it for development only. To build the same thing into your own tooling, use sms.webhooks.listen() or GET /v1/webhooks/listen.
Retries
Section titled “Retries”A delivery succeeds when your endpoint answers 2xx within 10 seconds. Anything else (another status, a timeout, a refused connection) is retried with backoff. Redirects are not followed.
| Attempt | Delay after the previous attempt |
|---|---|
| 1 | Immediately |
| 2 | 1 minute |
| 3 | 5 minutes |
| 4 | 15 minutes |
| 5 | 1 hour |
| 6 | 3 hours |
| 7 | 6 hours |
| 8 | 13 hours |
After the 8th attempt, about 23.5 hours after the event, the delivery is marked failed. Deliveries to a disabled endpoint fail without being sent.
Handle duplicates and order
Section titled “Handle duplicates and order”Retries and replays mean you can receive the same event more than once. Deduplicate on SMSFabric-Event-Id (the same value as id in the body): store the ids you have processed and skip any you’ve seen.
// A unique index on processed_events.id makes this safe with several workers.const inserted = await db.query('INSERT INTO processed_events (id) VALUES ($1) ON CONFLICT DO NOTHING', [eventId]);if (inserted.rowCount === 0) return; // already handledEvents can also arrive out of order: a message.delivered can come before a delayed message.sent. Compare the message’s status with what you have stored, and never move it backwards. Statuses only ever move forward: queued, routed, sending, sent, then one of delivered, failed or blocked.
Replay a delivery
Section titled “Replay a delivery”When your endpoint was down or had a bug, replay deliveries after you fix it:
- In the portal: Developers → Webhooks, open the endpoint, and click Replay on a delivery. See Webhooks in the portal.
- With the API: list attempts with
GET /v1/webhooks/:id/deliveries, thenPOST /v1/webhooks/:id/deliveries/:deliveryId/replay.
A replay sends the same event with the same id, signed with a fresh timestamp. Your deduplication sees it as already processed if it was.
curl -X POST https://api.smsfabric.com/v1/webhooks/whk_p9s2v5y8b1e4h7k0n3q6t9w2/deliveries/dlv_f3i6l9o2r5u8x1a4d7g0j3m6/replay \ -H "X-Api-Key: $SMSFABRIC_API_KEY"Receive events on your machine
Section titled “Receive events on your machine”While you build a webhook handler, your laptop has no public https address for SMSFabric to call. The listen stream solves that: your machine opens one outbound connection and gets the organization’s events over it, with no tunnel.
With the CLI, forward every event to your local handler, signed exactly like a real delivery:
export SMSFABRIC_API_KEY=sf_test_xxxxxxxxxxxx_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxexport SMSFABRIC_WEBHOOK_SECRET=whsec_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxsmsfabric listen --forward-to http://localhost:3000/hooks/smsfabricYour handler verifies the SMSFabric-Signature header with SMSFABRIC_WEBHOOK_SECRET, so the code above runs unchanged. Without that variable, the CLI makes a secret for the run and prints it once.
In Node, read the same stream with the SDK’s webhooks.listen():
import { SMSFabric } from '@smsfabric/sdk';
const sms = new SMSFabric({ apiKey: process.env.SMSFABRIC_API_KEY });const stop = new AbortController();process.once('SIGINT', () => stop.abort());
for await (const event of sms.webhooks.listen({ events: ['message.delivered', 'message.failed'], signal: stop.signal })) { console.log(event.type, event.id, event.payload.data);}The key needs webhooks:manage. The stream itself is described in the API reference.
Checklist
Section titled “Checklist”- Answer
2xxfast, then do the work in a queue. - Verify the signature on the raw body, with a 300-second tolerance.
- Deduplicate on
SMSFabric-Event-Id. - Keep the signing secret in a secret store. To change it, create a new endpoint, deploy its secret, then delete the old endpoint.
- Watch failed deliveries in the portal, and replay them after an outage.