API: webhooks, eventos e assinaturas
Um webhook envia um POST HTTPS para seu servidor quando algo acontece no workspace: uma nova conversa, uma venda, uma mídia pronta, uma conta que perdeu a conexão. Você escolhe os eventos; LanaChat assina cada entrega para você verificar que veio da gente, e tenta novamente quando seu servidor não responde.
Endpoints #
| Método | Caminho | Descrição | Permissão | Status |
|---|---|---|---|---|
| GET | /webhooks | Lista endpoints de webhook | owner | Planned |
| POST | /webhooks | Adiciona um endpoint: URL e eventos (o segredo de assinatura é mostrado uma vez) | owner | Planned |
| GET | /webhooks/{id} | Um endpoint e sua taxa de entrega nos últimos 7 dias | owner | Planned |
| PATCH | /webhooks/{id} | Altera URL ou eventos, pausa ou retoma | owner | Planned |
| DELETE | /webhooks/{id} | Remove um endpoint | owner | Planned |
| POST | /webhooks/{id}/rotate-secret | Novo segredo de assinatura; o antigo funciona por mais 24 horas | owner | Planned |
| POST | /webhooks/{id}/test | Envia um evento ping agora | owner | Planned |
| GET | /webhooks/{id}/deliveries | Entregas recentes, status e resposta | owner | Planned |
| POST | /webhooks/{id}/deliveries/{delivery_id}/retry | Reenvia uma entrega | owner | Planned |
Eventos #
| Evento | Enviado quando | Permissão necessária para os dados |
|---|---|---|
conversation.started | Um fã escreve pela primeira vez (com source_link_id quando conhecido) | can_fan_read |
conversation.needs_review | Uma conversa recebe status de Revisão ou Segurança | can_fan_read |
conversation.taken_over | Uma pessoa assume ou devolve uma conversa | can_fan_read |
message.received | Um fã envia uma mensagem | can_fan_read |
sale.completed | Uma compra verificada (Stars ou link de pagamento) | can_sales_read |
sale.refunded | Um reembolso é confirmado | can_sales_read |
media.ready | Uma mídia enviada foi processada ou falhou | can_setup |
account.health_changed | Uma conta fica conectada, pendente ou expirada | can_setup |
pool.saturated | Um pool alcança 95% da capacidade horária ou o limite do workspace | can_tracking |
brain.published | Um rascunho de brain é publicado | can_engine |
billing.low_balance | O saldo cai abaixo do valor dos próximos 7 dias de licenças | owner |
ping | Você apertou Test | nenhuma |
Um endpoint recebe um evento somente se o token que o criou tem a permissão que os dados exigem.
O objeto endpoint do webhook #
{
"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 | Descrição |
|---|---|---|
id | string | O endpoint |
url | string | Sua URL HTTPS |
events | array de strings | Os eventos que recebe (veja a tabela acima) |
status | string | active ou paused (por você, ou após 3 dias de falhas) |
delivery_rate_7d | number | Proporção de entregas respondidas com 2xx nos últimos 7 dias, de 0 a 1 |
created_at | string | ISO 8601, UTC |
Gerenciar endpoints #
Todas essas chamadas precisam de um token owner.
Adicionar um endpoint #
POST /webhooks · owner
| Parâmetro | Tipo | Obrigatório | Descrição |
|---|---|---|---|
url | string | Sim | Uma URL HTTPS do seu servidor |
events | array de strings | Sim | Os eventos a receber |
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"]}'
A resposta é o endpoint (201) e seu signing secret, mostrado só nesta resposta: guarde-o imediatamente, junto do seu token. Um nome de evento desconhecido responde 400.
Listar, ler, alterar e remover #
| Chamada | O que faz |
|---|---|
GET /webhooks | Todos os endpoints do workspace |
GET /webhooks/{id} | Um endpoint e sua taxa de entrega nos últimos 7 dias |
PATCH /webhooks/{id} | Altera url ou events; pausa ou retoma com status |
DELETE /webhooks/{id} | Remove; nada mais é enviado |
curl -X PATCH https://api.lanachat.ai/v1/webhooks/wh_12 \
-H "Authorization: Bearer $LANACHAT_TOKEN" \
-H "Content-Type: application/json" \
-d '{"status": "active"}'
Rotacionar o segredo #
POST /webhooks/{id}/rotate-secret · owner
curl -X POST https://api.lanachat.ai/v1/webhooks/wh_12/rotate-secret \
-H "Authorization: Bearer $LANACHAT_TOKEN" \
-H "Idempotency-Key: $(uuidgen)"
A resposta traz o novo segredo, uma vez. O antigo continua funcionando por 24 horas, para você implantar o novo sem perder entregas.
Enviar um teste #
POST /webhooks/{id}/test · owner
curl -X POST https://api.lanachat.ai/v1/webhooks/wh_12/test \
-H "Authorization: Bearer $LANACHAT_TOKEN" \
-H "Idempotency-Key: $(uuidgen)"
Seu servidor recebe um evento ping em segundos, assinado como qualquer outra entrega.
Entregas e reenvio #
GET /webhooks/{id}/deliveries lista as entregas recentes, seu status e a resposta do seu servidor. POST /webhooks/{id}/deliveries/{delivery_id}/retry reenvia uma delas, por exemplo após corrigir um bug do seu lado.
curl -X POST https://api.lanachat.ai/v1/webhooks/wh_12/deliveries/dlv_5f21a9/retry \
-H "Authorization: Bearer $LANACHAT_TOKEN" \
-H "Idempotency-Key: $(uuidgen)"
Uma entrega #
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
{
"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"
}
}
Todo evento tem o mesmo envelope: id, type, created_at, workspace_id e data. data carrega o objeto do evento, com os campos que o endpoint API correspondente retorna.
Payload de cada evento #
conversation.started: a conversa, com o link de origem.
{ "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: a conversa e seu novo status.
{ "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: quem está com a conversa agora (state é human quando uma pessoa assume, ai quando devolve).
{ "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: a mensagem do fã.
{ "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 e sale.refunded: a venda, como na entrega acima. Um reembolso tem o mesmo sale_id da venda que cancela.
media.ready: a mídia, status ready ou failed.
{ "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: a conta Telegram e seu novo health.
{ "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: o pool e sua carga.
{ "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: o brain e sua nova versão.
{ "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: seu saldo.
{ "id": "evt_31910", "type": "billing.low_balance", "created_at": "2026-10-06T08:00:00Z", "workspace_id": "ws_7Hq2",
"data": { "balance_cents": 2900 } }
ping: enviado pelo Test; data está vazio.
{ "id": "evt_31920", "type": "ping", "created_at": "2026-10-06T16:00:00Z", "workspace_id": "ws_7Hq2", "data": {} }
Verificar a assinatura #
LanaChat-Signature contém um timestamp t e v1, o HMAC-SHA256 de t + "." + raw body com o segredo de assinatura do seu endpoint, em hexadecimal.
Em Node (qualquer framework que forneça o raw body):
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)));
}
Um receptor completo com Express:
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);
Em Python, com Flask:
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
- Calcule sobre o raw body, antes de qualquer parsing JSON.
- Recuse um timestamp mais velho que 5 minutos: evita replay.
- Durante rotação de segredo, entregas trazem dois valores
v1; aceite qualquer um.
Retentativas #
- Responda qualquer
2xxem até 10 segundos. Qualquer outra coisa, ou sem resposta, é falha. - Uma entrega falhada é tentada 8 vezes em cerca de 24 horas (1 min, 5 min, 30 min, 2 h, 5 h, 10 h, 14 h, 24 h).
- O mesmo evento pode chegar duas vezes: use
idpara ignorar duplicatas. A ordem não é garantida: usecreated_at. - Após 3 dias de falhas o endpoint é pausado e o owner recebe um e-mail; retome com
PATCH /webhooks/{id}.