登入開始免費試用
Meta Tech Provider

在 Coexistence 號碼上用 Node.js 與 Python 建立 WhatsApp AI 智能代理

號碼的訊息可經轉發接收,附上你需要驗證的 HMAC 簽署(X-EC-Signature),或直接從 Meta 的 webhook 接收,並在 URL 中附上密鑰。之後略過已處理的訊息 ID;若對話中出現 echo 事件,顯示有人從手機回覆,則該對話保持靜默;只有在客戶最後一則訊息後 24 小時內,才透過 Cloud API 發送模型的回覆。

easyCoexistence 將商戶在 WhatsApp Business 應用程式中持續使用的號碼連接到 Meta 的 Cloud API,透過 get_api_credentials 向你的程式碼提供憑證,並在開啟自動化時,將訊息直接從 Meta 路由到你的伺服器,或透過已簽署的轉發路由。

5 min

簽署中的 t 與你的時鐘之間,可接受的最大差距;每次重試都會以新的 t 重新簽署。

10 s

轉發的 POST 等待 2xx 回應的時間,超過後 easyCoexistence 會排程重試該次投遞。

7 days

未收到 HTTP 200 時,Meta 重試直接 webhook 的時間長度,這可能導致同一則訊息送達兩次。

24 hours

用戶最後一則訊息後的客戶服務窗口;窗口以外,Meta 只接受訊息範本。

20 mps

同時使用 WhatsApp Business 應用程式與 Cloud API 的號碼所具備的固定吞吐量。

應採用哪條路由?

轉發方式表示號碼會保留在自動化的開啟模式中:Meta 把訊息送到 easyCoexistence,自動化仍可執行,且每個 Meta change 的已簽署副本會送到你的 Forward URL。另一種變體完全無需轉發:自動化的「Call my webhook」步驟會把訊息 POST 到你的端點,並在 20 秒內發送你回傳的 {"reply"},去重、手機暫停和 24 小時檢查均由平台代為處理。

直接方式表示 Meta 將自己的 webhook 直接發送到你的端點(以 set_webhook_destination 設定),easyCoexistence 完全看不到訊息。該號碼的自動化會關閉,因此所有防護都由你負責,號碼連接後 24 小時內儲存目的地時的 6 個月歷史匯入也由你負責。下方範例以一個共用核心處理全部三個入口。

Forwarded, signedDirect from Meta
Number modeAutomations on (managed)Direct to your server
BodyOne Meta change: id, event, received_at, connection, valueMeta's envelope: object, entry, changes
AuthenticationX-EC-Signature, HMAC-SHA256 with a per-number secretA secret in the URL path
AcknowledgeAny 2xx within 10 secondsHTTP 200; Meta retries other codes
Retries7 attempts over about 33 hoursUp to 7 days
ReplyGraph API, or {"reply"} to a Call my webhook stepGraph API
History importNot requestedRequested if saved within 24 hours of connecting

在 Node.js 中,代理如何處理訊息?

agent.mjs 包含兩條路由共用的邏輯。它記錄客戶最後一則訊息的時間;當 smb_message_echoes 事件顯示有人從 WhatsApp Business 應用程式回覆時(這是 easyCoexistence 自動化的預設行為),該對話會暫停 4 小時;略過已處理的訊息 ID;並且只在 24 小時窗口內發送。窗口從訊息本身的時間戳記起算,而非從抵達你的伺服器時起算,因為重試的投遞可能延遲數小時才到。

用戶以 BSUID(from_user_id,或 echo 中的 to_user_id)為鍵,電話號碼為後備;僅知道 BSUID 的用戶會以 recipient 取代 to 作答。模型呼叫可使用任何兼容 OpenAI 的 chat completions API;如果你偏好,可換成你的供應商 SDK。

agent.mjs: the shared logic
// agent.mjs: what the agent does with one Meta change, whichever route brought it.
const DAY = 24 * 3600 * 1000;
const PAUSE = 4 * 3600 * 1000;   // quiet time after a person replies (automations default to 4 h)
const seen = new Set();          // handled ids: use Redis or your database in production
const lastInbound = new Map();   // user -> ms of their last message
const quietUntil = new Map();    // user -> ms until which a person has the chat

export function firstTime(id) {
  if (seen.has(id)) return false;
  seen.add(id);
  return true;
}

export async function handleChange(field, value) {
  if (field === "smb_message_echoes") {
    // Someone answered from the WhatsApp Business app: step back on that chat.
    for (const e of value.message_echoes ?? []) {
      quietUntil.set(e.to_user_id ?? e.to, Number(e.timestamp) * 1000 + PAUSE);
    }
    return;
  }
  if (field !== "messages") return;              // statuses ride in value.statuses: ignored here
  for (const m of value.messages ?? []) {
    if (!firstTime(m.id)) continue;               // Meta delivered this message before
    const user = m.from_user_id ?? m.from;        // BSUID first, phone number as fallback
    lastInbound.set(user, Math.max(Number(m.timestamp) * 1000, lastInbound.get(user) ?? 0));
    if ((quietUntil.get(user) ?? 0) > Date.now()) continue; // a person has this chat
    if (m.type !== "text") continue;              // media: fetch it by id first (see the FAQ)
    const reply = await askModel([{ role: "user", content: m.text.body }]);
    if (!reply) continue;
    if (Date.now() - lastInbound.get(user) >= DAY) continue; // window closed: template only
    await sendText({ phone: m.from, bsuid: m.from_user_id }, reply);
  }
}

// Any OpenAI-compatible chat completions API (OpenAI, OpenRouter...).
export async function askModel(turns) {
  const res = await fetch(`${process.env.AI_BASE_URL}/chat/completions`, {
    method: "POST",
    headers: { Authorization: `Bearer ${process.env.AI_KEY}`, "Content-Type": "application/json" },
    body: JSON.stringify({
      model: process.env.AI_MODEL,
      messages: [{ role: "system", content: process.env.AI_INSTRUCTIONS ?? "Answer briefly." }, ...turns],
    }),
  });
  if (!res.ok) throw new Error(`AI provider answered ${res.status}`);
  const data = await res.json();
  return data.choices?.[0]?.message?.content?.trim() ?? "";
}

// send_endpoint and access_token come from get_api_credentials.
async function sendText({ phone, bsuid }, text) {
  const res = await fetch(process.env.SEND_ENDPOINT, {
    method: "POST",
    headers: { Authorization: `Bearer ${process.env.WA_TOKEN}`, "Content-Type": "application/json" },
    body: JSON.stringify({
      messaging_product: "whatsapp",
      recipient_type: "individual",
      ...(phone ? { to: phone } : { recipient: bsuid }), // a BSUID-only user gets recipient
      type: "text",
      text: { body: text.slice(0, 4096) },
    }),
  });
  if (!res.ok) throw new Error(`Graph API answered ${res.status}: ${await res.text()}`);
}

在 Node.js 中如何驗證並路由事件?

server.mjs 提供三個入口。/ec/forward 接收受管號碼的轉發:它在進行任何處理前,以該號碼的轉發密鑰驗證原始位元組上的 X-EC-Signature,並先回覆 200,且略過已接受的投遞 ID,因為重試會帶上相同的 ID 與新的簽署。主體中的 event 是 Meta 的欄位名稱,value 是 Meta 未經修改的 change。/ec/agent 回應「Call my webhook」步驟,以該自動化自己的 Signing secret 簽署,並將歷史記錄轉為對話輪次。/meta/:secret 是直接路由:它以原始的 hub.challenge 回應 Meta 的 GET 握手,且只接受路徑密鑰下的 POST。

HMAC 金鑰是整個密鑰(包括 whsec_ 前綴),以 UTF-8 文字計。express.raw 會保持位元組完整,其 5 MB 限制足以容納最大 3 MB 的 Meta 負載。

server.mjs: verification and routes (Express)
// server.mjs: Node 18+, npm i express, then node server.mjs
import crypto from "node:crypto";
import express from "express";
import { askModel, firstTime, handleChange } from "./agent.mjs";

const app = express();

// X-EC-Signature: t=<unix>,v1=<hex HMAC-SHA256 of "<t>.<raw body>">, keyed with the whole secret.
export function verifyEc(raw, header, secret, toleranceSec = 300) {
  const m = /^t=(\d+),v1=([0-9a-f]{64})$/.exec(String(header ?? "").trim());
  if (!m || !Buffer.isBuffer(raw) || !secret) return false;
  if (Math.abs(Date.now() / 1000 - Number(m[1])) > toleranceSec) return false; // stale or replayed
  const expected = crypto.createHmac("sha256", secret).update(`${m[1]}.`).update(raw).digest();
  return crypto.timingSafeEqual(expected, Buffer.from(m[2], "hex"));
}

function sameSecret(a, b) {
  const x = Buffer.from(String(a)), y = Buffer.from(String(b ?? ""));
  return x.length === y.length && crypto.timingSafeEqual(x, y);
}

// Route A, forwarded: a managed number's Forward URL. One Meta change per POST.
app.post("/ec/forward", express.raw({ type: "*/*", limit: "5mb" }), (req, res) => {
  if (!verifyEc(req.body, req.get("X-EC-Signature"), process.env.EC_FORWARD_SECRET)) return res.sendStatus(401);
  res.sendStatus(200);                                   // acknowledge inside 10 s, then work
  const d = JSON.parse(req.body.toString("utf8"));
  if (!firstTime(`delivery:${d.id}`)) return;            // a retry of a delivery already taken
  handleChange(d.event, d.value).catch(console.error);   // d.event is the Meta field name
});

// Route A, synchronous: a "Call my webhook" step. Answer {"reply"} within 20 s.
app.post("/ec/agent", express.raw({ type: "*/*", limit: "1mb" }), async (req, res) => {
  if (!verifyEc(req.body, req.get("X-EC-Signature"), process.env.EC_AUTOMATION_SECRET)) return res.sendStatus(401);
  const step = JSON.parse(req.body.toString("utf8"));
  const turns = step.history.map((h) => ({ role: h.direction === "in" ? "user" : "assistant", content: h.text }));
  while (turns[0]?.role === "assistant") turns.shift();
  if (!turns.length) turns.push({ role: "user", content: step.message?.text ?? "" }); // tests carry no history
  res.json({ reply: await askModel(turns) });            // step.dry_run is true on "Test it"
});

// Route B, direct: Meta's own envelope. The secret path is the credential.
app.get("/meta/:secret", (req, res) => {
  if (!sameSecret(req.params.secret, process.env.PATH_SECRET)) return res.sendStatus(404);
  if (req.query["hub.mode"] === "subscribe" && req.query["hub.verify_token"] === process.env.VERIFY_TOKEN) {
    return res.type("text/plain").send(String(req.query["hub.challenge"]));
  }
  res.sendStatus(403);
});

app.post("/meta/:secret", express.json({ limit: "5mb" }), (req, res) => {
  if (!sameSecret(req.params.secret, process.env.PATH_SECRET)) return res.sendStatus(404);
  res.sendStatus(200);                                   // Meta retries anything but 200
  for (const entry of req.body.entry ?? []) {
    for (const change of entry.changes ?? []) handleChange(change.field, change.value).catch(console.error);
  }
});

app.listen(process.env.PORT ?? 3000);

同一個代理的 Python 版本是怎樣的?

一個 Flask 檔案,具有相同的三條路由與相同規則。request.get_data() 會傳回用於 HMAC 的原始主體,hmac.compare_digest 負責常數時間比較,而工作會在 200 回應之後於背景執行緒執行,因此 easyCoexistence 和 Meta 都不必等待你的模型。開發時以 flask --app agent run 執行,正式環境則置於 gunicorn 或其他 WSGI 伺服器之後。

記憶體內的集合與字典適用於單一程序。若有多個工作程序或實例,請將其移至 Redis 或你的資料庫,訊息 ID 使用附有到期時間的 set-if-absent 寫入,否則兩個工作程序會回覆同一則訊息。

agent.py: the whole agent (Flask)
# agent.py: pip install flask requests, then flask --app agent run
import hashlib, hmac, json, os, re, threading, time
import requests
from flask import Flask, abort, request

app = Flask(__name__)
DAY, PAUSE = 24 * 3600, 4 * 3600
seen, last_inbound, quiet_until = set(), {}, {}  # use Redis or a database in production
lock = threading.Lock()

def verify_ec(raw: bytes, header: str, secret: str, tolerance: int = 300) -> bool:
    m = re.fullmatch(r"t=([0-9]+),v1=([0-9a-f]{64})", (header or "").strip())
    if not m or not secret or abs(time.time() - int(m[1])) > tolerance:
        return False
    expected = hmac.new(secret.encode(), m[1].encode() + b"." + raw, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, m[2])

def first_time(key: str) -> bool:
    with lock:
        if key in seen:
            return False
        seen.add(key)
        return True

def ask_model(turns: list) -> str:  # any OpenAI-compatible chat completions API
    r = requests.post(f"{os.environ['AI_BASE_URL']}/chat/completions", timeout=30,
                      headers={"Authorization": f"Bearer {os.environ['AI_KEY']}"},
                      json={"model": os.environ["AI_MODEL"], "messages": [
                          {"role": "system", "content": os.environ.get("AI_INSTRUCTIONS", "Answer briefly.")}, *turns]})
    r.raise_for_status()
    return (r.json()["choices"][0]["message"]["content"] or "").strip()

def send_text(phone, bsuid, text: str) -> None:  # SEND_ENDPOINT and WA_TOKEN: get_api_credentials
    to = {"to": phone} if phone else {"recipient": bsuid}
    r = requests.post(os.environ["SEND_ENDPOINT"], timeout=15,
                      headers={"Authorization": f"Bearer {os.environ['WA_TOKEN']}"},
                      json={"messaging_product": "whatsapp", "recipient_type": "individual", **to,
                            "type": "text", "text": {"body": text[:4096]}})
    r.raise_for_status()

def handle_change(field: str, value: dict) -> None:
    if field == "smb_message_echoes":  # a person answered from the app: step back
        for e in value.get("message_echoes", []):
            quiet_until[e.get("to_user_id") or e.get("to")] = int(e["timestamp"]) + PAUSE
        return
    if field != "messages":
        return
    for m in value.get("messages", []):
        if not first_time(m["id"]):  # Meta delivered this message before
            continue
        user = m.get("from_user_id") or m.get("from")
        last_inbound[user] = max(int(m["timestamp"]), last_inbound.get(user, 0))
        if quiet_until.get(user, 0) > time.time() or m.get("type") != "text":
            continue
        reply = ask_model([{"role": "user", "content": m["text"]["body"]}])
        if reply and time.time() - last_inbound[user] < DAY:  # past 24 h: template only
            send_text(m.get("from"), m.get("from_user_id"), reply)

def later(field, value):
    threading.Thread(target=handle_change, args=(field, value), daemon=True).start()

@app.post("/ec/forward")  # route A: a managed number's Forward URL
def forward():
    raw = request.get_data()
    if not verify_ec(raw, request.headers.get("X-EC-Signature", ""), os.environ["EC_FORWARD_SECRET"]):
        abort(401)
    d = json.loads(raw)
    if first_time("delivery:" + d["id"]):  # skip retries of a delivery already taken
        later(d["event"], d["value"])
    return "", 200

@app.post("/ec/agent")  # route A: a "Call my webhook" step, answer within 20 s
def agent_step():
    raw = request.get_data()
    if not verify_ec(raw, request.headers.get("X-EC-Signature", ""), os.environ["EC_AUTOMATION_SECRET"]):
        abort(401)
    step = json.loads(raw)
    turns = [{"role": "user" if h["direction"] == "in" else "assistant", "content": h["text"]}
             for h in step["history"]]
    while turns and turns[0]["role"] == "assistant":
        turns.pop(0)
    turns = turns or [{"role": "user", "content": step["message"]["text"] or ""}]
    return {"reply": ask_model(turns)}

@app.get("/meta/<secret>")  # route B: Meta's GET handshake
def meta_handshake(secret):
    if not hmac.compare_digest(secret.encode(), os.environ["PATH_SECRET"].encode()):
        abort(404)
    if (request.args.get("hub.mode") == "subscribe"
            and request.args.get("hub.verify_token") == os.environ["VERIFY_TOKEN"]):
        return request.args.get("hub.challenge", ""), 200, {"Content-Type": "text/plain"}
    abort(403)

@app.post("/meta/<secret>")  # route B: Meta's envelope, straight from Meta
def meta_events(secret):
    if not hmac.compare_digest(secret.encode(), os.environ["PATH_SECRET"].encode()):
        abort(404)
    for entry in (request.get_json(silent=True) or {}).get("entry", []):
        for change in entry.get("changes", []):
            later(change.get("field"), change.get("value", {}))
    return "", 200

如何避免重複回覆?

重複的成因有六種,上方範例處理了前五種:

  • Meta 的重試。直接 webhook 在收到 HTTP 200 以外的任何回應後,最多重試 7 天;請保存訊息 ID 的紀錄,並略過已處理的 ID。
  • 轉發的重試。easyCoexistence 會在 10 秒內未收到 2xx 的投遞時,以相同 ID 重試;略過已接受的 ID,然後以訊息 ID 去重,因為 Meta 重新投遞的 change 會以新 ID 再次轉發。
  • 回應確認過慢。先回覆,之後再處理;若處理程序等待模型,就會超時,同一事件會再次送來。
  • 有人在手機上回覆。smb_message_echoes 事件表示有人從應用程式回覆;請在該對話中保持靜默數小時。
  • 多個工作程序。記憶體內的集合無法跨程序共用;請將儲存移至 Redis 或你的資料庫。
  • 兩個回覆者。AI 回覆自動化與你自己的代理若同時在同一對話中作答,而你的 Graph API 發送不會產生 echo,因此不會暫停自動化。每個號碼請只選用一個回覆者。

密鑰與憑證從哪裡來?

來自控制台或 MCP 連接器,並且只應存放於你伺服器的環境變數中。get_api_credentials 會傳回 graph_api_base、waba_id、phone_number_id、send_endpoint 與 access_token,即該商戶自己的存取權杖;號碼頁面在「Plug in your own system」下顯示相同的值。若 access_token 為 null,請從電腦上以「Reconnect」重新連接號碼以發出權杖。請將存取權杖當作密碼處理,因為任何持有它的人都能以該商戶的身分發送訊息。

EC_FORWARD_SECRETShown once when you save a Forward URL, or returned once by set_inbound_mode; New secret rotates it
EC_AUTOMATION_SECRETSigning secret on the automation's page, under its Call my webhook step
SEND_ENDPOINT, WA_TOKENsend_endpoint and access_token from get_api_credentials
PATH_SECRET, VERIFY_TOKENDirect route: 32 or more random characters in the URL, and the handshake token you chose
AI_BASE_URL, AI_KEY, AI_MODELAny OpenAI-compatible API, such as https://api.openai.com/v1 or https://openrouter.ai/api/v1

常見錯誤

  • 以重新序列化的 JSON 檢查 HMAC。Python 的 json.dumps 預設在分隔符後加入空格,因此解析後再傾印的主體將不再相符;請驗證原始位元組。
  • 對密鑰進行 Base64 解碼,或捨去其 whsec_ 前綴。金鑰是整個字串,以 UTF-8 文字計,與你一次性看到的完全相同。
  • 在直接路由上以你自己的 Meta 應用程式密鑰驗證 X-Hub-Signature-256。Meta 以 easyCoexistence 的應用程式密鑰簽署,該密鑰並未共享,因此真實事件會驗證失敗;請改以路徑密鑰進行身分驗證。
  • 以抵達時間計算窗口。被數小時後才重試的轉發,仍帶有 Meta 的原始時間戳記;請以此比較,否則代理會在 24 小時後回覆,Meta 將拒絕發送。
使用 EasyCoexistence 完成這項設定

每個號碼均全天候 24/7 監控,連接中斷時會發出警報。每個號碼每月 US$ 9 起,號碼越多越便宜,最低降至 US$ 0.75,並提供首 3 天免費試用。

常見問題

代理可以理解語音訊息和相片嗎?

可以,但需要你自己的程式碼。Meta 的負載包含媒體 ID:以 GET /<media-id> 及號碼的存取權杖下載,再以相同的 Authorization 標頭取得返回的 URL,然後用你的模型轉錄或描述內容。自動化只會看到 [voice message] 之類的佔位符。

範例可以使用哪些模型?

任何兼容 OpenAI chat completions 端點的模型,包括 OpenAI 的模型,以及透過 OpenRouter 接入的模型;你也可以將 askModel 與 ask_model 替換為你的供應商 SDK。easyCoexistence 從不為 AI 收費:由你的供應商直接向你收費。

代理可以主動開啟對話嗎?

只能使用已獲批准的範本,並以 type template 發送到相同的發送端點。在 Coexistence 號碼上,範本只能透過 API 發出,不能從手機應用程式發出,而 Meta 按每則訊息向商戶自己的 WhatsApp Business Account 收費。

一個代理能服務多個號碼嗎?

可以。以 value.metadata.phone_number_id 或 connection.phone_number_id 路由,並為每個號碼保留一個發送端點、一個存取權杖與一個轉發密鑰,因為每個號碼各有自己的設定。

繼續閱讀

準備開始嗎?

幾分鐘內設定 WhatsApp Coexistence,而非幾個月。應用程式在手機上仍可繼續運作。

開始免費試用

驗證日期