# API: webhooks, eventos y firmas

_API · 7 min de lectura · Actualizado 2026-10-22 · https://lanachat.ai/guides/es/api-webhooks/_

Un **webhook** envía un `POST` HTTPS a tu servidor cuando ocurre algo en el espacio de trabajo: una nueva conversación, una venta, un medio listo, una cuenta que perdió conexión. Tú eliges los eventos; LanaChat firma cada entrega para que puedas verificar que vino de nosotros, y reintenta cuando tu servidor no responde.

## Endpoints

| Método | Ruta | Descripción | Permiso | Estado |
|---|---|---|---|---|
| GET | `/webhooks` | Lista de endpoints webhook | `owner` | Planned |
| POST | `/webhooks` | Añadir un endpoint: URL y eventos (el secreto de firma se muestra una vez) | `owner` | Planned |
| GET | `/webhooks/{id}` | Un endpoint y su tasa de entrega en 7 días | `owner` | Planned |
| PATCH | `/webhooks/{id}` | Cambiar su URL o eventos, pausar o reanudar | `owner` | Planned |
| DELETE | `/webhooks/{id}` | Eliminar un endpoint | `owner` | Planned |
| POST | `/webhooks/{id}/rotate-secret` | Nuevo secreto de firma; el antiguo funciona 24 horas más | `owner` | Planned |
| POST | `/webhooks/{id}/test` | Enviar un evento `ping` ahora | `owner` | Planned |
| GET | `/webhooks/{id}/deliveries` | Entregas recientes, su estado y respuesta | `owner` | Planned |
| POST | `/webhooks/{id}/deliveries/{delivery_id}/retry` | Reenviar una entrega | `owner` | Planned |

## Eventos

| Evento | Se envía cuando | Permiso que necesita la data |
|---|---|---|
| `conversation.started` | Un fan escribe por primera vez (con `source_link_id` cuando se conoce) | `can_fan_read` |
| `conversation.needs_review` | Una conversación obtiene estado de Revisión o Seguridad | `can_fan_read` |
| `conversation.taken_over` | Una persona toma o devuelve una conversación | `can_fan_read` |
| `message.received` | Un fan envía un mensaje | `can_fan_read` |
| `sale.completed` | Una compra verificada (Stars o enlace de pago) | `can_sales_read` |
| `sale.refunded` | Se confirma un reembolso | `can_sales_read` |
| `media.ready` | Un medio subido está procesado o falló | `can_setup` |
| `account.health_changed` | Una cuenta cambia a conectado, pendiente o expirado | `can_setup` |
| `pool.saturated` | Un pool alcanza 95% de su capacidad horaria o el límite del espacio | `can_tracking` |
| `brain.published` | Un borrador de brain se publica | `can_engine` |
| `billing.low_balance` | El saldo baja del monto para los próximos 7 días de licencias | `owner` |
| `ping` | Pulsaste Test | ninguno |

Un endpoint recibe un evento solo si el token que lo creó tiene el permiso que necesita la data.

## El objeto endpoint webhook

```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"
}
```

| Campo | Tipo | Descripción |
|---|---|---|
| `id` | string | El endpoint |
| `url` | string | Tu URL HTTPS |
| `events` | array de strings | Los eventos que recibe (ver tabla arriba) |
| `status` | string | `active` o `paused` (por ti, o tras 3 días de fallos) |
| `delivery_rate_7d` | number | Proporción de entregas respondidas con `2xx` en 7 días, de 0 a 1 |
| `created_at` | string | ISO 8601, UTC |

## Gestionar endpoints

Todas estas llamadas requieren un token **owner**.

### Añadir un endpoint

`POST /webhooks` · `owner`

| Parámetro | Tipo | Requerido | Descripción |
|---|---|---|---|
| `url` | string | Sí | Una URL HTTPS de tu servidor |
| `events` | array de strings | Sí | Los eventos a recibir |

```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"]}'
```

La respuesta es el endpoint (`201`) y su **signing secret**, mostrado solo en esta respuesta: guárdalo de inmediato, junto a tu token. Un nombre de evento desconocido responde `400`.

### Listar, leer, cambiar y eliminar

| Llamada | Qué hace |
|---|---|
| `GET /webhooks` | Todos los endpoints del espacio de trabajo |
| `GET /webhooks/{id}` | Un endpoint y su tasa de entrega en 7 días |
| `PATCH /webhooks/{id}` | Cambiar `url` o `events`; pausar o reanudar con `status` |
| `DELETE /webhooks/{id}` | Eliminarlo; no se envía nada más |

```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"}'
```

### Rotar el secreto

`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)"
```

La respuesta lleva el nuevo secreto, una vez. El antiguo sigue funcionando 24 horas, para que puedas desplegar el nuevo sin perder entregas.

### Enviar una prueba

`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)"
```

Tu servidor recibe un evento `ping` en segundos, firmado como cualquier otra entrega.

### Entregas y reintentos

`GET /webhooks/{id}/deliveries` lista las entregas recientes, su estado y la respuesta de tu servidor. `POST /webhooks/{id}/deliveries/{delivery_id}/retry` reenvía una entrega, por ejemplo tras corregir un error.

```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)"
```

## Una entrega

```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"
  }
}
```

Cada evento tiene el mismo sobre: `id`, `type`, `created_at`, `workspace_id` y `data`. `data` lleva el objeto del evento, con los campos que devuelve el endpoint API correspondiente.

## Payload de cada evento

`conversation.started`: la [conversación](https://lanachat.ai/guides/es/api-conversations/), con el enlace de donde vino.

```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`: la conversación y su nuevo estado.

```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`: quién tiene la conversación ahora (`state` es `human` cuando una persona la toma, `ai` cuando se devuelve).

```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`: el mensaje del fan.

```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` y `sale.refunded`: la venta, como en la entrega arriba. Un reembolso lleva el mismo `sale_id` que la venta que cancela.

`media.ready`: el [medio](https://lanachat.ai/guides/es/api-vault/), `status` `ready` o `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`: la [cuenta de Telegram](https://lanachat.ai/guides/es/api-telegram-accounts/) y su nuevo `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`: el [pool](https://lanachat.ai/guides/es/api-telegram-accounts/) y su carga.

```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`: el [brain](https://lanachat.ai/guides/es/api-ai-brains/) y su nueva versión.

```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`: tu [saldo](https://lanachat.ai/guides/es/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`: enviado por **Test**; `data` está vacío.

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

## Verificar la firma

`LanaChat-Signature` contiene una marca de tiempo `t` y `v1`, el HMAC-SHA256 de `t + "." + raw body` con el secreto de firma de tu endpoint, en hexadecimal.

En Node (cualquier framework que te dé el 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)));
}
```

Un receptor completo con 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);
```

En Python, con 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
```

- Calcula la firma sobre el cuerpo raw, antes de parsear JSON.
- Rechaza una marca de tiempo mayor a 5 minutos: evita replays.
- Durante rotación de secreto, las entregas llevan dos valores `v1`; acepta cualquiera.

## Reintentos

- Responde cualquier `2xx` en 10 segundos. Cualquier otra cosa, o sin respuesta, es fallo.
- Una entrega fallida se reintenta 8 veces en unas 24 horas (1 min, 5 min, 30 min, 2 h, 5 h, 10 h, 14 h, 24 h).
- El mismo evento puede llegar dos veces: usa `id` para ignorar duplicados. El orden no está garantizado: usa `created_at`.
- Tras 3 días de fallos el endpoint se pausa y el owner recibe un e-mail; reanúdalo con `PATCH /webhooks/{id}`.

## Artículos relacionados

- [API de LanaChat: inicio rápido, autenticación y errores](https://lanachat.ai/guides/es/api-overview/)
- [Recetas rápidas de API: copiar, pegar, ejecutar](https://lanachat.ai/guides/es/api-recipes/)
- [API: fans, conversations and messages](https://lanachat.ai/guides/es/api-conversations/)
