Skip to content
Codelia SMSDocs
Guides: Webhooks

Webhooks

A webhook endpoint is a URL of yours that we send events to: when a message is delivered or fails, when a campaign finishes, and when a number opts out or opts back in. Each request is signed, so you can check it came from us.

Add an endpoint

Send the URL and the events you want to POST /organizations/{accountId}/webhook-endpoints. The API key needs webhooks:write:

curl -X POST "https://api.sms.codelia.studio/v1/organizations/$CODELIA_ACCOUNT_ID/webhook-endpoints" \
  -H "Authorization: Bearer $CODELIA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
  "url": "https://hooks.example.com/codelia",
  "description": "Delivery reports for the order system",
  "eventTypes": [
    "message.delivered",
    "message.failed",
    "campaign.completed",
    "campaign.partial_failure",
    "campaign.failed"
  ]
}'
  • url must use HTTPS and be reachable from the internet, up to 2,048 characters.
  • eventTypes needs at least one event. The opt-out events, contact.opted_out and contact.opted_in, also need opt-outs:read, because they carry the numbers on your opt-out list.
  • description is optional, up to 200 characters.

The answer includes secret, the key you check signatures with. It's shown only this once: store it now, because no other answer includes it. There's no way to change an endpoint's secret: to get a new one, add a new endpoint, then delete the old one.

You can also add endpoints, and see their deliveries, on the Webhooks screen in the portal.

Manage your endpoints

  • GET /organizations/{accountId}/webhook-endpoints lists your endpoints, newest first, and GET /organizations/{accountId}/webhook-endpoints/{endpointId} gets one. Neither includes the secret. These need webhooks:read.
  • PATCH /organizations/{accountId}/webhook-endpoints/{endpointId} changes the url, description, eventTypes or status. It needs webhooks:write, and also opt-outs:read to add an opt-out event or to change the url of an endpoint that gets them.
  • DELETE /organizations/{accountId}/webhook-endpoints/{endpointId} removes the endpoint and its deliveries, and nothing more is sent to it. It needs webhooks:write.

Events

typeSent when
message.deliveredA delivery report says the message was delivered.
message.failedA delivery report says the message is undelivered, failed or rejected.
campaign.completedA campaign finished completed.
campaign.partial_failureA campaign finished partial_failure.
campaign.failedA campaign finished failed, including one that sent to nobody, a scheduled campaign that couldn't go out, and a large campaign sent now that couldn't go out once it was accepted.
contact.opted_outA number opted out: with its unsubscribe link, or added by you in the portal, with the API or in a bulk opt-out.
contact.opted_inA number stopped being opted out: the person opted back in from their link, or you removed the opt-out.
webhook.testYou sent a test event. It isn't one you subscribe to.

Message events come from delivery reports, so only a message that was handed to the network gets one:

  • A message that was refused or skipped when it was sent, like a number that opted out or one we can't send to, a placeholder with no value, or provider_unavailable, gets no event. Its result is already in the answer to your request, or in the campaign's messages.
  • A message whose delivery report never arrives stays sending, and gets no event.

A canceled campaign gets no event.

The opt-out events are sent only when something changes. Adding an opt-out for a number that's already opted out sends no contact.opted_out, and removing one that isn't there sends no contact.opted_in. So an endpoint that keeps another system's list in step gets one event for each change. Use the event's id to ignore a repeat.

We send the opt-out events just after the change is saved, so the opt-out itself never waits for your endpoint. They usually arrive within seconds; a bulk opt-out of many numbers can take a little longer. If your endpoint is paused or disabled, or stops listening for the event, before one is sent, that delivery is canceled with the reason. Replay it to send it.

The request

Each event is a POST with a JSON body:

{
  "id": "evt_0a8d52b4-7c3e-5f1a-9b6d-2e4f8c1a7d30",
  "version": "2026-07-30",
  "type": "message.delivered",
  "created": "2026-10-01T09:30:12.000Z",
  "data": {
    "messageId": "5b1c6f2e-8a4d-4e3b-9f7a-1c2d3e4f5a6b",
    "direction": "outbound",
    "status": "delivered",
    "type": "marketing",
    "recipient": "+442079460123",
    "sender": "InfoSMS",
    "segments": 1,
    "priceMicros": 55000,
    "currency": "EUR",
    "countryCode": "GB",
    "errorCode": null,
    "errorDescription": null,
    "sentAt": "2026-10-01T09:30:05.000Z",
    "deliveredAt": "2026-10-01T09:30:11.000Z"
  }
}

The data of a campaign.* event:

{
  "campaignId": "c3f1a9e2-4b7d-4c8a-9e1f-2a3b4c5d6e7f",
  "status": "partial_failure",
  "type": "marketing",
  "recipientCount": 1200,
  "sentCount": 1180,
  "failedCount": 4,
  "skippedCount": 16,
  "totalMicros": 64900000,
  "currency": "EUR",
  "recurringCampaignId": null,
  "failureReason": null
}

status is how the campaign finished: see Follow it. failureReason is set when no one in the campaign could be sent to, when a scheduled campaign couldn't go out when it was due, or when a large campaign sent now couldn't go out once it was accepted. It's also feature_not_enabled when a transactional campaign stopped while sending because your organization's access to transactional messages was turned off; see Transactional messages. Otherwise it's null. A message event's errorCode says why that message didn't arrive: see After you send.

The data of a contact.opted_out event:

{
  "phone": "+442079460123",
  "source": "link",
  "reason": null,
  "optedOutAt": "2026-10-01T09:30:12.000Z",
  "contactId": "8f2d4c1a-6b3e-4a7f-9c2d-5e1f3a4b6c7d"
}

source is how the number was opted out, as on the opt-out list: link, manual, api or imported. contactId is your contact with that number, or null if you have none.

The data of a contact.opted_in event:

{
  "phone": "+442079460123",
  "source": "manual",
  "optedInAt": "2026-10-03T14:05:40.000Z",
  "contactId": "8f2d4c1a-6b3e-4a7f-9c2d-5e1f3a4b6c7d"
}

source says who removed the opt-out: link when the person opted back in from their link, manual when someone in your organization removed it in the portal, and api when an API key or a connected app removed it.

New event types and new fields can be added, so ignore any you don't recognize.

Handle each event once

The same event can reach you more than once: when we try again after a failed attempt, and when you replay a delivery. id is the same every time we send the same event. Keep the IDs you've handled, skip an event whose id you've seen, and record it only once you've handled it, so an event that failed partway is handled when it comes again. Retrying safely explains keys on the sending side.

Check the signature

Every request has an X-Codelia-Signature header:

X-Codelia-Signature: t=1790847012,v1=5f2b…

t is when we signed it, in seconds since 1970. v1 is an HMAC-SHA256, in hex, of t, a period (.) and the raw request body, keyed with your endpoint's secret. Before you trust a request:

  1. Read the body as raw text, before you parse the JSON. Parsing and writing it out again changes the bytes, and the signature no longer matches.
  2. Work out the HMAC with the secret exactly as it was shown to you, as UTF-8 text. Don't decode it from hex.
  3. Compare it to v1 in constant time.
  4. Refuse the request if t is more than 5 minutes away from your clock.

A future signature could be added as v2 in the same header. Ignore any key you don't know.

This function does all four. It's TypeScript that uses the Web Crypto API (crypto.subtle) and imports nothing, so it works on Node.js 20 or later and in any runtime that has Web Crypto. For JavaScript, remove the type annotations:

verify-webhook.ts
/**
 * Checks that a webhook request came from Codelia SMS and wasn't changed on
 * the way. Pass the request body exactly as it arrived, before any JSON
 * parsing, the X-Codelia-Signature header, and the endpoint's secret.
 *
 * Uses the Web Crypto API (crypto.subtle) and imports nothing.
 */
export async function verifyWebhook(
  rawBody: string,
  signatureHeader: string | null,
  secret: string,
  nowSeconds: number = Math.floor(Date.now() / 1000),
): Promise<boolean> {
  // Without a secret, such as an unset environment variable, nothing verifies.
  if (!signatureHeader || !secret) return false;

  // The header is t=<seconds>,v1=<hex>. Ignore any key you don't know, such
  // as a future v2.
  let timestamp = "";
  const signatures: string[] = [];
  for (const part of signatureHeader.split(",")) {
    const separator = part.indexOf("=");
    if (separator === -1) continue;
    const key = part.slice(0, separator).trim();
    const value = part.slice(separator + 1).trim();
    if (key === "t") timestamp = value;
    if (key === "v1") signatures.push(value);
  }
  if (!/^\d+$/.test(timestamp) || signatures.length === 0) return false;

  // Refuse a request signed more than 5 minutes from your clock, so a request
  // someone recorded earlier stops working.
  if (Math.abs(nowSeconds - Number(timestamp)) > 300) return false;

  // The key is the secret's text as UTF-8, exactly as it was shown to you.
  // Don't decode it from hex.
  const encoder = new TextEncoder();
  const key = await crypto.subtle.importKey(
    "raw",
    encoder.encode(secret),
    { name: "HMAC", hash: "SHA-256" },
    false,
    ["verify"],
  );
  const signed = encoder.encode(`${timestamp}.${rawBody}`);

  for (const signature of signatures) {
    const bytes = hexToBytes(signature);
    // verify() does the comparison, so you don't compare the two signatures
    // yourself.
    if (bytes && (await crypto.subtle.verify("HMAC", key, bytes, signed))) {
      return true;
    }
  }
  return false;
}

/** 64 hex characters as 32 bytes, or null if it isn't that. */
function hexToBytes(hex: string) {
  if (!/^[0-9a-f]{64}$/i.test(hex)) return null;
  const bytes = new Uint8Array(32);
  for (let i = 0; i < 32; i += 1) {
    bytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
  }
  return bytes;
}

In a handler that takes a Fetch Request:

fetch-handler.ts
import { verifyWebhook } from "./verify-webhook";

export async function POST(request: Request) {
  const rawBody = await request.text();
  const valid = await verifyWebhook(
    rawBody,
    request.headers.get("X-Codelia-Signature"),
    process.env.CODELIA_WEBHOOK_SECRET ?? "",
  );
  if (!valid) return new Response(null, { status: 400 });

  const event = JSON.parse(rawBody);
  // Handle event.type here, and skip an event.id you've already handled.
  return new Response(null, { status: 204 });
}

In Express, read the body with express.raw, so it arrives untouched:

express-handler.ts
import express from "express";

import { verifyWebhook } from "./verify-webhook";

const app = express();

app.post(
  "/webhooks/codelia",
  express.raw({ type: "application/json" }),
  async (req, res) => {
    const rawBody = req.body.toString("utf8");
    const valid = await verifyWebhook(
      rawBody,
      req.get("X-Codelia-Signature") ?? null,
      process.env.CODELIA_WEBHOOK_SECRET ?? "",
    );
    if (!valid) return res.sendStatus(400);

    const event = JSON.parse(rawBody);
    // Handle event.type here, and skip an event.id you've already handled.
    res.sendStatus(204);
  },
);

Send a test event

POST /organizations/{accountId}/webhook-endpoints/{endpointId}/test sends a webhook.test event to the endpoint straight away, whatever events it's subscribed to and even while it's paused. {endpointId} is the id the endpoint was created with:

curl -X POST "https://api.sms.codelia.studio/v1/organizations/$CODELIA_ACCOUNT_ID/webhook-endpoints/$ENDPOINT_ID/test" \
  -H "Authorization: Bearer $CODELIA_API_KEY"

The answer is the delivery: its status, the lastStatusCode your server answered with, and the first 500 characters of what it said, in responseExcerpt.

Answer quickly

  • Answer with any 2xx status within 5 seconds. Anything else, including a redirect, counts as a failure: we don't follow redirects.
  • We try each event up to 3 times over a few seconds. If every try fails, the delivery is marked failed and isn't tried again on its own.
  • To send one again, find it with GET /organizations/{accountId}/webhook-endpoints/{endpointId}/deliveries and call POST /organizations/{accountId}/webhook-endpoints/{endpointId}/deliveries/{deliveryId}/replay. It sends the same body with the same id. A delivery still being tried is refused with 409 and delivery_in_flight. An opt-out event to an endpoint a connected app created is refused with 409 and event_not_permitted once that app can no longer see opt-outs.
  • Events can arrive in any order.
  • After 20 failed deliveries in a row, we disable the endpoint (status: "disabled"). Tests and replays don't count toward the 20. To turn it back on, send "status": "active" to PATCH /organizations/{accountId}/webhook-endpoints/{endpointId}.
  • You can pause an endpoint with "status": "paused". While an endpoint is paused or disabled, nothing is sent to it, and nothing that happened meanwhile is sent later.

When it's refused

StatuserrorWhat happenedWhat to do
400validation_errorThe url doesn't use HTTPS, has a user name or password in it, points to a private address, or isn't a URL. errors.url says which.Use a public HTTPS URL.
403insufficient_scopeYou chose an opt-out event, or changed the url of an endpoint that gets them, with an API key that doesn't have opt-outs:read.Use a key with opt-outs:read, or leave those events out.
409delivery_in_flightYou replayed a delivery that's still being tried.Wait until it finishes, then replay it.
409event_not_permittedYou replayed an opt-out event to an endpoint a connected app created, and that app can no longer see opt-outs.Give whoever connected it opt-outs:read again, or reconnect it with that permission.