# API: webhooks, events and signatures

_API · 7 min read · Updated 2026-10-22 · https://lanachat.ai/guides/api-webhooks/_

A **webhook** sends an HTTPS `POST` to your server when something happens in the workspace: a new conversation, a sale, a media ready, an account that lost its connection. You choose the events; LanaChat signs every delivery so you can check it came from us, and retries when your server does not answer.

## Endpoints

| Method | Path | Description | Permission | Status |
|---|---|---|---|---|
| GET | `/webhooks` | List webhook endpoints | `owner` | Planned |
| POST | `/webhooks` | Add an endpoint: URL and events (the signing secret is shown once) | `owner` | Planned |
| GET | `/webhooks/{id}` | One endpoint and its delivery rate over 7 days | `owner` | Planned |
| PATCH | `/webhooks/{id}` | Change its URL or events, pause or resume it | `owner` | Planned |
| DELETE | `/webhooks/{id}` | Remove an endpoint | `owner` | Planned |
| POST | `/webhooks/{id}/rotate-secret` | New signing secret; the old one works 24 hours more | `owner` | Planned |
| POST | `/webhooks/{id}/test` | Send a `ping` event now | `owner` | Planned |
| GET | `/webhooks/{id}/deliveries` | Recent deliveries, their status and answer | `owner` | Planned |
| POST | `/webhooks/{id}/deliveries/{delivery_id}/retry` | Send one delivery again | `owner` | Planned |

## Events

| Event | Sent when | Permission the data needs |
|---|---|---|
| `conversation.started` | A fan writes for the first time (with `source_link_id` when known) | `can_fan_read` |
| `conversation.needs_review` | A conversation gets a Review or Safety hold status | `can_fan_read` |
| `conversation.taken_over` | A person takes a conversation over, or gives it back | `can_fan_read` |
| `message.received` | A fan sends a message | `can_fan_read` |
| `sale.completed` | A verified purchase (Stars or payment link) | `can_sales_read` |
| `sale.refunded` | A refund is confirmed | `can_sales_read` |
| `media.ready` | An uploaded media is processed, or failed | `can_setup` |
| `account.health_changed` | An account goes connected, pending or expired | `can_setup` |
| `pool.saturated` | A pool reaches 95% of its hourly capacity, or the workspace cap | `can_tracking` |
| `brain.published` | A brain draft is published | `can_engine` |
| `billing.low_balance` | The balance drops under the amount of the next 7 days of licences | `owner` |
| `ping` | You pressed Test | none |

An endpoint receives an event only if the token that created it has the permission its data needs.

## The webhook endpoint object

```json
{
  "id": "wh_12",
  "url": "https://hooks.mia-agency.com/lanachat/webhook",
  "events": ["sale.completed", "sale.refunded", "conversation.needs_review"],
  "status": "active",
  "delivery_rate_7d": 0.998,
  "created_at": "2026-10-01T09:00:00Z"
}
```

| Field | Type | Description |
|---|---|---|
| `id` | string | The endpoint |
| `url` | string | Your HTTPS URL |
| `events` | array of strings | The events it receives (see the table above) |
| `status` | string | `active` or `paused` (by you, or after 3 days of failures) |
| `delivery_rate_7d` | number | Share of deliveries answered `2xx` over 7 days, 0 to 1 |
| `created_at` | string | ISO 8601, UTC |

## Manage endpoints

All these calls need an **owner** token.

### Add an endpoint

`POST /webhooks` · `owner`

| Parameter | Type | Required | Description |
|---|---|---|---|
| `url` | string | Yes | An HTTPS URL of your server |
| `events` | array of strings | Yes | The events to receive |

```bash
curl -X POST https://api.lanachat.ai/v1/webhooks \
  -H "Authorization: Bearer $LANACHAT_TOKEN" \
  -H "Idempotency-Key: $(uuidgen)" \
  -H "Content-Type: application/json" \
  -d '{"url": "https://hooks.mia-agency.com/lanachat/webhook", "events": ["sale.completed", "sale.refunded"]}'
```

The answer is the endpoint (`201`) and its **signing secret**, shown in this answer only: store it at once, next to your token. An unknown event name answers `400`.

### List, read, change and remove

| Call | What it does |
|---|---|
| `GET /webhooks` | Every endpoint of the workspace |
| `GET /webhooks/{id}` | One endpoint and its delivery rate over 7 days |
| `PATCH /webhooks/{id}` | Change `url` or `events`; pause or resume it with `status` |
| `DELETE /webhooks/{id}` | Remove it; nothing more is sent |

```bash
curl -X PATCH https://api.lanachat.ai/v1/webhooks/wh_12 \
  -H "Authorization: Bearer $LANACHAT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"status": "active"}'
```

### Rotate the secret

`POST /webhooks/{id}/rotate-secret` · `owner`

```bash
curl -X POST https://api.lanachat.ai/v1/webhooks/wh_12/rotate-secret \
  -H "Authorization: Bearer $LANACHAT_TOKEN" \
  -H "Idempotency-Key: $(uuidgen)"
```

The answer carries the new secret, once. The old one keeps working 24 hours, so you can deploy the new one without losing a delivery.

### Send a test

`POST /webhooks/{id}/test` · `owner`

```bash
curl -X POST https://api.lanachat.ai/v1/webhooks/wh_12/test \
  -H "Authorization: Bearer $LANACHAT_TOKEN" \
  -H "Idempotency-Key: $(uuidgen)"
```

Your server receives a `ping` event within seconds, signed like any other delivery.

### Deliveries and retry

`GET /webhooks/{id}/deliveries` lists the recent deliveries, their status and your server's answer. `POST /webhooks/{id}/deliveries/{delivery_id}/retry` sends one of them again, for example after you fixed a bug on your side.

```bash
curl -X POST https://api.lanachat.ai/v1/webhooks/wh_12/deliveries/dlv_5f21a9/retry \
  -H "Authorization: Bearer $LANACHAT_TOKEN" \
  -H "Idempotency-Key: $(uuidgen)"
```

## A delivery

```http
POST /lanachat/webhook HTTP/1.1
Host: hooks.mia-agency.com
Content-Type: application/json
LanaChat-Event: sale.completed
LanaChat-Delivery: dlv_5f21a9
LanaChat-Signature: t=1759762800,v1=5257a869e7ecebeda32affa62cdca3fa51cad7e77a0e56ff536d0ce8e108d8bd
```

```json
{
  "id": "evt_31877",
  "type": "sale.completed",
  "created_at": "2026-10-06T15:00:00Z",
  "workspace_id": "ws_7Hq2",
  "data": {
    "sale_id": "sale_8812", "fan_id": "fan_921", "creator_id": "cr_lea", "account_id": "acc_1001",
    "conversation_id": "conv_1001_88231", "stars": 300, "net_cents": 390, "sent_by": "ai", "kind": "offer"
  }
}
```

Every event has the same envelope: `id`, `type`, `created_at`, `workspace_id` and `data`. `data` carries the object the event is about, with the fields the matching API endpoint returns.

## Payload of each event

`conversation.started`: the [conversation](https://lanachat.ai/guides/api-conversations/), with the link it came from.

```json
{ "id": "evt_31801", "type": "conversation.started", "created_at": "2026-10-06T14:01:12Z", "workspace_id": "ws_7Hq2",
  "data": { "id": "conv_1001_88231", "fan_id": "fan_921", "creator_id": "cr_lea", "account_id": "acc_1001", "state": "ai", "source_link_id": "lnk_3" } }
```

`conversation.needs_review`: the conversation and its new status.

```json
{ "id": "evt_31840", "type": "conversation.needs_review", "created_at": "2026-10-06T14:20:00Z", "workspace_id": "ws_7Hq2",
  "data": { "id": "conv_1001_88231", "creator_id": "cr_lea", "account_id": "acc_1001", "state": "off", "status": { "tag": "review", "reason": "The fan asked for a refund." } } }
```

`conversation.taken_over`: who holds the conversation now (`state` is `human` when a person takes it, `ai` when it is given back).

```json
{ "id": "evt_31852", "type": "conversation.taken_over", "created_at": "2026-10-06T14:04:00Z", "workspace_id": "ws_7Hq2",
  "data": { "id": "conv_1001_88231", "state": "human", "taken_by": "tok_31", "taken_at": "2026-10-06T14:04:00Z" } }
```

`message.received`: the fan's message.

```json
{ "id": "evt_31860", "type": "message.received", "created_at": "2026-10-06T14:02:10Z", "workspace_id": "ws_7Hq2",
  "data": { "id": "msg_77119", "conversation_id": "conv_1001_88231", "from": "fan", "text": "show me more", "at": "2026-10-06T14:02:10Z" } }
```

`sale.completed` and `sale.refunded`: the sale, as in the delivery above. A refund carries the same `sale_id` as the sale it cancels.

`media.ready`: the [media](https://lanachat.ai/guides/api-vault/), `status` `ready` or `failed`.

```json
{ "id": "evt_31870", "type": "media.ready", "created_at": "2026-10-06T14:22:05Z", "workspace_id": "ws_7Hq2",
  "data": { "id": "med_5521", "creator_id": "cr_lea", "type": "photo", "status": "ready", "folder_id": "vf_3" } }
```

`account.health_changed`: the [Telegram account](https://lanachat.ai/guides/api-telegram-accounts/) and its new `health`.

```json
{ "id": "evt_31881", "type": "account.health_changed", "created_at": "2026-10-06T15:10:00Z", "workspace_id": "ws_7Hq2",
  "data": { "id": "acc_1004", "creator_id": "cr_lea", "username": "lea_backup", "health": "expired" } }
```

`pool.saturated`: the [pool](https://lanachat.ai/guides/api-telegram-accounts/) and its load.

```json
{ "id": "evt_31890", "type": "pool.saturated", "created_at": "2026-10-06T21:00:00Z", "workspace_id": "ws_7Hq2",
  "data": { "id": "pool_lea_fr_instagram", "creator_id": "cr_lea", "sent_last_hour": 381, "capacity_per_hour": 400, "status": "saturated" } }
```

`brain.published`: the [brain](https://lanachat.ai/guides/api-ai-brains/) and its new version.

```json
{ "id": "evt_31901", "type": "brain.published", "created_at": "2026-10-06T14:20:03Z", "workspace_id": "ws_7Hq2",
  "data": { "id": "br_lea_main", "version": 13, "published_at": "2026-10-06T14:20:03Z" } }
```

`billing.low_balance`: your [balance](https://lanachat.ai/guides/api-billing/).

```json
{ "id": "evt_31910", "type": "billing.low_balance", "created_at": "2026-10-06T08:00:00Z", "workspace_id": "ws_7Hq2",
  "data": { "balance_cents": 2900 } }
```

`ping`: sent by **Test**; `data` is empty.

```json
{ "id": "evt_31920", "type": "ping", "created_at": "2026-10-06T16:00:00Z", "workspace_id": "ws_7Hq2", "data": {} }
```

## Check the signature

`LanaChat-Signature` holds a timestamp `t` and `v1`, the HMAC-SHA256 of `t + "." + raw body` with your endpoint's signing secret, in hex.

In Node (any framework that gives you the raw body):

```js
import { createHmac, timingSafeEqual } from 'node:crypto';

// rawBody: the request body as received (Buffer or string), before any JSON parsing
export function verify(rawBody, header, secret) {
  const parts = (header || '').split(',').map((p) => p.trim().split('='));
  const t = parts.find(([k]) => k === 't')?.[1];
  const signatures = parts.filter(([k]) => k === 'v1').map(([, v]) => v);   // two during a secret rotation
  if (!t || !(Math.abs(Date.now() / 1000 - Number(t)) < 300)) return false;  // older than 5 minutes: refuse
  const want = createHmac('sha256', secret).update(t + '.').update(rawBody).digest('hex');
  return signatures.some((v) => v.length === want.length && timingSafeEqual(Buffer.from(v), Buffer.from(want)));
}
```

A complete receiver with Express:

```js
import express from 'express';
import { verify } from './verify.js';

const app = express();
const seen = new Set();   // use your database in production

app.post('/lanachat/webhook', express.raw({ type: 'application/json' }), (req, res) => {
  if (!verify(req.body, req.get('LanaChat-Signature'), process.env.LANACHAT_WEBHOOK_SECRET)) return res.sendStatus(400);
  const event = JSON.parse(req.body);
  res.sendStatus(200);                       // answer fast, work after
  if (seen.has(event.id)) return;            // the same event can arrive twice
  seen.add(event.id);
  if (event.type === 'sale.completed') console.log('New sale', event.data.stars, 'Stars for', event.data.creator_id);
});

app.listen(3000);
```

In Python, with Flask:

```python
import hashlib
import hmac
import json
import os
import time

from flask import Flask, abort, request

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

def verify(raw_body: bytes, header: str) -> bool:
    parts = [p.strip().split("=", 1) for p in (header or "").split(",") if "=" in p]
    t = next((v for k, v in parts if k == "t"), None)
    signatures = [v for k, v in parts if k == "v1"]  # two during a secret rotation
    if not t or abs(time.time() - int(t)) >= 300:    # older than 5 minutes: refuse
        return False
    want = hmac.new(SECRET, t.encode() + b"." + raw_body, hashlib.sha256).hexdigest()
    return any(hmac.compare_digest(want, v) for v in signatures)

@app.post("/lanachat/webhook")
def webhook():
    raw = request.get_data()
    if not verify(raw, request.headers.get("LanaChat-Signature")):
        abort(400)
    event = json.loads(raw)
    if event["type"] == "sale.completed":
        print("New sale", event["data"]["stars"], "Stars for", event["data"]["creator_id"])
    return "", 200
```

- Compute it on the raw body, before any JSON parsing.
- Refuse a timestamp older than 5 minutes: it stops a replay.
- During a secret rotation, deliveries carry two `v1` values; accept either.

## Retries

- Answer any `2xx` within 10 seconds. Anything else, or no answer, is a failure.
- A failed delivery is retried 8 times over about 24 hours (1 min, 5 min, 30 min, 2 h, 5 h, 10 h, 14 h, 24 h).
- The same event can arrive twice: use `id` to ignore duplicates. Order is not guaranteed: use `created_at`.
- After 3 days of failures the endpoint is paused and the owner gets an e-mail; resume it with `PATCH /webhooks/{id}`.

## Related

- [LanaChat API: quick start, authentication and errors](https://lanachat.ai/guides/api-overview/)
- [API quick recipes: copy, paste, run](https://lanachat.ai/guides/api-recipes/)
- [API: fans, conversations and messages](https://lanachat.ai/guides/api-conversations/)
