New: every plan now includes free incoming texts and rollover credits. See pricing →
Search Help Center Documentation

Guide

Webhooks

SMSBlast posts an event to your server the moment something happens: a reply comes in, a text is delivered, someone opts out.

Set up an endpoint#

An endpoint is a URL on your server that accepts POST requests. Add one in the dashboard at Settings → Developers (Add webhook), or with POST /v1/webhooks:

curl -X POST https://app.smsblast.net/v1/webhooks \
  -H "Authorization: Bearer $SMSBLAST_API_KEY" \
  -H "Idempotency-Key: $(openssl rand -hex 16)" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://hooks.example.com/smsblast",
    "events": [
      "message.received",
      "contact.opted_out"
    ],
    "description": "CRM sync"
  }'
const res = await fetch('https://app.smsblast.net/v1/webhooks', {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${process.env.SMSBLAST_API_KEY}`,
    'Idempotency-Key': crypto.randomUUID(),
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    url: 'https://hooks.example.com/smsblast',
    events: ['message.received', 'contact.opted_out'],
    description: 'CRM sync',
  }),
});
console.log(res.status, await res.json());
import os
import uuid

import requests

res = requests.post(
    "https://app.smsblast.net/v1/webhooks",
    headers={
        "Authorization": f"Bearer {os.environ['SMSBLAST_API_KEY']}",
        "Idempotency-Key": str(uuid.uuid4()),
    },
    json={
        "url": "https://hooks.example.com/smsblast",
        "events": ["message.received", "contact.opted_out"],
        "description": "CRM sync",
    },
)
print(res.status_code, res.json())
  • The address must be a public https:// URL. Addresses in private networks are refused when you save the webhook and again before every delivery, and redirects are not followed.
  • Choose the events it gets, or ["*"] for all of them. An account can have up to 10 webhooks.
  • The answer includes the signing secret (whsec_...). Fetch it again any time with GET /v1/webhooks/{id}, and replace it with POST /v1/webhooks/{id}/rotate-secret: the old secret stops working at once, so update your server straight after.

Events#

EventWhen
message.receivedA text came in. Someone texted one of your numbers.
message.sentA text was sent. The carrier accepted one of your outgoing texts, of any kind (campaign, API, inbox, workflow, keyword reply, compliance answer or test).
message.deliveredA text was delivered. The carrier confirmed one of your texts reached the phone.
message.failedA text failed. One of your texts could not be sent, or the carrier reported it undelivered.
contact.createdA contact was added. A contact was added: with POST /v1/contacts (or by hand in the dashboard), by texting a signup keyword, or as an opt-out record when an unknown number texted STOP (then status is unsubscribed).
contact.opted_inA contact opted in. A contact agreed to get your texts: added with consent through POST /v1/contacts (or by hand), texted a signup keyword, or texted START after opting out.
contact.opted_outA contact opted out. A contact opted out: they texted STOP or a similar word or phrase (source sms:...), or were unsubscribed with POST /v1/contacts/bulk or in the dashboard (manual).
campaign.sendingA campaign was sent or scheduled. A campaign was sent (or scheduled, then scheduledFor is set) and its texts are queued.
campaign.sentA campaign finished. Every text of a campaign has gone out or ended.
link.clickedA tracked link was clicked. A person opened a tracked link in one of your texts for the first time.
webhook.testTest event. Sent only when you call POST /v1/webhooks/{id}/test, even to a webhook that is switched off.

The webhook events reference shows every payload field.

What a delivery looks like#

Each delivery is a POST with a JSON body: an envelope with the event id, its type, when it happened (created) and the event's data.

Body · message.received
{
  "id": "evt_Qm4xT9rV2kLp8NwZ",
  "type": "message.received",
  "created": "2026-11-20T16:45:03.200Z",
  "data": {
    "message": {
      "id": "d1f3a5c7-9e0b-4d2f-a4c6-e8f0b2d4f697",
      "direction": "inbound",
      "status": "received",
      "kind": "inbound",
      "from": "+14155550101",
      "to": "+14155550100",
      "body": "Do you have rye bread today?",
      "mediaUrls": [],
      "credits": 0,
      "contactId": "0f8d5c3a-6b2e-4f1d-9a7c-3e5b8d2f1a60",
      "campaignId": null,
      "error": null,
      "sendAt": null,
      "createdAt": "2026-11-20T16:45:03.118Z",
      "sentAt": null,
      "deliveredAt": null
    }
  }
}

It comes with these headers:

SMSBlast-Signaturestringrequired

t=<unix seconds>,v1=<hex HMAC-SHA256>. The HMAC is of <t>.<raw body> with your webhook's secret as the key. Check it before trusting the body.

Example "t=1795712703,v1=5f0b6a8e2d4c71f9b3a0e6d2c8f41a7b9e3d5c0f2a6b8d1e4f7a9c3b5d2e8f01".

SMSBlast-Event-Idstringrequired

The event id, the same as id in the body.

Example "evt_Qm4xT9rV2kLp8NwZ".

SMSBlast-Event-Typestringrequired

The event type, the same as type in the body.

plus Content-Type: application/json and User-Agent: SMSBlast-Webhooks/1.0.

Verify the signature#

Anyone can post to your URL, so check that each delivery came from SMSBlast before you trust it. The SMSBlast-Signature header looks like this:

Header
SMSBlast-Signature: t=1795712703,v1=5f0b6a8e2d4c71f9b3a0e6d2c8f41a7b9e3d5c0f2a6b8d1e4f7a9c3b5d2e8f01
  1. Split the header on commas into t (Unix seconds) and v1 (a hex HMAC-SHA256).
  2. Compute an HMAC-SHA256 with your webhook's secret as the key, over <t>.<raw body>: the value of t, a dot, and the exact bytes of the request body. Use the raw body: JSON that has been parsed and serialised again will not match.
  3. Compare it with v1 in constant time, and refuse the delivery if they differ or if t is more than 5 minutes from now.

Complete receivers, each verifying the signature, skipping repeats and answering at once:

// server.mjs: npm install express, then SMSBLAST_WEBHOOK_SECRET=whsec_... node server.mjs
import crypto from 'node:crypto';
import express from 'express';

const SECRET = process.env.SMSBLAST_WEBHOOK_SECRET; // the webhook's signing secret, whsec_...
const TOLERANCE = 300; // seconds; refuse deliveries signed longer ago than this
const seen = new Set(); // event ids already handled (use your database in production)

function verify(rawBody, header) {
  if (!header) return false;
  const parts = Object.fromEntries(header.split(',').map((p) => p.split('=', 2)));
  const t = Number(parts.t);
  if (!Number.isInteger(t) || !parts.v1 || Math.abs(Date.now() / 1000 - t) > TOLERANCE) return false;
  const expected = crypto.createHmac('sha256', SECRET).update(`${t}.`).update(rawBody).digest();
  const given = Buffer.from(parts.v1, 'hex');
  return given.length === expected.length && crypto.timingSafeEqual(given, expected);
}

const app = express();

// express.raw keeps the exact bytes we sent: the signature is over those, not over parsed JSON.
app.post('/webhooks/smsblast', express.raw({ type: 'application/json' }), (req, res) => {
  if (!verify(req.body, req.get('SMSBlast-Signature'))) return res.status(400).send('Bad signature');
  const event = JSON.parse(req.body.toString('utf8'));
  res.sendStatus(200); // answer at once; do slow work after

  if (seen.has(event.id)) return; // the same event can arrive more than once
  seen.add(event.id);

  switch (event.type) {
    case 'message.received':
      console.log(`Text from ${event.data.message.from}: ${event.data.message.body}`);
      break;
    case 'contact.opted_out':
      console.log('Opted out:', event.data);
      break;
    default:
      console.log('Event', event.type, event.id);
  }
});

app.listen(3000, () => console.log('Listening on http://localhost:3000/webhooks/smsblast'));
# app.py: pip install flask, then SMSBLAST_WEBHOOK_SECRET=whsec_... flask run --port 3000
import hashlib
import hmac
import json
import os
import time

from flask import Flask, abort, request

SECRET = os.environ["SMSBLAST_WEBHOOK_SECRET"]  # the webhook's signing secret, whsec_...
TOLERANCE = 300  # seconds; refuse deliveries signed longer ago than this
seen = set()  # event ids already handled (use your database in production)

app = Flask(__name__)


def verify(raw_body: bytes, header: str | None) -> bool:
    if not header:
        return False
    parts = dict(p.split("=", 1) for p in header.split(",") if "=" in p)
    try:
        t = int(parts["t"])
    except (KeyError, ValueError):
        return False
    if "v1" not in parts or abs(time.time() - t) > TOLERANCE:
        return False
    expected = hmac.new(SECRET.encode(), f"{t}.".encode() + raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, parts["v1"])


@app.post("/webhooks/smsblast")
def smsblast_webhook():
    raw = request.get_data()  # the exact bytes we sent: the signature is over those
    if not verify(raw, request.headers.get("SMSBlast-Signature")):
        abort(400)
    event = json.loads(raw)

    if event["id"] in seen:  # the same event can arrive more than once
        return "", 200
    seen.add(event["id"])

    if event["type"] == "message.received":
        message = event["data"]["message"]
        print(f"Text from {message['from']}: {message['body']}")
    elif event["type"] == "contact.opted_out":
        print("Opted out:", event["data"])
    else:
        print("Event", event["type"], event["id"])
    return "", 200  # answer within 10 seconds; hand slow work to a queue
<?php
// webhook.php: point your webhook at this file, with SMSBLAST_WEBHOOK_SECRET set on the server.
$secret = getenv('SMSBLAST_WEBHOOK_SECRET'); // the webhook's signing secret, whsec_...
$payload = file_get_contents('php://input'); // the exact bytes we sent: the signature is over those
$header = $_SERVER['HTTP_SMSBLAST_SIGNATURE'] ?? '';

function smsblast_verify(string $payload, string $header, string $secret, int $tolerance = 300): bool
{
    $parts = [];
    foreach (explode(',', $header) as $piece) {
        $kv = explode('=', $piece, 2);
        if (count($kv) === 2) {
            $parts[$kv[0]] = $kv[1];
        }
    }
    if (!isset($parts['t'], $parts['v1']) || !ctype_digit($parts['t'])) {
        return false;
    }
    if (abs(time() - (int) $parts['t']) > $tolerance) {
        return false;
    }
    $expected = hash_hmac('sha256', $parts['t'] . '.' . $payload, $secret);
    return hash_equals($expected, $parts['v1']);
}

if (!smsblast_verify($payload, $header, $secret)) {
    http_response_code(400);
    exit('Bad signature');
}

$event = json_decode($payload, true);
// The same event can arrive more than once: skip ids you have already handled
// (for example with a database table that has a unique index on the event id).

switch ($event['type']) {
    case 'message.received':
        error_log('Text from ' . $event['data']['message']['from'] . ': ' . $event['data']['message']['body']);
        break;
    case 'contact.opted_out':
        error_log('Opted out: ' . json_encode($event['data']));
        break;
}

http_response_code(200); // answer within 10 seconds

Answer quickly, expect retries#

  • Answer with any 2xx status within 10 seconds. Do slow work afterwards, for example in a queue.
  • Anything else (an error status, a redirect, no answer in 10 seconds, a failed connection) is retried after 1 minute, 5 minutes, 30 minutes, 2 hours, 6 hours, 12 hours and 24 hours: 8 attempts over about two days. Then the delivery is marked failed; send it again with POST /v1/webhooks/{id}/deliveries/{deliveryId}/retry.
  • An endpoint that fails 100 deliveries in a row is switched off. Fix it, then switch it back on in the dashboard or with PATCH /v1/webhooks/{id} ("enabled": true). Events that happen while an endpoint is off are not sent later.
  • Every attempt is in the delivery log for 30 days: GET /v1/webhooks/{id}/deliveries, or the webhook's page in the dashboard.

Repeats and order#

The same event can arrive more than once (a retry after a timeout, or a delivery you sent again), and events can arrive out of order. Each event has an id, also sent as SMSBlast-Event-Id: store the ids you have handled and skip any you have seen. Use created to put events in order, or fetch the latest state from the API when order matters.

Test your endpoint#

Choose Send test event on the webhook's page in the dashboard, or call POST /v1/webhooks/{id}/test. It sends a webhook.test event, signed like any other:

Body · webhook.test
{
  "id": "evt_Qm4xT9rV2kLp8NwZ",
  "type": "webhook.test",
  "created": "2026-11-20T16:45:03.200Z",
  "data": {
    "message": "This is a test event from SMSBlast. If you can read it, your endpoint works."
  }
}
  • A test event is sent even to a webhook that is switched off. It is tried once, never retried, and does not count towards switching a failing webhook off.
  • The answer gives the deliveryId; see how it went in the delivery log.
  • Webhook addresses must be public, so to test against your own computer use a tunnelling tool that gives you a public https:// address.