# AIBot Partner API v1 — 戰略夥伴對接文檔

> **適用對象**：所有 AIBot 戰略夥伴的開發團隊（本文檔為通用規格，適用於每一家夥伴）。夥伴自行向客戶收費，AIBot 按租戶方案與批發價向夥伴結算（Microsoft CSP 模式）。
> **Base URL**：`https://wtsaibot.com`（對外唯一入口）｜**線上文檔**：`https://wtsaibot.com/api`
> **版本**：v1（2026-09-13；介面深度凍結——開放建立租戶、用量報表與渠道團隊數據。知識庫（KB）與 AI 人格（prompt）設定**不經 API** 提供，由 AIBot 方為每位客戶人工服務；夥伴收集客戶資料後交由 AIBot 跟進即可）

---

## 1. 認證

所有請求須附帶 header：

```
X-Partner-Key: <PARTNER_API_KEY>
```

- Key 由 AIBot 後台生成，為 64 位十六進制字串，僅在生成或重新生成時顯示一次——請即時妥善保存（遺失後只能重新生成，舊 Key 即時失效）。
- Key 與夥伴綁定（不與租戶綁定）——所有經 API 建立的租戶自動歸入貴夥伴名下（批發結算依據）。
- 鑑權失敗一律返回 `401`（不會透露該 Key 是否曾經有效）。

## 2. 限流

每個夥伴 Key **每分鐘上限 120 個請求**（Durable Object 強一致計數）。超出上限返回 `429` 並附帶 `Retry-After: 60`。建立租戶屬低頻操作，正常整合不會觸及此上限。

## 3. 端點總覽

| 端點 | 方法 | 用途 |
|---|---|---|
| `/partner/v1/tenants` | `POST` | 建立租戶（即時可用，自動歸入貴夥伴名下） |
| `/partner/v1/tenants` | `GET` | 列出名下租戶 |
| `/partner/v1/usage?month=YYYY-MM` | `GET` | 名下租戶用量聚合（對話數；批價結算用） |
| `/partner/v1/team` | `GET` | 渠道團隊：旗下 Agent 漏斗＋最近成交單 |

---

## 4. `POST /partner/v1/tenants` — 建立租戶

### Request body（JSON）

| 欄位 | 類型 | 必填 | 說明 |
|---|---|---|---|
| `name` | string | ✅ | 客戶店名或公司名（顯示用，≤60 字） |
| `phone` | string | ✅ | 客戶聯絡電話（E.164 純數字 6-15 位，如 `85291234567`）——作為租戶登記手機 |
| `plan` | string | ✅ | `lite199`（Lite）或 `pro499`（Pro） |
| `notes` | string | ❌ | 備註（≤500 字；例如客戶行業、知識庫要點——AIBot 方服務時會參考） |

### curl 範例

```bash
curl -X POST "https://wtsaibot.com/partner/v1/tenants" \
  -H "X-Partner-Key: <PARTNER_API_KEY>" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "示範茶餐廳",
    "phone": "85291234567",
    "plan": "pro499",
    "notes": "港式茶餐廳，午市套餐外賣為主"
  }'
```

### Response `201`

```json
{
  "tenantId": "yourbrand_a1b2c3",
  "webhookToken": "1234567890",
  "webhookUrl": "https://wtsaibot.com/webhook/1234567890",
  "portalUrl": "https://wtsaibot.com/merchant"
}
```

| 欄位 | 說明 |
|---|---|
| `tenantId` | 租戶唯一 ID（`夥伴id_6位隨機`格式，不可自行指定） |
| `webhookUrl` | WhatsApp 入站訊息 webhook——**填入 RPMSMS／WhatsApp 後台的 Webhook 欄**（客戶綁定裝置時由 AIBot 方指引） |
| `portalUrl` | 商戶門戶登入入口（客戶自助使用；登入資料由 AIBot 方交付客戶） |

新建租戶即時套用**功能白名單**（預設：AI 核心對話＋多輪記憶＋智能分流＋轉人工；報價單 PDF 等其他功能預設關閉——客戶需要額外功能時請聯絡 AIBot 開通）。

---

## 5. `GET /partner/v1/tenants` — 列出名下租戶

### curl 範例

```bash
curl "https://wtsaibot.com/partner/v1/tenants" \
  -H "X-Partner-Key: <PARTNER_API_KEY>"
```

### Response `200`

```json
{
  "partner": "yourbrand",
  "tenants": [
    {
      "tenantId": "yourbrand_a1b2c3",
      "name": "示範茶餐廳",
      "status": "trial",
      "planTier": "pro499",
      "createdAt": 1747267200000
    }
  ]
}
```

`status`：`trial`（試用中）／`paid`（已付費）／`suspended`（已暫停）。`createdAt` 為 Unix 毫秒時間戳。

---

## 6. `GET /partner/v1/usage` — 用量報表

查詢名下所有租戶於指定月份的對話用量聚合（批價結算依據）。月份以香港時間（HKT）為日界計算。

### 參數

| 參數 | 必填 | 說明 |
|---|---|---|
| `month` | ❌ | `YYYY-MM`；預設＝當月（HKT） |

### curl 範例

```bash
curl "https://wtsaibot.com/partner/v1/usage?month=2026-09" \
  -H "X-Partner-Key: <PARTNER_API_KEY>"
```

### Response `200`

```json
{
  "partner": "yourbrand",
  "month": "2026-09",
  "tenants": [
    {
      "tenantId": "yourbrand_a1b2c3",
      "name": "示範茶餐廳",
      "conversations": 42,
      "messages": 318
    }
  ],
  "totals": {
    "conversations": 42,
    "messages": 318
  }
}
```

- `conversations`＝獨立客戶對話段數（以 session 計）；`messages`＝訊息總數（客戶＋AI 回覆）。
- 當月查詢為進行中數字（未完月）。

---

## 7. `GET /partner/v1/team` — 渠道團隊（Agent 漏斗＋成交單）

查詢貴夥伴旗下所有推薦 Agent 的表現漏斗（點擊／查詢／成交／累計佣金）與最近成交訂單（最近 100 筆）。

### curl 範例

```bash
curl "https://wtsaibot.com/partner/v1/team" \
  -H "X-Partner-Key: <PARTNER_API_KEY>"
```

### Response `200`

```json
{
  "partner": "yourbrand",
  "agents": [
    {
      "id": 12,
      "name": "陳大文",
      "code": "A1B2C3",
      "status": "active",
      "activatedAt": 1747267200000,
      "clicks": 150,
      "leads": 32,
      "converted": 5,
      "rewardsTotal": 10000
    }
  ],
  "orders": [
    {
      "orderId": "ORD-20261001-001",
      "customerName": "示範茶餐廳",
      "plan": "pro499",
      "amount": 5490,
      "status": "paid",
      "refCode": "A1B2C3",
      "createdAt": 1791072000000
    }
  ]
}
```

- `status`：`pending`（待審核）／`active`（已審核）。`rewardsTotal` 為該 Agent 累計佣金（HK$）。
- `orders` 只回最近 100 筆；`amount` 為合約總額（HK$）；`status`：`pending`／`paid`／`cancelled`。

---

## 8. 錯誤碼表

| HTTP | `code` | 場景 | 處理建議 |
|---|---|---|---|
| `400` | `MISSING_NAME` | 建立租戶時未填 `name` | 檢查 request body |
| `400` | `INVALID_PHONE` | `phone` 不是 6-15 位純數字 | 轉為 E.164 純數字（去除 `+`） |
| `400` | `INVALID_PLAN` | `plan` 不是 `lite199`/`pro499` | — |
| `401` | `INVALID_PARTNER_KEY` | 未附帶或錯誤的 Key | 檢查 header 名稱為 `X-Partner-Key`；Key 重新生成後舊 Key 即時失效 |
| `404` | `NOT_FOUND` | 路徑或方法不正確 | 對照端點表 |
| `429` | `RATE_LIMITED` | 超過 120 req/min | 按 `Retry-After` 秒數後重試（建議指數退避） |
| `503` | `ID_COLLISION` | tenant_id 隨機撞號（極罕見） | 重試一次即可 |

錯誤回應一律為 JSON：`{"error": "...", "code": "..."}`。

## 9. Webhook 推送（可選進階設置）

除輪詢外，夥伴可選擇開通 **Webhook 推送**——指定事件發生時，AIBot 主動將數據推送到貴方系統，免輪詢、近乎即時。適合已自有 CRM／結算系統、想把訂單與成交數據自動同步的夥伴。

### 開通方式

聯絡 AIBot 提供 **HTTPS 回調端點 URL**（必須為公網 HTTPS），開通後 AIBot 交付一組 **Webhook Secret**（簽名驗證用）。設置由 AIBot 方配置，夥伴無需自助操作。

### 事件類型（第一期）

| 事件 | 觸發時機 |
|---|---|
| `order.created` | 名下租戶產生新訂單 |
| `order.paid` | 訂單付款確認 |

### Payload（JSON）

```json
{
  "event": "order.paid",
  "partner": "yourbrand",
  "timestamp": 1791072000000,
  "data": {
    "orderId": "ORD-20261001-001",
    "tenantId": "yourbrand_a1b2c3",
    "customerName": "示範茶餐廳",
    "plan": "pro499",
    "amount": 5490,
    "refCode": "A1B2C3"
  }
}
```

### 簽名驗證

每個請求附帶 headers：

- `X-AIBot-Event`：事件類型
- `X-AIBot-Signature`：`HMAC-SHA256(Webhook Secret, 原始 request body)` 的 hex

貴方伺服器應以同一 Secret 重新計算並比對（建議常數時間比較），通過才處理。

### 重試策略

回應非 `2xx` 或超時（10 秒）視為失敗，按 **1 分 → 5 分 → 30 分 → 2 小時**重試共 4 次；仍失敗可經 `GET /team`（orders）補數，不會漏單。

### 未開通時

未開通 Webhook 的夥伴照舊以 `GET /team` 與 `GET /usage` 輪詢過渡——兩種方式並行不衝突。

## 10. 整合備註

- 所有請求與回應均為 UTF-8 JSON。
- 建議每次整合前先呼叫 `GET /partner/v1/tenants` 自檢鑑權。
- **KB／prompt／功能開通**：此等事項由 AIBot 方人工服務。客戶資料（菜單、常見問題、收費、人設要求）由夥伴整理後交予 AIBot，交付時效另行商議。
- **測試**：AIBot 會為每個夥伴提供一組**測試 Key**（對應測試夥伴帳號）作整合驗證；正式 Key 僅接收生產流量。
