> ## Documentation Index
> Fetch the complete documentation index at: https://docs.telaven.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Webhooks

> Instead of polling, let Messaly call your server when a message is delivered, a customer replies, someone opts out, a campaign finishes or a top-up lands.

## Set up an endpoint

**1. Add your URL**

In the dashboard, open **Settings → Webhooks** and add your HTTPS URL.

**2. Pick events**

Choose the events you want, or all of them.

**3. Copy the signing secret**

It starts with `whsec_` and is shown once. Keep it on your server.

**4. Test it**

Select **Test** next to the endpoint to receive a signed `ping` event.

## What Messaly sends

A `POST` with a JSON body. Every event has the same envelope; `data` depends on the event.

```http theme={null}
POST /telaven/webhooks HTTP/1.1
Content-Type: application/json
User-Agent: Telaven-Webhooks/1.0
X-Telaven-Event: sms.delivered
X-Telaven-Delivery: 0d6f2c1e-…
X-Telaven-Signature: t=1762939807,v1=5f2b9c…
```

```json theme={null}
{
  "id": "3b0e8f5c-…",
  "event": "sms.delivered",
  "createdAt": "2026-11-12T09:30:07.000Z",
  "data": {
    "campaignId": "6f1c…",
    "recipientId": "a3d2…",
    "phone": "+254712345678",
    "messageId": "ATXid_8f3…",
    "status": "delivered",
    "error": null
  }
}
```

## Events

> [accordion] sms.delivered
>
> The network confirms an SMS reached the phone.
>
> ```json theme={null}
> { "campaignId": "6f1c…", "recipientId": "a3d2…", "phone": "+254712345678", "messageId": "ATXid_8f3…", "status": "delivered", "error": null }
> ```

> [accordion] sms.failed
>
> The network reports an SMS couldn't be delivered. Its charge is refunded to your wallet.
>
> ```json theme={null}
> { "campaignId": "6f1c…", "recipientId": "a3d2…", "phone": "+254712345678", "messageId": "ATXid_8f3…", "status": "failed", "error": "AbsentSubscriber" }
> ```

> [accordion] sms.inbound
>
> Someone texts your shortcode or number (anything other than STOP/START).
>
> ```json theme={null}
> { "from": "+254712345678", "to": "22384", "text": "What time do you open on Saturday?" }
> ```

> [accordion] sms.opt\_out
>
> Someone replies STOP (or UNSUBSCRIBE, and so on). They're left out of your future sends automatically.
>
> ```json theme={null}
> { "phone": "+254712345678", "text": "STOP" }
> ```

> [accordion] campaign.completed
>
> An SMS or WhatsApp campaign finishes sending.
>
> ```json theme={null}
> { "channel": "sms", "campaignId": "6f1c…", "name": "November offer", "status": "completed", "totalSent": 1196, "totalFailed": 4 }
> ```

> [accordion] wallet.topup
>
> A wallet top-up is paid and credited.
>
> ```json theme={null}
> { "method": "paystack", "channel": "mobile_money", "amountCents": 500000, "reference": "TLV-8K2M…", "balanceCents": 1943750 }
> ```

> [accordion] whatsapp.inbound
>
> A customer messages your WhatsApp number.
>
> ```json theme={null}
> { "from": "254712345678", "name": "Jane", "type": "text", "text": "Is my order ready?", "wamid": "wamid.HBgM…", "optOut": false }
> ```

> [accordion] whatsapp.status
>
> A WhatsApp message you sent is `sent`, `delivered`, `read` or `failed`.
>
> ```json theme={null}
> { "wamid": "wamid.HBgM…", "status": "read", "error": null }
> ```

## Verify the signature

`X-Telaven-Signature` is `t=<unix seconds>,v1=<hex>`, where `v1 = HMAC-SHA256(secret, t + "." + rawBody)`.
Compute it over the **raw** request body, before any JSON parsing. Compare in constant time, and reject anything older than 5 minutes.

```javascript Node.js theme={null}
import crypto from "node:crypto";
import express from "express";

const app = express();

// Use the raw body: the signature is over the exact bytes Messaly sent.
app.post("/telaven/webhooks", express.raw({ type: "application/json" }), (req, res) => {
  const header = req.get("X-Telaven-Signature") ?? "";
  const { t, v1 } = Object.fromEntries(header.split(",").map((p) => p.split("=")));
  const expected = crypto
    .createHmac("sha256", process.env.TELAVEN_WEBHOOK_SECRET)
    .update(`${t}.${req.body}`)
    .digest("hex");

  const fresh = Math.abs(Date.now() / 1000 - Number(t)) < 300;
  const valid =
    v1 && v1.length === expected.length &&
    crypto.timingSafeEqual(Buffer.from(v1), Buffer.from(expected));
  if (!fresh || !valid) return res.status(400).send("bad signature");

  const event = JSON.parse(req.body);
  // event.id is unique: skip it if you've already handled it.
  console.log(event.event, event.data);
  res.sendStatus(200); // reply fast; do slow work in the background
});
```

```python Python theme={null}
import hashlib, hmac, json, os, time
from flask import Flask, request, abort

app = Flask(__name__)
SECRET = os.environ["TELAVEN_WEBHOOK_SECRET"].encode()

@app.post("/telaven/webhooks")
def telaven_webhook():
    raw = request.get_data()  # the exact bytes Messaly sent
    parts = dict(p.split("=", 1) for p in request.headers.get("X-Telaven-Signature", "").split(","))
    t, v1 = parts.get("t", "0"), parts.get("v1", "")
    expected = hmac.new(SECRET, f"{t}.".encode() + raw, hashlib.sha256).hexdigest()

    if abs(time.time() - int(t)) > 300 or not hmac.compare_digest(v1, expected):
        abort(400)

    event = json.loads(raw)
    print(event["event"], event["data"])
    return "", 200
```

```php PHP theme={null}
<?php
$raw = file_get_contents("php://input"); // the exact bytes Messaly sent
$secret = getenv("TELAVEN_WEBHOOK_SECRET");

$parts = [];
foreach (explode(",", $_SERVER["HTTP_X_TELAVEN_SIGNATURE"] ?? "") as $p) {
    [$k, $v] = array_pad(explode("=", $p, 2), 2, "");
    $parts[$k] = $v;
}
$t = $parts["t"] ?? "0";
$expected = hash_hmac("sha256", $t . "." . $raw, $secret);

if (abs(time() - (int) $t) > 300 || !hash_equals($expected, $parts["v1"] ?? "")) {
    http_response_code(400);
    exit("bad signature");
}

$event = json_decode($raw, true);
error_log($event["event"]);
http_response_code(200);
```

```csharp C# theme={null}
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;

var app = WebApplication.CreateBuilder(args).Build();
var secret = Encoding.UTF8.GetBytes(Environment.GetEnvironmentVariable("TELAVEN_WEBHOOK_SECRET")!);

app.MapPost("/telaven/webhooks", async (HttpRequest request) =>
{
    // Read the raw body: the signature is over the exact bytes Messaly sent.
    using var buffer = new MemoryStream();
    await request.Body.CopyToAsync(buffer);
    var raw = buffer.ToArray();

    var parts = new Dictionary<string, string>();
    foreach (var part in request.Headers["X-Telaven-Signature"].ToString().Split(','))
    {
        var kv = part.Split('=', 2);
        if (kv.Length == 2) parts[kv[0].Trim()] = kv[1].Trim();
    }
    if (!parts.TryGetValue("t", out var t) || !long.TryParse(t, out var timestamp) ||
        !parts.TryGetValue("v1", out var v1))
        return Results.BadRequest("bad signature");

    // Reject signatures more than 5 minutes old (or from the future).
    if (Math.Abs(DateTimeOffset.UtcNow.ToUnixTimeSeconds() - timestamp) > 300)
        return Results.BadRequest("bad signature");

    var signed = Encoding.UTF8.GetBytes(t + ".").Concat(raw).ToArray();
    var expected = HMACSHA256.HashData(secret, signed);
    byte[] received;
    try { received = Convert.FromHexString(v1); }
    catch (FormatException) { return Results.BadRequest("bad signature"); }

    if (!CryptographicOperations.FixedTimeEquals(expected, received))
        return Results.BadRequest("bad signature");

    using var evt = JsonDocument.Parse(raw);
    // The event's "id" is unique: skip it if you've already handled it.
    Console.WriteLine($"{evt.RootElement.GetProperty("event")} {evt.RootElement.GetProperty("data")}");
    return Results.Ok(); // reply fast; do slow work in the background
});

app.Run();
```

## Retries

* Reply with any **2xx** within **10 seconds**. Anything else, including a redirect, counts as a failure.
* A failed delivery is tried up to **6 times** in total, waiting about 10s, 20s, 40s, 80s and 160s between attempts.
* Retries keep the same `id` and `X-Telaven-Delivery`, so you can ignore duplicates.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.