Pular para o conteúdo
Menu

Buscar no site

Digite para buscar em guias, blog, API e produto.

↑ ↓ para navegar · Enter para abrir · Esc para fechar

Referência da API

API

Webhooks

Avise o seu sistema, na hora e assinado, quando algo acontece no seu agente

Ver como Markdown

Um webhook é uma URL do seu sistema para a qual o TBit faz um POST assinado toda vez que algo acontece no seu agente: uma consulta é agendada, reagendada ou cancelada, um pedido é pago ou a IA passa uma conversa para a equipe. Assim a sua agenda, o seu ERP ou o seu CRM ficam sabendo sem precisar perguntar.

Os webhooks são criados aqui com a API, no app (Plugins › Desenvolvimento › Webhooks) ou pelo MCP com manage_webhooks. As três portas usam os mesmos nomes: url, events, description e status. Até 10 por agente.

MétodoRotaDescrição
GET/v1/webhooksLista os webhooks, cada um com as suas últimas 5 entregas
POST/v1/webhooksCria um webhook; devolve o segredo uma única vez
GET/v1/webhooks/{id}Um webhook com as suas últimas entregas (?limit= até 100)
PATCH/v1/webhooks/{id}Altera url, events, description ou status
DELETE/v1/webhooks/{id}Apaga o webhook
POST/v1/webhooks/{id}/testEnvia já um evento webhook.test assinado e devolve o que o seu sistema respondeu

Criar um webhook

Campos: url (https e pública: não se aceitam IPs privados, localhost nem endereços internos), events (pelo menos um da tabela de eventos) e description (opcional, até 200 caracteres). A resposta traz secret: guarde-o, é a única vez que sai e com ele você verifica cada entrega.

POST/v1/webhooks
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"
  }'
const response = await fetch('https://rest-api.tbit.app/v1/webhooks', {
  method: 'POST',
  headers: {
    'X-API-Key': process.env.TBIT_API_KEY,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    url: 'https://tu-sistema.com/webhooks/tbit',
    events: [
      'appointment.created',
      'appointment.cancelled',
    ],
    description: 'Agenda del consultorio',
  }),
});
const data = await response.json();
import axios from 'axios';

const { data } = await axios.post(
  'https://rest-api.tbit.app/v1/webhooks',
  {
    url: 'https://tu-sistema.com/webhooks/tbit',
    events: [
      'appointment.created',
      'appointment.cancelled',
    ],
    description: 'Agenda del consultorio',
  },
  {
    headers: {
      'X-API-Key': process.env.TBIT_API_KEY,
    },
  },
);
import os
import requests

response = requests.post(
    'https://rest-api.tbit.app/v1/webhooks',
    headers={'X-API-Key': os.environ['TBIT_API_KEY']},
    json={
        'url': 'https://tu-sistema.com/webhooks/tbit',
        'events': [
            'appointment.created',
            'appointment.cancelled',
        ],
        'description': 'Agenda del consultorio',
    },
)
data = response.json()
<?php
$ch = curl_init('https://rest-api.tbit.app/v1/webhooks');
curl_setopt_array($ch, [
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        'X-API-Key: ' . getenv('TBIT_API_KEY'),
        'Content-Type: application/json',
    ],
    CURLOPT_POSTFIELDS => json_encode([
        'url' => 'https://tu-sistema.com/webhooks/tbit',
        'events' => [
            'appointment.created',
            'appointment.cancelled',
        ],
        'description' => 'Agenda del consultorio',
    ]),
]);
$data = json_decode(curl_exec($ch), true);
curl_close($ch);
Resposta
{
  "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)"
  }
}

Cada webhook traz recent_deliveries: o evento, o status (delivered, pending ou failed), as tentativas, o código HTTP que o seu sistema respondeu e quanto tempo levou. As entregas são guardadas por 30 dias.

GET/v1/webhooks/6b1d2e3f4a5b6c7d8e9f0a2d
curl "https://rest-api.tbit.app/v1/webhooks/6b1d2e3f4a5b6c7d8e9f0a2d?limit=20" \
  -H "X-API-Key: $TBIT_API_KEY"
const response = await fetch('https://rest-api.tbit.app/v1/webhooks/6b1d2e3f4a5b6c7d8e9f0a2d?limit=20', {
  headers: {
    'X-API-Key': process.env.TBIT_API_KEY,
  },
});
const data = await response.json();
import axios from 'axios';

const { data } = await axios.get(
  'https://rest-api.tbit.app/v1/webhooks/6b1d2e3f4a5b6c7d8e9f0a2d?limit=20',
  {
    headers: {
      'X-API-Key': process.env.TBIT_API_KEY,
    },
  },
);
import os
import requests

response = requests.get(
    'https://rest-api.tbit.app/v1/webhooks/6b1d2e3f4a5b6c7d8e9f0a2d?limit=20',
    headers={'X-API-Key': os.environ['TBIT_API_KEY']},
)
data = response.json()
<?php
$ch = curl_init('https://rest-api.tbit.app/v1/webhooks/6b1d2e3f4a5b6c7d8e9f0a2d?limit=20');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        'X-API-Key: ' . getenv('TBIT_API_KEY'),
    ],
]);
$data = json_decode(curl_exec($ch), true);
curl_close($ch);
Resposta
{
  "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
        }
      ]
    }
  }
}

Envie só o que muda. "status": "disabled" desliga o webhook sem apagá-lo; "status": "active" o liga de novo e zera a contagem de falhas (assim se reativa um que o TBit desligou).

PATCH/v1/webhooks/6b1d2e3f4a5b6c7d8e9f0a2d
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"
  }'
const response = await fetch('https://rest-api.tbit.app/v1/webhooks/6b1d2e3f4a5b6c7d8e9f0a2d', {
  method: 'PATCH',
  headers: {
    'X-API-Key': process.env.TBIT_API_KEY,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    events: [
      'appointment.created',
      'order.paid',
    ],
    status: 'active',
  }),
});
const data = await response.json();
import axios from 'axios';

const { data } = await axios.patch(
  'https://rest-api.tbit.app/v1/webhooks/6b1d2e3f4a5b6c7d8e9f0a2d',
  {
    events: [
      'appointment.created',
      'order.paid',
    ],
    status: 'active',
  },
  {
    headers: {
      'X-API-Key': process.env.TBIT_API_KEY,
    },
  },
);
import os
import requests

response = requests.patch(
    'https://rest-api.tbit.app/v1/webhooks/6b1d2e3f4a5b6c7d8e9f0a2d',
    headers={'X-API-Key': os.environ['TBIT_API_KEY']},
    json={
        'events': [
            'appointment.created',
            'order.paid',
        ],
        'status': 'active',
    },
)
data = response.json()
<?php
$ch = curl_init('https://rest-api.tbit.app/v1/webhooks/6b1d2e3f4a5b6c7d8e9f0a2d');
curl_setopt_array($ch, [
    CURLOPT_CUSTOMREQUEST => 'PATCH',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        'X-API-Key: ' . getenv('TBIT_API_KEY'),
        'Content-Type: application/json',
    ],
    CURLOPT_POSTFIELDS => json_encode([
        'events' => [
            'appointment.created',
            'order.paid',
        ],
        'status' => 'active',
    ]),
]);
$data = json_decode(curl_exec($ch), true);
curl_close($ch);
DELETE/v1/webhooks/6b1d2e3f4a5b6c7d8e9f0a2d
curl -X DELETE "https://rest-api.tbit.app/v1/webhooks/6b1d2e3f4a5b6c7d8e9f0a2d" \
  -H "X-API-Key: $TBIT_API_KEY"
const response = await fetch('https://rest-api.tbit.app/v1/webhooks/6b1d2e3f4a5b6c7d8e9f0a2d', {
  method: 'DELETE',
  headers: {
    'X-API-Key': process.env.TBIT_API_KEY,
  },
});
const data = await response.json();
import axios from 'axios';

const { data } = await axios.delete(
  'https://rest-api.tbit.app/v1/webhooks/6b1d2e3f4a5b6c7d8e9f0a2d',
  {
    headers: {
      'X-API-Key': process.env.TBIT_API_KEY,
    },
  },
);
import os
import requests

response = requests.delete(
    'https://rest-api.tbit.app/v1/webhooks/6b1d2e3f4a5b6c7d8e9f0a2d',
    headers={'X-API-Key': os.environ['TBIT_API_KEY']},
)
data = response.json()
<?php
$ch = curl_init('https://rest-api.tbit.app/v1/webhooks/6b1d2e3f4a5b6c7d8e9f0a2d');
curl_setopt_array($ch, [
    CURLOPT_CUSTOMREQUEST => 'DELETE',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        'X-API-Key: ' . getenv('TBIT_API_KEY'),
    ],
]);
$data = json_decode(curl_exec($ch), true);
curl_close($ch);

Enviar um teste

Envia na hora um evento webhook.test assinado com o segredo do webhook, mesmo que esteja desligado e mesmo que não esteja inscrito em nada, e diz o que o seu sistema respondeu. Não conta como falha para o desligamento automático. Limite: 20 por minuto.

POST/v1/webhooks/6b1d2e3f4a5b6c7d8e9f0a2d/test
curl -X POST "https://rest-api.tbit.app/v1/webhooks/6b1d2e3f4a5b6c7d8e9f0a2d/test" \
  -H "X-API-Key: $TBIT_API_KEY"
const response = await fetch('https://rest-api.tbit.app/v1/webhooks/6b1d2e3f4a5b6c7d8e9f0a2d/test', {
  method: 'POST',
  headers: {
    'X-API-Key': process.env.TBIT_API_KEY,
  },
});
const data = await response.json();
import axios from 'axios';

const { data } = await axios.post(
  'https://rest-api.tbit.app/v1/webhooks/6b1d2e3f4a5b6c7d8e9f0a2d/test',
  {},
  {
    headers: {
      'X-API-Key': process.env.TBIT_API_KEY,
    },
  },
);
import os
import requests

response = requests.post(
    'https://rest-api.tbit.app/v1/webhooks/6b1d2e3f4a5b6c7d8e9f0a2d/test',
    headers={'X-API-Key': os.environ['TBIT_API_KEY']},
)
data = response.json()
<?php
$ch = curl_init('https://rest-api.tbit.app/v1/webhooks/6b1d2e3f4a5b6c7d8e9f0a2d/test');
curl_setopt_array($ch, [
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        'X-API-Key: ' . getenv('TBIT_API_KEY'),
    ],
]);
$data = json_decode(curl_exec($ch), true);
curl_close($ch);
Resposta
{
  "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."
  }
}
EventoQuando sai
appointment.createdUm agendamento foi criado (a IA, a equipe no app, o MCP ou a API).
appointment.rescheduledUm agendamento mudou de data ou hora. Cada mudança é um evento.
appointment.cancelledUm agendamento foi cancelado (também se o apagarem do Google Calendar conectado).
order.paidUm pedido ficou pago.
escalation.createdA IA passou uma conversa para a equipe (escalonamento).
webhook.testSó com «Enviar teste». Não se inscreve.

As reservas de recursos que se alugam (quartos, salões, veículos) ainda não saem como appointment.*. O evento de contato novo chega em uma próxima versão.

Todas as entregas têm a mesma forma: id (único por evento: use-o para não processar duas vezes), type, created_at (ISO 8601, UTC), agent_id e data, com campos planos. As datas vão em UTC; um campo sem valor chega em null.

appointment.rescheduled

Os mesmos campos, com a hora nova em start e end.

escalation.created

trigger diz quem o provocou: cliente (pediu), bot (a IA deixou nas mãos da equipe), energy_blocked (o TBit não respondeu por falta de energia) ou bot_guard (parecia um sistema automático).

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."
  }
}
HeaderValor
Content-Typeapplication/json
TBit-EventO tipo de evento, por exemplo appointment.created
TBit-DeliveryO id da entrega. É o mesmo em cada nova tentativa dessa entrega.
TBit-Signaturet=<unix>,v1=<hex>: a assinatura, veja abaixo
User-AgentTBit-Webhooks/1.0

O TBit assina cada entrega com o segredo do webhook (HMAC-SHA256), no estilo do Stripe. O header TBit-Signature traz t (a hora unix do envio) e v1 (a assinatura em hex). Para verificar:

  1. Pega o corpo CRU da requisição, os bytes exatos, sem reprocessar nem reordenar o JSON.
  2. Monta o texto <t>.<cuerpo> e calcula HMAC-SHA256 com o seu segredo (whsec_…, completo).
  3. Compara com v1 em tempo constante. Se não coincidir, responde 400 e descarta.
  4. Rejeita as que tiverem t a mais de 5 minutos da sua hora, para que ninguém reenvie uma entrega antiga.
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

Uma entrega conta como entregue quando o seu sistema responde 2xx em menos de 10 segundos. Um 3xx não é seguido (conta como falha), assim como um 4xx, um 5xx, um timeout ou um erro de rede. Se falhar, o TBit tenta de novo com esta espera:

TentativaEspera desde a anterior
21 minuto
35 minutos
430 minutos
52 horas
66 horas
724 horas

Depois da sétima tentativa a entrega fica failed. Se 20 entregas seguidas terminarem falhando, o TBit desliga o webhook (status: disabled, disabled_reason: failure_streak) e envia um e-mail aos administradores do agente. Para reativá-lo, corrija o seu sistema, verifique com POST /v1/webhooks/{id}/test e envie PATCH {"status": "active"}. Os eventos que aconteceram enquanto ele estava desligado não são enviados depois.

CódigoQuando
400 VALIDATION_ERRORURL que não é https, privada ou interna; evento desconhecido; nada para alterar.
404 NOT_FOUNDO webhook não existe neste agente.
409 LIMIT_REACHEDO agente já tem 10 webhooks.
429 RATE_LIMITEDMais de 20 testes por minuto.