# Webhook

> Avvisa il tuo sistema, all'istante e firmato, quando succede qualcosa nel tuo agente

- Pagina: https://tbit.app/it/docs/api/webhooks
- URL base: `https://rest-api.tbit.app/v1`
- Autenticazione: header `X-API-Key` con la tua chiave in ogni richiesta (gli esempi la leggono dalla variabile d'ambiente `TBIT_API_KEY`)

## Panoramica

Un webhook è un URL del tuo sistema a cui TBit fa un POST firmato ogni volta che succede qualcosa nel tuo agente: un appuntamento viene fissato, riprogrammato o annullato, un ordine viene pagato o l'IA passa una conversazione al team. Così la tua agenda, il tuo ERP o il tuo CRM lo sanno senza dover chiedere.

I webhook si creano qui con l'API, nell'app (Plugin › Sviluppo › Webhook) o dal MCP con `manage_webhooks`. Le tre porte usano gli stessi nomi: `url`, `events`, `description` e `status`. Fino a 10 per agente.

## Endpoint

| Metodo | Percorso | Descrizione |
| --- | --- | --- |
| `GET` | `/v1/webhooks` | Elenca i webhook, ognuno con le sue ultime 5 consegne |
| `POST` | `/v1/webhooks` | Crea un webhook; restituisce il segreto una sola volta |
| `GET` | `/v1/webhooks/{id}` | Un webhook con le sue ultime consegne (?limit= fino a 100) |
| `PATCH` | `/v1/webhooks/{id}` | Cambia url, events, description o status |
| `DELETE` | `/v1/webhooks/{id}` | Elimina il webhook |
| `POST` | `/v1/webhooks/{id}/test` | Invia subito un evento webhook.test firmato e restituisce cosa ha risposto il tuo sistema |

## Creare un webhook

Campi: `url` (https e pubblico: non si accettano IP privati, localhost né indirizzi interni), `events` (almeno uno dalla tabella degli eventi) e `description` (opzionale, fino a 200 caratteri). La risposta contiene `secret`: salvalo, è l'unica volta che esce e con esso verifichi ogni consegna.

`POST /v1/webhooks`

```bash
curl -X POST "https://rest-api.tbit.app/v1/webhooks" \
  -H "X-API-Key: $TBIT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://tu-sistema.com/webhooks/tbit",
    "events": [
      "appointment.created",
      "appointment.cancelled"
    ],
    "description": "Agenda del consultorio"
  }'
```

Risposta:

```json
{
  "data": {
    "webhook": {
      "webhook_id": "6b1d2e3f4a5b6c7d8e9f0a2d",
      "url": "https://tu-sistema.com/webhooks/tbit",
      "events": [
        "appointment.created",
        "appointment.cancelled"
      ],
      "description": "Agenda del consultorio",
      "status": "active",
      "disabled_reason": null,
      "failure_streak": 0,
      "last_delivery_at": null,
      "created_at": "2026-11-19T15:00:00.000Z"
    },
    "secret": "whsec_9c1f…(64 caracteres hex)"
  }
}
```

## Elencare e vedere le consegne

Ogni webhook contiene `recent_deliveries`: l'evento, lo stato (`delivered`, `pending` o `failed`), i tentativi, il codice HTTP che ha risposto il tuo sistema e quanto ci ha messo. Le consegne si conservano 30 giorni.

`GET /v1/webhooks/6b1d2e3f4a5b6c7d8e9f0a2d`

```bash
curl "https://rest-api.tbit.app/v1/webhooks/6b1d2e3f4a5b6c7d8e9f0a2d?limit=20" \
  -H "X-API-Key: $TBIT_API_KEY"
```

Risposta:

```json
{
  "data": {
    "webhook": {
      "webhook_id": "6b1d2e3f4a5b6c7d8e9f0a2d",
      "url": "https://tu-sistema.com/webhooks/tbit",
      "events": [
        "appointment.created"
      ],
      "status": "active",
      "failure_streak": 0,
      "recent_deliveries": [
        {
          "delivery_id": "6b1d2e3f4a5b6c7d8e9f0a3e",
          "event_id": "evt_3f1c9a7e2b6d4c58a0e1f2b3c4d5e6f7",
          "type": "appointment.created",
          "status": "delivered",
          "attempts": 1,
          "http_status": 200,
          "duration_ms": 184,
          "error": null,
          "created_at": "2026-11-19T15:02:11.000Z",
          "delivered_at": "2026-11-19T15:02:31.000Z",
          "next_attempt_at": null
        }
      ]
    }
  }
}
```

## Modificare, spegnere o eliminare

Invia solo ciò che cambia. `"status": "disabled"` spegne il webhook senza eliminarlo; `"status": "active"` lo riaccende e azzera il conteggio dei fallimenti (così si riattiva uno che TBit ha spento).

`PATCH /v1/webhooks/6b1d2e3f4a5b6c7d8e9f0a2d`

```bash
curl -X PATCH "https://rest-api.tbit.app/v1/webhooks/6b1d2e3f4a5b6c7d8e9f0a2d" \
  -H "X-API-Key: $TBIT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "events": [
      "appointment.created",
      "order.paid"
    ],
    "status": "active"
  }'
```

`DELETE /v1/webhooks/6b1d2e3f4a5b6c7d8e9f0a2d`

```bash
curl -X DELETE "https://rest-api.tbit.app/v1/webhooks/6b1d2e3f4a5b6c7d8e9f0a2d" \
  -H "X-API-Key: $TBIT_API_KEY"
```

## Inviare una prova

Invia all'istante un evento `webhook.test` firmato con il segreto del webhook, anche se è spento e anche se non è iscritto a nulla, e ti dice cosa ha risposto il tuo sistema. Non conta come fallimento per lo spegnimento automatico. Limite: 20 al minuto.

`POST /v1/webhooks/6b1d2e3f4a5b6c7d8e9f0a2d/test`

```bash
curl -X POST "https://rest-api.tbit.app/v1/webhooks/6b1d2e3f4a5b6c7d8e9f0a2d/test" \
  -H "X-API-Key: $TBIT_API_KEY"
```

Risposta:

```json
{
  "data": {
    "webhook_id": "6b1d2e3f4a5b6c7d8e9f0a2d",
    "delivery_id": "6b1d2e3f4a5b6c7d8e9f0a4f",
    "event_id": "evt_0a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d",
    "ok": true,
    "http_status": 200,
    "duration_ms": 212,
    "error": null,
    "response": "ok",
    "receipt": "Tu sistema respondió 200 en 212 ms. La firma viaja en TBit-Signature."
  }
}
```

## Eventi

| Evento | Quando arriva |
| --- | --- |
| `appointment.created` | È stato fissato un appuntamento (l'IA, il team nell'app, l'MCP o l'API). |
| `appointment.rescheduled` | Un appuntamento ha cambiato data o ora. Ogni modifica è un evento. |
| `appointment.cancelled` | Un appuntamento è stato annullato (anche se lo eliminano dal Google Calendar collegato). |
| `order.paid` | Un ordine è stato pagato. |
| `escalation.created` | L'IA ha passato una conversazione al team (escalation). |
| `webhook.test` | Solo con «Invia prova». Non si sottoscrive. |

Le prenotazioni di risorse a noleggio (camere, sale, veicoli) non arrivano ancora come `appointment.*`. L'evento di nuovo contatto arriverà in una prossima versione.

## L'involucro

Tutte le consegne hanno la stessa forma: `id` (unico per evento: usalo per non elaborare due volte), `type`, `created_at` (ISO 8601, UTC), `agent_id` e `data`, con campi piatti. Le date vanno in UTC; un campo senza valore arriva in `null`.

### appointment.rescheduled

Gli stessi campi, con la nuova ora in `start` e `end`.

### escalation.created

`trigger` dice chi lo ha provocato: `cliente` (lo ha richiesto), `bot` (l'IA lo ha lasciato al team), `energy_blocked` (TBit non ha risposto per mancanza di energia) o `bot_guard` (sembrava un sistema automatico).

```json
{
  "id": "evt_3f1c9a7e2b6d4c58a0e1f2b3c4d5e6f7",
  "type": "appointment.created",
  "created_at": "2026-11-19T15:02:11.000Z",
  "agent_id": "66a54f2f2281f02197cb21bd",
  "data": {
    "appointment_id": "6b1d2e3f4a5b6c7d8e9f0a1b",
    "service_id": "6af9a1b2c3d4e5f6a7b8c9d0",
    "service_name": "Limpieza dental",
    "collaborator_id": "6af9a1b2c3d4e5f6a7b8c9d1",
    "collaborator_name": "Geral Díaz",
    "start": "2026-11-21T14:00:00.000Z",
    "end": "2026-11-21T14:45:00.000Z",
    "status": "CONFIRMED",
    "contact_id": "6ac9f1e6af6d42a269f21b15",
    "contact_name": "Ana Gómez",
    "phone": "+573001234567",
    "external_id": null,
    "order_id": "6b1d2e3f4a5b6c7d8e9f0a1c"
  }
}
```

```json
{
  "id": "evt_8a2b0c4d6e8f0a1b2c3d4e5f6a7b8c9d",
  "type": "appointment.rescheduled",
  "created_at": "2026-11-19T15:02:11.000Z",
  "agent_id": "66a54f2f2281f02197cb21bd",
  "data": {
    "appointment_id": "6b1d2e3f4a5b6c7d8e9f0a1b",
    "service_id": "6af9a1b2c3d4e5f6a7b8c9d0",
    "service_name": "Limpieza dental",
    "collaborator_id": "6af9a1b2c3d4e5f6a7b8c9d1",
    "collaborator_name": "Geral Díaz",
    "start": "2026-11-22T16:00:00.000Z",
    "end": "2026-11-22T16:45:00.000Z",
    "status": "CONFIRMED",
    "contact_id": "6ac9f1e6af6d42a269f21b15",
    "contact_name": "Ana Gómez",
    "phone": "+573001234567",
    "external_id": null,
    "order_id": "6b1d2e3f4a5b6c7d8e9f0a1c"
  }
}
```

```json
{
  "id": "evt_c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5",
  "type": "appointment.cancelled",
  "created_at": "2026-11-19T15:02:11.000Z",
  "agent_id": "66a54f2f2281f02197cb21bd",
  "data": {
    "appointment_id": "6b1d2e3f4a5b6c7d8e9f0a1b",
    "service_id": "6af9a1b2c3d4e5f6a7b8c9d0",
    "service_name": "Limpieza dental",
    "collaborator_id": "6af9a1b2c3d4e5f6a7b8c9d1",
    "collaborator_name": "Geral Díaz",
    "start": "2026-11-21T14:00:00.000Z",
    "end": "2026-11-21T14:45:00.000Z",
    "status": "CANCELLED",
    "contact_id": "6ac9f1e6af6d42a269f21b15",
    "contact_name": "Ana Gómez",
    "phone": "+573001234567",
    "external_id": null,
    "order_id": "6b1d2e3f4a5b6c7d8e9f0a1c"
  }
}
```

```json
{
  "id": "evt_5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b",
  "type": "order.paid",
  "created_at": "2026-11-19T15:10:42.000Z",
  "agent_id": "66a54f2f2281f02197cb21bd",
  "data": {
    "order_id": "6b1d2e3f4a5b6c7d8e9f0a1c",
    "status": "PAID",
    "total": 180000,
    "currency": "COP",
    "payment_method": "wompi",
    "contact_id": "6ac9f1e6af6d42a269f21b15",
    "contact_name": "Ana Gómez",
    "phone": "+573001234567",
    "external_id": null
  }
}
```

```json
{
  "id": "evt_9f8e7d6c5b4a39281706f5e4d3c2b1a0",
  "type": "escalation.created",
  "created_at": "2026-11-19T15:20:03.000Z",
  "agent_id": "66a54f2f2281f02197cb21bd",
  "data": {
    "trigger": "cliente",
    "contact_id": "6ac9f1e6af6d42a269f21b15",
    "contact_name": "Ana Gómez",
    "phone": "+573001234567",
    "reason": "Pide hablar con una persona sobre un cobro",
    "message": "¿Me puede atender alguien? Me cobraron dos veces"
  }
}
```

```json
{
  "id": "evt_0a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d",
  "type": "webhook.test",
  "created_at": "2026-11-19T15:00:00.000Z",
  "agent_id": "66a54f2f2281f02197cb21bd",
  "data": {
    "webhook_id": "6b1d2e3f4a5b6c7d8e9f0a2d",
    "message": "Prueba de TBit: si ves esto, tu endpoint recibe y puede verificar la firma."
  }
}
```

## Headers

| Header | Valore |
| --- | --- |
| `Content-Type` | `application/json` |
| `TBit-Event` | Il tipo di evento, per esempio `appointment.created` |
| `TBit-Delivery` | L'id della consegna. È lo stesso in ogni nuovo tentativo di quella consegna. |
| `TBit-Signature` | `t=<unix>,v1=<hex>`: la firma, vedi sotto |
| `User-Agent` | `TBit-Webhooks/1.0` |

## Verificare la firma

TBit firma ogni consegna con il segreto del webhook (HMAC-SHA256), nello stile di Stripe. L'header `TBit-Signature` contiene `t` (l'ora unix dell'invio) e `v1` (la firma in hex). Per verificare:

1. Prendi il corpo GREZZO della richiesta, i byte esatti, senza riparsare né riordinare il JSON.
2. Componi il testo `<t>.<cuerpo>` e calcola HMAC-SHA256 con il tuo segreto (`whsec_…`, completo).
3. Confronta con `v1` in tempo costante. Se non coincide, rispondi 400 e scarta.
4. Rifiuta quelle che hanno `t` a più di 5 minuti dalla tua ora, così nessuno ti reinvia una consegna vecchia.

```javascript
import crypto from "node:crypto";
import express from "express";

const SECRET = process.env.TBIT_WEBHOOK_SECRET; // whsec_…
const TOLERANCE_SECONDS = 300;

function verify(rawBody, header) {
  const parts = Object.fromEntries(
    (header || "").split(",").map((p) => p.split("=").map((s) => s.trim())),
  );
  const t = Number(parts.t);
  const v1 = parts.v1;
  if (!t || !v1) return false;
  if (Math.abs(Date.now() / 1000 - t) > TOLERANCE_SECONDS) return false;
  const expected = crypto
    .createHmac("sha256", SECRET)
    .update(`${t}.${rawBody}`, "utf8")
    .digest("hex");
  return (
    expected.length === v1.length &&
    crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(v1))
  );
}

const app = express();
// El cuerpo CRUDO: la firma es sobre los bytes exactos, no sobre el JSON reparseado.
app.post("/webhooks/tbit", express.raw({ type: "application/json" }), (req, res) => {
  const raw = req.body.toString("utf8");
  if (!verify(raw, req.get("TBit-Signature"))) return res.sendStatus(400);
  const event = JSON.parse(raw);
  // Responde rápido y procesa aparte; deduplica por event.id.
  res.sendStatus(200);
  console.log(event.type, event.data);
});

app.listen(3000);
```

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

from flask import Flask, abort, request

SECRET = os.environ["TBIT_WEBHOOK_SECRET"]  # whsec_…
TOLERANCE_SECONDS = 300

app = Flask(__name__)


def verify(raw_body: bytes, header: str) -> bool:
    parts = dict(p.strip().split("=", 1) for p in (header or "").split(",") if "=" in p)
    try:
        t = int(parts["t"])
        v1 = parts["v1"]
    except (KeyError, ValueError):
        return False
    if abs(time.time() - t) > TOLERANCE_SECONDS:
        return False
    signed = f"{t}.".encode() + raw_body
    expected = hmac.new(SECRET.encode(), signed, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, v1)


@app.post("/webhooks/tbit")
def tbit_webhook():
    raw = request.get_data()  # los bytes exactos que firmó TBit
    if not verify(raw, request.headers.get("TBit-Signature", "")):
        abort(400)
    event = json.loads(raw)
    # Responde rápido y procesa aparte; deduplica por event["id"].
    print(event["type"], event["data"])
    return "", 200
```

## Nuovi tentativi e spegnimento automatico

Una consegna conta come consegnata quando il tuo sistema risponde 2xx in meno di 10 secondi. Un 3xx non viene seguito (conta come errore), così come un 4xx, un 5xx, un timeout o un errore di rete. Se fallisce, TBit riprova con questa attesa:

| Tentativo | Attesa dal precedente |
| --- | --- |
| 2 | 1 minuto |
| 3 | 5 minuti |
| 4 | 30 minuti |
| 5 | 2 ore |
| 6 | 6 ore |
| 7 | 24 ore |

Dopo il settimo tentativo la consegna resta `failed`. Se 20 consegne di seguito terminano fallite, TBit spegne il webhook (`status: disabled`, `disabled_reason: failure_streak`) e scrive un'email agli amministratori dell'agente. Per riattivarlo, sistema il tuo sistema, verifica con `POST /v1/webhooks/{id}/test` e invia `PATCH {"status": "active"}`. Gli eventi accaduti mentre era spento non vengono inviati dopo.

> **Buone pratiche**
>
> - Rispondi 2xx appena ricevi e verifichi, e elabora a parte: se impieghi più di 10 secondi, conta come errore e si riprova.
> - La consegna è almeno una volta: lo stesso evento può arrivare due volte. Deduplica per `id`.
> - L'ordine non è garantito: usa `created_at` e, se serve, consulta lo stato attuale.

## Errori

| Codice | Quando |
| --- | --- |
| `400 VALIDATION_ERROR` | URL che non è https, privata o interna; evento sconosciuto; niente da cambiare. |
| `404 NOT_FOUND` | Il webhook non esiste in questo agente. |
| `409 LIMIT_REACHED` | L'agente ha già 10 webhook. |
| `429 RATE_LIMITED` | Più di 20 prove al minuto. |
