Polling tells you what happened to a message you sent. Webhooks tell you what happened that you didn’t cause: the contact read it, reacted to it, wrote back. For an AI agent or a CRM, that second half is the whole conversation.
iSnap reports 37 event types, from message.received to line.offline. This recipe subscribes to the message family, verifies each delivery, and handles it the way the docs ask: fast, idempotent, and without trusting the order events arrive in.
message.received
1. Subscribe
POST /v1/webhooks takes the address iSnap should call and the events you want: an exact type such as message.received, a family wildcard such as message.*, or * for everything. Add line_ids to hear from some of your lines only.
import { ISnapClient } from '@isnap/sdk'
const client = new ISnapClient({ apiKey: process.env.ISNAP_API_KEY ?? '', maxRetries: 2 })
// maxRetries: 0, because this operation does not honor Idempotency-Key:
// a retry after a lost response would create a second subscription.
const subscription = await client.webhooks.create(
{ url: 'https://hooks.your-domain.example/isnap', events: ['message.*'] },
{ maxRetries: 0 }
)
console.log(subscription.id)
// Store subscription.secret now as ISNAP_WEBHOOK_SECRET: no other call returns it.curl -sS https://api.isnap.ai/v1/webhooks \
-H "Authorization: Bearer $ISNAP_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"url": "https://hooks.your-domain.example/isnap",
"events": ["message.*"]
}'- The secret comes once. The response holds the subscription’s signing secret, and no other call returns it. Store it as
ISNAP_WEBHOOK_SECRETbefore you do anything else. - This call is not idempotent. It ignores
Idempotency-Key, which is why the TypeScript sample turns retries off: a retry after a lost response would create a second subscription, and you would receive every event twice. - The address must be public. HTTPS on a public host with a standard certificate. iSnap refuses private and loopback addresses with
ssrf_blocked.
What iSnap sends
Each delivery is one HTTP POST whose body is one event, as compact UTF-8 JSON. The envelope always has six fields: api_version (always v1, which is not the API’s version), event_id, event_type, created_at, trace_id and data. Here is Dana’s reply:
{
"api_version": "v1",
"event_id": "evt_Fh50GcqYY37ay4VjUxQ2rR6jN",
"event_type": "message.received",
"created_at": "2026-10-08T14:22:57.143Z",
"trace_id": "174b4a27e4e4938fa67ea87b23a18579",
"data": {
"message": {
"id": "msg_7Hq3Zd9Kp2Vx6Wn4Tb8Lc5Ym1",
"line_id": "line_8Xk2mQ4vTn7Bw9Rz3Lc6Yp1Hd",
"direction": "inbound",
"kind": "message",
"to": "+14155550124",
"from": "+14155550123",
"body": "Is the table still free at 8?",
"channel": "iMessage",
"service": "iMessage",
"status": "delivered",
"effect": null,
"reply_to_message_id": null,
"use_typing_indicator": true,
"metadata": null,
"attachments": [],
"reactions": [],
"scheduled_for": null,
"schedule_reason": null,
"reply_lane": false,
"ignore_quiet_hours": false,
"queue_info": null,
"created_at": "2026-10-08T14:22:57.101Z",
"queued_at": null,
"sent_at": null,
"delivered_at": "2026-10-08T14:22:56.000Z",
"read_at": null,
"failed_at": null,
"error_code": null,
"error_message": null,
"cancelled_at": null
},
"chat_id": "chat_6Rm1Yb5Tq9Hd3Kx7Wc2Ln8Vz4",
"contact_name": "Dana Whitfield",
"received_at": "2026-10-08T14:22:56.000Z",
"metadata": null,
"line_metadata": { "crm_account_id": "acct_4821" }
}
}For message.received, data holds the message, the chat_id of the conversation, the contact_name when the device knows one, received_at, and two metadata objects: the message’s and the line’s. Line metadata is how one endpoint serves many customers. Put your own account id on each line once with PATCH /v1/lines/{id}, and every event from that line carries it, like crm_account_id above. Anyone who has a line’s id can read its metadata, so store an id there, never personal data.
The headers carry the signature: webhook-id (the event id), webhook-timestamp (Unix seconds, new on every attempt) and webhook-signature. The X-iSnap-* headers, with the event type, delivery id, attempt number and subscription id, are useful in logs but are not signed. Never trust them on their own.
2. Verify, then handle
This is the complete server from the SDK examples, with no framework. Read it top to bottom: the comments carry the rules.
import { createServer, type IncomingMessage } from 'node:http'
import {
WebhookSignatureError,
isMessageEvent,
verifyWebhook,
type WebhookEventBase
} from '@isnap/sdk'
const secret = process.env.ISNAP_WEBHOOK_SECRET
if (!secret) {
console.error('Set ISNAP_WEBHOOK_SECRET to the signing secret of your webhook subscription.')
process.exit(1)
}
// The ids of the events already processed. This set is lost on restart and is not
// shared between processes: replace it with storage of your own.
const processed = new Set<string>()
const processEvent = async (event: WebhookEventBase): Promise<void> => {
// Other families, probes and event types this script does not know: nothing to do.
if (!isMessageEvent(event)) return
const { message } = event.data
switch (event.event_type) {
case 'message.received':
console.log(`${message.id} received on ${message.line_id}`)
break
case 'message.failed':
console.log(`${message.id} failed: ${message.error_code ?? 'reported by the device'}`)
break
}
}
const handle = async (req: IncomingMessage): Promise<number> => {
if (req.method !== 'POST' || req.url !== '/webhooks/isnap') return 404
// Keep the body as received. Verification fails on a body that was parsed and serialized again.
const chunks: Buffer[] = []
for await (const chunk of req) chunks.push(chunk as Buffer)
const rawBody = Buffer.concat(chunks).toString('utf8')
let event: WebhookEventBase
try {
event = verifyWebhook(rawBody, req.headers, secret)
} catch (err) {
if (err instanceof WebhookSignatureError) return 400
throw err
}
// A retry or a replay carries the same event_id.
if (processed.has(event.event_id)) return 200
await processEvent(event)
// Record the event_id only after the work succeeded. When processEvent throws,
// the server responds 500, and the next attempt, if one remains, processes the event.
processed.add(event.event_id)
return 200
}
const server = createServer((req, res) => {
handle(req).then(
(status) => {
res.writeHead(status).end()
},
() => {
res.writeHead(500).end()
}
)
})
server.listen(3000, () => {
console.log('Listening on port 3000, path /webhooks/isnap')
})Four things it gets right, and your handler should too:
- It verifies the raw body.
verifyWebhookchecks the signature against the bytes exactly as they arrived. Parse the JSON and serialize it again, and verification fails, because the bytes changed. If your framework parses JSON for you, turn that off for this route. - It refuses what it can’t verify. A bad or missing signature, or a timestamp too far from your clock, throws
WebhookSignatureError, and the handler answers 400 without touching the event. - It dedupes on
event_id. A retry or a replay carries the same id, and the handler records an id only after the work succeeded. As its comment says, replace the in-memory set with storage of your own: a set is lost on restart and isn’t shared between processes. - It ignores what it doesn’t know.
isMessageEventfilters the family, and event types the handler has never seen fall through. iSnap adds event types in minor versions, so a handler that throws on an unknown type breaks on an ordinary release.
The rules your endpoint must follow
- Answer 2xx within 10 seconds. Respond first and do the slow work after, in a queue. A call to a language model does not belong between the request and the response.
- No redirects. A 3xx counts as a failed attempt.
- Never answer 410. It turns the subscription off.
- Don’t rely on order. Events can arrive in any order. When order matters, read the resource:
GET /v1/messages/{id}is the source of truth, not the last event you saw. - Accept unknown types. Answer 200 and move on.
Retries, suspension and replays
iSnap delivers each event at least once while the subscription is active, so duplicates are normal. A failed delivery gets up to 7 attempts in all: at once, then after 30 seconds, 1 minute, 5 minutes, 30 minutes, 2 hours and 12 hours, about 14 and a half hours end to end. iSnap ignores Retry-After on your responses.
After 10 deliveries in a row fail every attempt, iSnap suspends the subscription and probes it with webhook.test, at least 15 minutes apart. Events that happen during a suspension are lost. Watch failure_count and last_failure_at on GET /v1/webhooks/{id} and fix a failing endpoint long before it gets there.
Two ways to catch up after an outage on your side:
- Replay a delivery.
POST /v1/webhooks/{id}/deliveries/{delivery_id}/replaysends a finished delivery’s event again, while its record exists: at least 72 hours. - Pull the events feed.
GET /v1/webhooks/events, with a requiredsince, lists the last 72 hours of events that matched an active subscription.
Neither replaces the API as the record. Events can be lost, so when your data and iSnap’s disagree, read the message or the line. The delivery guarantees page states all of this in one place.
Verify without the SDK
The scheme is Standard Webhooks, so any Standard Webhooks library works with the secret exactly as iSnap returns it. To write the check yourself:
- Build the signed content: the
webhook-id, a dot, thewebhook-timestamp, a dot, then the raw body. - Take the key: the base64 decoding of the secret after its
whsec_prefix. Not its hexadecimal decoding. - Compute HMAC-SHA256 over the content and base64 it. The header holds one or more signatures separated by spaces, each prefixed
v1,. - Compare in constant time, and refuse a timestamp more than 300 seconds from your clock.
The docs’ Python version uses only the standard library:
import base64
import hashlib
import hmac
import json
import time
TOLERANCE_SECONDS = 300
def verify_delivery(raw_body: bytes, headers, secret, now=None) -> dict:
"""Verifies one delivery and returns the parsed event. Raises ValueError otherwise.
raw_body the request body exactly as received, as bytes
headers a mapping of header names in lowercase to their values
secret the signing secret, or a list of secrets during a rotation
now the current time in Unix seconds
"""
message_id = headers.get("webhook-id")
timestamp = headers.get("webhook-timestamp")
signatures = headers.get("webhook-signature")
if not message_id or not timestamp or not signatures:
raise ValueError("missing signature header")
now = time.time() if now is None else now
if not (timestamp.isascii() and timestamp.isdigit()):
raise ValueError("malformed timestamp")
if abs(now - int(timestamp)) > TOLERANCE_SECONDS:
raise ValueError("timestamp outside the tolerance")
signed = f"{message_id}.{timestamp}.".encode() + raw_body
given = [entry[3:] for entry in signatures.split(" ") if entry.startswith("v1,")]
for candidate in [secret] if isinstance(secret, str) else secret:
# The key is the base64 decoding of the secret without its prefix, not its hexadecimal decoding.
key = base64.b64decode(candidate.removeprefix("whsec_"))
expected = base64.b64encode(hmac.new(key, signed, hashlib.sha256).digest()).decode()
# Constant-time comparison.
if any(hmac.compare_digest(expected.encode(), signature.encode()) for signature in given):
return json.loads(raw_body)
raise ValueError("signature mismatch")When you rotate the secret with POST /v1/webhooks/{id}/rotate-secret, the old one keeps working until old_secret_expires_at. Both helpers accept a list of secrets for that window: pass the new one and the old one. The signatures page publishes a test vector to check your own implementation against.
For an AI agent: the reply loop
With verification in place, an agent’s loop is short. On message.received, record the event_id and answer 200. In your worker, load your own record of the conversation by chat_id (iSnap keeps messages for at least 72 hours, not forever), let your agent decide the answer, and send it with POST /v1/messages from message.line_id to message.from. Because the contact just wrote, the answer takes the reply lane: it skips the line’s hourly and daily caps and quiet hours.
Treat the text as untrusted input. The docs’ AI agents page asks agents to treat data from the API as untrusted, and for a conversational agent that is literal: the body of a message.received was written by whoever holds the other phone, and it can carry instructions aimed at your model.
Your handler is also where opt-outs arrive. iSnap has no automatic STOP handling: when a contact asks you to stop texting them, your code records it and your agent stops. You need permission to text people in the first place, and honoring an opt-out is your job, not the line’s.
Next, make the answers feel like a person’s: read receipts, typing and tapbacks are in recipe 03.
Next recipe: A natural rhythm for agents. Or go back to all recipes and the API at a glance.