# API: webhook-uri, evenimente și semnături

_API · 7 min de citit · Actualizat 2026-10-22 · https://lanachat.ai/guides/ro/api-webhooks/_

Un **webhook** trimite un `POST` HTTPS către serverul tău când se întâmplă ceva în workspace: o conversație nouă, o vânzare, un media gata, un cont care și-a pierdut conexiunea. Alegi evenimentele; LanaChat semnează fiecare livrare ca să poți verifica că vine de la noi și reîncearcă când serverul tău nu răspunde.

## Endpoints

| Method | Path | Descriere | Permisiune | Stare |
|---|---|---|---|---|
| GET | `/webhooks` | Listează endpoint-urile webhook | `owner` | Planned |
| POST | `/webhooks` | Adaugă un endpoint: URL și evenimente (secretul de semnare se arată o singură dată) | `owner` | Planned |
| GET | `/webhooks/{id}` | Un endpoint și rata lui de livrare pe 7 zile | `owner` | Planned |
| PATCH | `/webhooks/{id}` | Schimbă URL-ul sau evenimentele, pune pe pauză sau reia | `owner` | Planned |
| DELETE | `/webhooks/{id}` | Șterge un endpoint | `owner` | Planned |
| POST | `/webhooks/{id}/rotate-secret` | Secret nou de semnare; cel vechi funcționează încă 24 de ore | `owner` | Planned |
| POST | `/webhooks/{id}/test` | Trimite acum un eveniment `ping` | `owner` | Planned |
| GET | `/webhooks/{id}/deliveries` | Livrările recente, starea lor și răspunsul serverului tău | `owner` | Planned |
| POST | `/webhooks/{id}/deliveries/{delivery_id}/retry` | Retrimite o livrare | `owner` | Planned |

## Evenimente

| Eveniment | Se trimite când | Permisiunea necesară datelor |
|---|---|---|
| `conversation.started` | Un fan scrie prima dată (cu `source_link_id` când e cunoscut) | `can_fan_read` |
| `conversation.needs_review` | O conversație primește status Review sau Safety hold | `can_fan_read` |
| `conversation.taken_over` | O persoană preia o conversație sau o dă înapoi | `can_fan_read` |
| `message.received` | Un fan trimite un mesaj | `can_fan_read` |
| `sale.completed` | O achiziție verificată (Stars sau link de plată) | `can_sales_read` |
| `sale.refunded` | O rambursare este confirmată | `can_sales_read` |
| `media.ready` | Un media încărcat este procesat sau a eșuat | `can_setup` |
| `account.health_changed` | Un cont devine conectat, în așteptare sau expirat | `can_setup` |
| `pool.saturated` | Un pool atinge 95% din capacitatea orară sau limita workspace-ului | `can_tracking` |
| `brain.published` | Un draft de brain este publicat | `can_engine` |
| `billing.low_balance` | Soldul scade sub suma pentru următoarele 7 zile de licențe | `owner` |
| `ping` | Ai apăsat Test | niciuna |

Un endpoint primește un eveniment doar dacă tokenul care l-a creat are permisiunea necesară datelor.

## Obiectul endpoint-ului 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"
}
```

| Câmp | Tip | Descriere |
|---|---|---|
| `id` | string | Endpoint-ul |
| `url` | string | URL-ul tău HTTPS |
| `events` | array de stringuri | Evenimentele pe care le primește (vezi tabelul de mai sus) |
| `status` | string | `active` sau `paused` (de tine sau după 3 zile de eșecuri) |
| `delivery_rate_7d` | number | Proporția livrărilor răspunse cu `2xx` în 7 zile, între 0 și 1 |
| `created_at` | string | ISO 8601, UTC |

## Gestionarea endpoint-urilor

Toate aceste apeluri necesită un token **owner**.

### Adaugă un endpoint

`POST /webhooks` · `owner`

| Parametru | Tip | Obligatoriu | Descriere |
|---|---|---|---|
| `url` | string | Da | Un URL HTTPS al serverului tău |
| `events` | array de stringuri | Da | Evenimentele pe care vrei să le primești |

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

Răspunsul este endpoint-ul (`201`) și **secretul de semnare**, afișat doar acum: salvează-l imediat, lângă tokenul tău. Un nume de eveniment necunoscut răspunde cu `400`.

### Listează, citește, schimbă și șterge

| Apel | Ce face |
|---|---|
| `GET /webhooks` | Toate endpoint-urile workspace-ului |
| `GET /webhooks/{id}` | Un endpoint și rata lui de livrare pe 7 zile |
| `PATCH /webhooks/{id}` | Schimbă `url` sau `events`; pune pe pauză sau reia cu `status` |
| `DELETE /webhooks/{id}` | Șterge-l; nu se mai trimit date |

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

### Rotirea secretului

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

Răspunsul conține secretul nou, o singură dată. Cel vechi funcționează încă 24 de ore, ca să poți implementa noul secret fără să pierzi livrări.

### Trimite un 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)"
```

Serverul tău primește un eveniment `ping` în câteva secunde, semnat ca orice altă livrare.

### Livrări și reîncercări

`GET /webhooks/{id}/deliveries` listează livrările recente, starea lor și răspunsul serverului tău. `POST /webhooks/{id}/deliveries/{delivery_id}/retry` retrimite o livrare, de exemplu după ce ai rezolvat o problemă la tine.

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

## O livrare

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

Fiecare eveniment are aceeași structură: `id`, `type`, `created_at`, `workspace_id` și `data`. `data` conține obiectul despre care este evenimentul, cu câmpurile pe care le returnează endpoint-ul API corespunzător.

## Payload-ul fiecărui eveniment

`conversation.started`: [conversația](https://lanachat.ai/guides/ro/api-conversations/), cu linkul de unde a venit.

```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`: conversația și noul ei 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`: cine deține acum conversația (`state` este `human` când o preia o persoană, `ai` când este dată înapoi).

```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`: mesajul fanului.

```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` și `sale.refunded`: vânzarea, ca în exemplul de mai sus. O rambursare are același `sale_id` ca vânzarea pe care o anulează.

`media.ready`: [media](https://lanachat.ai/guides/ro/api-vault/), `status` `ready` sau `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`: [contul Telegram](https://lanachat.ai/guides/ro/api-telegram-accounts/) și noua lui `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`: [pool-ul](https://lanachat.ai/guides/ro/api-telegram-accounts/) și încărcarea lui.

```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`: [brain-ul](https://lanachat.ai/guides/ro/api-ai-brains/) și noua lui versiune.

```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`: [soldul tău](https://lanachat.ai/guides/ro/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`: trimis de **Test**; `data` este gol.

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

## Verifică semnătura

`LanaChat-Signature` conține un timestamp `t` și `v1`, HMAC-SHA256 al lui `t + "." + raw body` cu secretul endpoint-ului tău, în hex.

În Node (orice framework care îți dă 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 complet cu 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);
```

În Python, cu 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
```

- Calculează semnătura pe raw body, înainte de orice parsare JSON.
- Refuză un timestamp mai vechi de 5 minute: previne replay-ul.
- În timpul rotației secretului, livrările au două valori `v1`; acceptă oricare.

## Reîncercări

- Răspunde cu orice `2xx` în 10 secunde. Orice altceva sau lipsa răspunsului e eșec.
- O livrare eșuată se reîncearcă de 8 ori în circa 24 de ore (1 min, 5 min, 30 min, 2 h, 5 h, 10 h, 14 h, 24 h).
- Același eveniment poate veni de două ori: folosește `id` ca să ignori duplicatele. Ordinea nu e garantată: folosește `created_at`.
- După 3 zile de eșecuri endpoint-ul se pune pe pauză și proprietarul primește un e-mail; reia-l cu `PATCH /webhooks/{id}`.

## Articole conexe

- [API LanaChat: început rapid, autentificare și erori](https://lanachat.ai/guides/ro/api-overview/)
- [Rețete rapide API: copiază, lipește, rulează](https://lanachat.ai/guides/ro/api-recipes/)
- [API: fani, conversații și mesaje](https://lanachat.ai/guides/ro/api-conversations/)
