Webhooks in. API out.
Every message and event reaches your server as a signed webhook. Your CRM, agent or helpdesk answers through the API.
37 webhook events · OpenAPI 3.0
Your tools decide. iSnap texts.
iSnap doesn't replace your CRM or your agent. It gives them a phone: events in by webhook, messages out by API.
- Subscribe
POST /v1/webhooks with your HTTPS URL and the events you want. The signing secret comes back once. - Verify
Check the Standard Webhooks signature on the raw body before you parse it. - Respond fast
Return 2xx within 10 seconds, then do the work. - Decide
Your CRM or agent picks the answer, using the chat and your line metadata. - Send
POST /v1/messages with an Idempotency-Key, so a retry never sends twice.
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.*"]
}'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.From the docs: Quickstart, receive its events
37 events in nine families.
Subscribe to an exact type, to a family with message.*, or to everything with *.
- message.* (9)
queued, scheduled, sent, delivered, read, failed, received, cancelled, fallback_triggered - reaction.* (3)
added, received, removed - line.* (12)
connected, disconnected, offline, degraded, apple_id_flagged, quota_warning, quota_exceeded, capability_changed, terminated, variant_changed, variant_scheduled, variant_unscheduled - trial.* (5)
linked, dormant, reactivated, bind_conflict, revoked - pre_order.* (2)
fulfilled, cancelled
- macos_session.* (2)
rented, released - binding.* (1)
released - webhook.* (1)
test, a probe of a suspended subscription - typing_indicator.* (2)
started, stopped. iMessage lines never send these.
Some changes send no event (a reservation, an activation, a config change), so reconcile from the API. Every payload is in the event catalog.
At least once, in any order.
Webhooks are built for retries: dedupe on event_id, don't rely on order, and treat the API as the source of truth.
- Retries
Up to 7 attempts: at once, then after 30 s, 1 min, 5 min, 30 min, 2 h and 12 h. - Suspension
After 10 deliveries in a row fail every attempt, the subscription pauses, and events in the meantime are lost. - Replay and catch up
Replay a finished delivery while its record exists, at least 72 hours, or read the events feed.
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")import { 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
}From the docs: Verifying signatures, with Python
TypeScript SDK, or plain HTTP.
@isnap/sdk types every operation and handles retries. Any other language calls the same REST API with JSON.
- Typed errors
AuthenticationError, RateLimitError, QuotaExceededError, ConflictError and more. - Safe retries
On connection failures, timeouts, 500 and 503, with an Idempotency-Key on every write. - Webhook helpers
verifyWebhook, plus type guards such as isMessageEvent. - OpenAPI 3.0
At api.isnap.ai/openapi.json, no key needed.
import { ISnapClient } from '@isnap/sdk'
// The constructor throws when the key is missing or empty.
const client = new ISnapClient({ apiKey: process.env.ISNAP_API_KEY ?? '', maxRetries: 2 })
const { version } = await client.version()
console.log(`API version: ${version}`)
const { lines } = await client.lines.listMine()
for (const line of lines) {
console.log(line.id, line.status)
}import os
import requests
response = requests.get(
"https://api.isnap.ai/v1/lines/my",
headers={"Authorization": f"Bearer {os.environ['ISNAP_API_KEY']}"},
timeout=30,
)
body = response.json()
if response.status_code != 200:
raise SystemExit(f"{body['error']['status']} {body['error']['code']}: {body['error']['message']}")
for line in body["data"]["lines"]:
print(line["id"], line["billing_tier"], line["status"], line["inbound_only"])curl -sS https://api.isnap.ai/v1/lines/my \
-H "Authorization: Bearer $ISNAP_API_KEY"From the docs: TypeScript SDK
Connect your CRM by webhook.
If your CRM can receive a webhook and make an HTTPS call, it can text through iSnap. Your records stay where they are.
- Tag lines with your ids
Line metadata, such as a crm_account_id, rides on every event. Use ids, not personal data: anyone with the line id can read it. - Thread by chat
A chat is one line and one contact, and it follows the line. Key conversations on chat_id. - Keep your own history
iSnap deletes messages at least 72 hours after recording them. Store what you need. - GoHighLevel
The BYOP plan includes a native GoHighLevel integration. See pricing.
- event_id
- Your dedupe key; the same on retries and replays
- event_type
- message.received
- data.message
- The body, from, to, service (iMessage or SMS) and status
- data.chat_id
- The thread: one line and one contact
- data.contact_name
- When the device reports one
- data.line_metadata
- Your ids, set on the line
- trace_id
- Quote it to support
The whole payload: the event envelope.
Where to go next.
Put a real iPhone
to work.
Start free with no credit card. Rent a line, or bring your own iPhone.