API: webhook, eventi e firme
Un webhook invia un POST HTTPS al tuo server quando succede qualcosa nel workspace: una nuova conversazione, una vendita, un media pronto, un account che ha perso la connessione. Scegli tu gli eventi; LanaChat firma ogni consegna così puoi verificare che venga da noi, e ritenta quando il tuo server non risponde.
Endpoint #
| Metodo | Percorso | Descrizione | Permesso | Stato |
|---|---|---|---|---|
| GET | /webhooks | Elenca gli endpoint webhook | owner | Planned |
| POST | /webhooks | Aggiungi un endpoint: URL ed eventi (il segreto di firma è mostrato una sola volta) | owner | Planned |
| GET | /webhooks/{id} | Un endpoint e il suo tasso di consegna negli ultimi 7 giorni | owner | Planned |
| PATCH | /webhooks/{id} | Cambia URL o eventi, metti in pausa o riprendi | owner | Planned |
| DELETE | /webhooks/{id} | Rimuovi un endpoint | owner | Planned |
| POST | /webhooks/{id}/rotate-secret | Nuovo segreto di firma; il vecchio funziona ancora 24 ore | owner | Planned |
| POST | /webhooks/{id}/test | Invia ora un evento ping | owner | Planned |
| GET | /webhooks/{id}/deliveries | Consegne recenti, stato e risposta | owner | Planned |
| POST | /webhooks/{id}/deliveries/{delivery_id}/retry | Invia di nuovo una consegna | owner | Planned |
Eventi #
| Evento | Inviato quando | Permesso richiesto dai dati |
|---|---|---|
conversation.started | Un fan scrive per la prima volta (con source_link_id se noto) | can_fan_read |
conversation.needs_review | Una conversazione riceve stato Review o Safety hold | can_fan_read |
conversation.taken_over | Una persona prende in carico o restituisce una conversazione | can_fan_read |
message.received | Un fan invia un messaggio | can_fan_read |
sale.completed | Un acquisto verificato (Stars o link di pagamento) | can_sales_read |
sale.refunded | Un rimborso è confermato | can_sales_read |
media.ready | Un media caricato è processato o fallito | can_setup |
account.health_changed | Un account cambia stato: connesso, in sospeso o scaduto | can_setup |
pool.saturated | Un pool raggiunge il 95% della capacità oraria o il limite workspace | can_tracking |
brain.published | Una bozza di brain è pubblicata | can_engine |
billing.low_balance | Il saldo scende sotto l’importo delle prossime 7 giornate di licenze | owner |
ping | Hai premuto Test | nessuno |
Un endpoint riceve un evento solo se il token che lo ha creato ha il permesso richiesto dai dati.
L’oggetto endpoint 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 | Descrizione |
|---|---|---|
id | stringa | L’endpoint |
url | stringa | La tua URL HTTPS |
events | array di stringhe | Gli eventi che riceve (vedi tabella sopra) |
status | stringa | active o paused (da te, o dopo 3 giorni di errori) |
delivery_rate_7d | numero | Percentuale di consegne con risposta 2xx negli ultimi 7 giorni, da 0 a 1 |
created_at | stringa | ISO 8601, UTC |
Gestire gli endpoint #
Tutte queste chiamate richiedono un token owner.
Aggiungere un endpoint #
POST /webhooks · owner
| Parametro | Tipo | Obbligatorio | Descrizione |
|---|---|---|---|
url | stringa | Sì | Un URL HTTPS del tuo server |
events | array di stringhe | Sì | Gli eventi da ricevere |
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 risposta è l’endpoint (201) e il suo signing secret, mostrato solo in questa risposta: salvalo subito, insieme al tuo token. Un nome evento sconosciuto risponde 400.
Elencare, leggere, modificare e rimuovere #
| Chiamata | Cosa fa |
|---|---|
GET /webhooks | Tutti gli endpoint del workspace |
GET /webhooks/{id} | Un endpoint e il suo tasso di consegna negli ultimi 7 giorni |
PATCH /webhooks/{id} | Cambia url o events; metti in pausa o riprendi con status |
DELETE /webhooks/{id} | Rimuovilo; non verrà più inviato nulla |
curl -X PATCH https://api.lanachat.ai/v1/webhooks/wh_12 \
-H "Authorization: Bearer $LANACHAT_TOKEN" \
-H "Content-Type: application/json" \
-d '{"status": "active"}'
Ruotare il segreto #
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)"
La risposta contiene il nuovo segreto, una sola volta. Il vecchio funziona ancora 24 ore, così puoi aggiornare senza perdere consegne.
Inviare un test #
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)"
Il tuo server riceve un evento ping entro pochi secondi, firmato come ogni altra consegna.
Consegne e ritentativi #
GET /webhooks/{id}/deliveries elenca le consegne recenti, il loro stato e la risposta del tuo server. POST /webhooks/{id}/deliveries/{delivery_id}/retry invia di nuovo una consegna, per esempio dopo aver risolto un bug.
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 consegna #
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"
}
}
Ogni evento ha lo stesso involucro: id, type, created_at, workspace_id e data. data contiene l’oggetto a cui si riferisce l’evento, con i campi restituiti dall’endpoint API corrispondente.
Payload di ogni evento #
conversation.started: la conversazione, con il link da cui proviene.
{ "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 conversazione e il suo nuovo stato.
{ "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: chi gestisce ora la conversazione (state è human quando una persona la prende, ai quando viene restituita).
{ "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: il messaggio del fan.
{ "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: la vendita, come nella consegna sopra. Un rimborso ha lo stesso sale_id della vendita che annulla.
media.ready: il media, status ready o 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: l’account Telegram e il suo nuovo 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: il pool e il suo carico.
{ "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: il brain e la sua nuova versione.
{ "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: il tuo saldo.
{ "id": "evt_31910", "type": "billing.low_balance", "created_at": "2026-10-06T08:00:00Z", "workspace_id": "ws_7Hq2",
"data": { "balance_cents": 2900 } }
ping: inviato da Test; data è vuoto.
{ "id": "evt_31920", "type": "ping", "created_at": "2026-10-06T16:00:00Z", "workspace_id": "ws_7Hq2", "data": {} }
Verifica la firma #
LanaChat-Signature contiene un timestamp t e v1, l’HMAC-SHA256 di t + "." + raw body con il segreto di firma del tuo endpoint, in esadecimale.
In Node (qualsiasi framework che ti fornisce il 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)));
}
Un ricevitore completo con 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);
In Python, con 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
- Calcolala sul raw body, prima di qualsiasi parsing JSON.
- Rifiuta un timestamp più vecchio di 5 minuti: blocca i replay.
- Durante la rotazione del segreto, le consegne portano due valori
v1; accetta entrambi.
Ritentativi #
- Rispondi con qualsiasi
2xxentro 10 secondi. Altro o nessuna risposta è un fallimento. - Una consegna fallita viene ritentata 8 volte in circa 24 ore (1 min, 5 min, 30 min, 2 h, 5 h, 10 h, 14 h, 24 h).
- Lo stesso evento può arrivare due volte: usa
idper ignorare duplicati. L’ordine non è garantito: usacreated_at. - Dopo 3 giorni di fallimenti l’endpoint viene messo in pausa e il proprietario riceve una mail; riprendi con
PATCH /webhooks/{id}.