# Webhooks

> أبلغ نظامك، فورًا وموقّعًا، عندما يحدث شيء في وكيلك

- الصفحة: https://tbit.app/ar/docs/api/webhooks
- عنوان URL الأساسي: `https://rest-api.tbit.app/v1`
- المصادقة: ترويسة `X-API-Key` تحمل مفتاحك في كل طلب (تقرأه الأمثلة من متغير البيئة `TBIT_API_KEY`)

## نظرة عامة

الـ webhook هو عنوان URL في نظامك يرسل إليه TBit طلب POST موقّعًا كلما حدث شيء في وكيلك: جدولة موعد أو إعادة جدولته أو إلغائه، أو دفع طلب، أو تمرير الذكاء الاصطناعي لمحادثة إلى الفريق. بهذا يعرف تقويمك أو نظام ERP أو CRM دون الحاجة إلى السؤال.

تُنشأ الـ webhooks هنا عبر الـ API، أو في التطبيق (الإضافات › التطوير › Webhooks) أو من MCP باستخدام `manage_webhooks`. تستخدم الأبواب الثلاثة الأسماء نفسها: `url`, `events`, `description` و `status`. حتى 10 لكل وكيل.

## نقاط النهاية

| الطريقة | المسار | الوصف |
| --- | --- | --- |
| `GET` | `/v1/webhooks` | يسرد الـ webhooks، كل واحد مع آخر 5 عمليات تسليم له |
| `POST` | `/v1/webhooks` | ينشئ webhook؛ يعيد السر مرة واحدة فقط |
| `GET` | `/v1/webhooks/{id}` | webhook مع آخر عمليات تسليمه (?limit= حتى 100) |
| `PATCH` | `/v1/webhooks/{id}` | يغيّر url أو events أو description أو status |
| `DELETE` | `/v1/webhooks/{id}` | يحذف الـ webhook |
| `POST` | `/v1/webhooks/{id}/test` | يرسل الآن حدث webhook.test موقّعًا ويعيد ما استجاب به نظامك |

## إنشاء webhook

الحقول: `url` (https وعام: لا تُقبل عناوين IP خاصة ولا localhost ولا عناوين داخلية)، `events` (واحد على الأقل من جدول الأحداث) و `description` (اختياري، حتى 200 حرف). تتضمن الاستجابة `secret`: احفظه، فهو المرة الوحيدة التي يظهر فيها وبه تتحقق من كل عملية تسليم.

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

الاستجابة:

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

## سرد وعرض عمليات التسليم

كل webhook يتضمن `recent_deliveries`: الحدث، والحالة (`delivered`, `pending` أو `failed`)، والمحاولات، ورمز HTTP الذي استجاب به نظامك، وكم استغرق. تُحفظ عمليات التسليم 30 يومًا.

`GET /v1/webhooks/6b1d2e3f4a5b6c7d8e9f0a2d`

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

الاستجابة:

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

## تغيير أو إيقاف أو حذف

أرسل فقط ما يتغير. `"status": "disabled"` يوقف الـ webhook دون حذفه؛ `"status": "active"` يعيد تشغيله ويصفّر عدد الإخفاقات (هكذا يُعاد تفعيل واحد أوقفه TBit).

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

## إرسال اختبار

يرسل فورًا حدث `webhook.test` موقّعًا بسر الـ webhook، حتى لو كان متوقفًا وحتى لو لم يكن مشتركًا في شيء، ويخبرك بما استجاب به نظامك. لا يُحتسب كإخفاق للإيقاف التلقائي. الحد: 20 في الدقيقة.

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

الاستجابة:

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

## الأحداث

| الحدث | متى يُرسل |
| --- | --- |
| `appointment.created` | تم جدولة موعد (بواسطة الذكاء الاصطناعي، أو الفريق في التطبيق، أو MCP، أو الـ API). |
| `appointment.rescheduled` | تغيّر تاريخ أو وقت موعد. كل تغيير هو حدث. |
| `appointment.cancelled` | تم إلغاء موعد (أيضًا إذا حذفوه من Google Calendar المتصل). |
| `order.paid` | أصبح طلب مدفوعًا. |
| `escalation.created` | حوّل الذكاء الاصطناعي محادثة إلى الفريق (تصعيد). |
| `webhook.test` | فقط مع «إرسال اختبار». لا يتم الاشتراك. |

حجوزات الموارد التي تُستأجر (غرف، قاعات، مركبات) لا تظهر بعد كـ `appointment.*`. حدث جهة الاتصال الجديدة سيصل في إصدار قادم.

## المغلّف

جميع عمليات التسليم لها الشكل نفسه: `id` (فريد لكل حدث: استخدمه لعدم المعالجة مرتين)، `type`, `created_at` (ISO 8601، UTC)، `agent_id` و `data`، بحقول مسطحة. التواريخ بتوقيت UTC؛ الحقل بلا قيمة يصل في `null`.

### appointment.rescheduled

الحقول نفسها، مع الوقت الجديد في `start` و `end`.

### escalation.created

`trigger` يحدد من تسبّب فيه: `cliente` (طلبه)، `bot` (تركه الذكاء الاصطناعي للفريق)، `energy_blocked` (لم يرد TBit بسبب نقص الطاقة) أو `bot_guard` (بدا كنظام آلي).

```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 | القيمة |
| --- | --- |
| `Content-Type` | `application/json` |
| `TBit-Event` | نوع الحدث، مثلًا `appointment.created` |
| `TBit-Delivery` | معرّف التسليم. هو نفسه في كل إعادة محاولة لذلك التسليم. |
| `TBit-Signature` | `t=<unix>,v1=<hex>`: التوقيع، انظر أدناه |
| `User-Agent` | `TBit-Webhooks/1.0` |

## التحقق من التوقيع

يوقّع TBit كل تسليم بسرّ الـ webhook (HMAC-SHA256)، على طريقة Stripe. الترويسة `TBit-Signature` تحمل `t` (وقت الإرسال بنظام يونكس) و `v1` (التوقيع بالنظام السادس عشري). للتحقق:

1. خذ جسم الطلب الخام، البايتات الدقيقة، دون إعادة تحليل أو إعادة ترتيب JSON.
2. كوّن النص `<t>.<cuerpo>` واحسب HMAC-SHA256 بسرّك (`whsec_…`، كاملًا).
3. قارن مع `v1` بزمن ثابت. إن لم يتطابق، أجب بـ 400 واتركه.
4. ارفض تلك التي تحمل `t` أبعد من 5 دقائق عن وقتك، حتى لا يعيد أحد إرسال تسليم قديم إليك.

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

## إعادة المحاولات والإيقاف التلقائي

يُعد التسليم مسلَّمًا عندما يستجيب نظامك بـ 2xx في أقل من 10 ثوانٍ. لا يُتبع 3xx (يُعد فشلًا)، وكذلك 4xx و5xx والمهلة وخطأ الشبكة. إن فشل، يعيد TBit المحاولة بهذا الانتظار:

| المحاولة | الانتظار من السابقة |
| --- | --- |
| 2 | دقيقة واحدة |
| 3 | 5 دقائق |
| 4 | 30 دقيقة |
| 5 | ساعتان |
| 6 | 6 ساعات |
| 7 | 24 ساعة |

بعد المحاولة السابعة يصبح التسليم `failed`. إذا انتهت 20 عملية تسليم متتالية بالفشل، يوقف TBit الـ webhook (`status: disabled`, `disabled_reason: failure_streak`) ويرسل بريدًا إلكترونيًا إلى مسؤولي الوكيل. لإعادة تفعيله، أصلح نظامك، وتحقق بـ `POST /v1/webhooks/{id}/test` وأرسل `PATCH {"status": "active"}`. الأحداث التي مرت أثناء إيقافه لا تُرسل بعد ذلك.

> **أفضل الممارسات**
>
> - أجب بـ 2xx بمجرد الاستلام والتحقق، وعالج على حدة: إذا تأخرت أكثر من 10 ثوانٍ، يُعد فشلًا وتُعاد المحاولة.
> - التسليم مرة على الأقل: قد يصل الحدث نفسه مرتين. أزل التكرار بـ `id`.
> - الترتيب غير مضمون: استخدم `created_at` وإن لزم، استعلم عن الحالة الحالية.

## الأخطاء

| الرمز | متى |
| --- | --- |
| `400 VALIDATION_ERROR` | URL ليس https أو خاص أو داخلي؛ حدث غير معروف؛ لا شيء لتغييره. |
| `404 NOT_FOUND` | الـ webhook غير موجود في هذا الوكيل. |
| `409 LIMIT_REACHED` | لدى الوكيل بالفعل 10 webhooks. |
| `429 RATE_LIMITED` | أكثر من 20 اختبارًا في الدقيقة. |
