在 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 直接路由到您的服务器,或经由带签名的转发路由。
签名中的 t 与您服务器时钟之间可接受的最大差值;每次重试都会以新的 t 重新签名。
转发的 POST 在 easyCoexistence 安排该次投递重试之前,等待 2xx 响应的时长。
Meta 在直接 Webhook 未收到 HTTP 200 时重试的时长,这可能导致同一消息被投递两次。
用户最后一条消息之后的客服窗口期;窗口期之外,Meta 只接受模板消息。
同时使用 WhatsApp Business 应用和 Cloud API 的号码的固定吞吐量。
编写的智能体应使用哪种路由?
转发模式下,号码保留在自动化模式中:Meta 将消息投递给 easyCoexistence,自动化仍可运行,每条 Meta 变更的签名副本会发送到您的转发 URL。另一种变体无需转发:自动化中的“调用我的 Webhook”步骤会把消息 POST 到您的端点,并在 20 秒内发送您返回的 {"reply"},去重、手机暂停和 24 小时检查均由平台完成。
直连模式下,Meta 直接将其 Webhook 发送到您的端点(通过 set_webhook_destination 设置),easyCoexistence 永远看不到这些消息。该号码的自动化处于关闭状态,因此所有防护措施都需由您自行实现。若在连接后 24 小时内保存目的地,6 个月历史记录的导入同样由您负责。下方示例用一套共享核心处理全部三种入口。
| Forwarded, signed | Direct from Meta | |
|---|---|---|
| Number mode | Automations on (managed) | Direct to your server |
| Body | One Meta change: id, event, received_at, connection, value | Meta's envelope: object, entry, changes |
| Authentication | X-EC-Signature, HMAC-SHA256 with a per-number secret | A secret in the URL path |
| Acknowledge | Any 2xx within 10 seconds | HTTP 200; Meta retries other codes |
| Retries | 7 attempts over about 33 hours | Up to 7 days |
| Reply | Graph API, or {"reply"} to a Call my webhook step | Graph API |
| History import | Not requested | Requested 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: 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 响应“调用我的 Webhook”步骤,使用该自动化自己的签名密钥签名,并将历史记录转换为聊天轮次。/meta/:secret 是直连路由:它以原始 hub.challenge 响应 Meta 的 GET 握手请求,并且仅在密钥路径上接受 POST。
HMAC 密钥是完整的密钥,包括 whsec_ 前缀,以 UTF-8 文本形式使用。express.raw 保持字节完整,其 5 MB 限制足以容纳最大 3 MB 的 Meta 负载。
// 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: 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 重新投递的变更会以新的 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,其中 access_token 是企业自有的访问令牌;号码页面在“接入您自己的系统”下显示相同的值。若 access_token 为 null,请从电脑上使用“重新连接”重新连接该号码以签发令牌。请像保护密码一样保护该访问令牌,因为持有它的任何人都能以企业身份发送消息。
常见错误
- 对重新序列化的 JSON 校验 HMAC。Python 的 json.dumps 默认会在分隔符后添加空格,因此经解析再转储的请求体将不再匹配;请校验原始字节。
- 对密钥进行 Base64 解码,或去掉其 whsec_ 前缀。密钥就是整个字符串,按 UTF-8 文本使用,与您当初只显示一次的内容完全一致。
- 在直连路由上使用您自己的 Meta 应用密钥校验 X-Hub-Signature-256。Meta 使用 easyCoexistence 的应用密钥签名,该密钥并未共享,因此真实事件会校验失败;请改用路径密钥进行身份验证。
- 根据到达时间计算窗口。被延迟数小时后重试的转发仍携带 Meta 的原始时间戳;请与其比较,否则智能体会在 24 小时后回复,Meta 将拒绝发送。
每个号码全天候受到监控,连接中断时发出警报。每个号码每月 US$ 9 起,最低降至 US$ 0.75,号码越多越便宜,前 3 天免费试用。
常见问题
智能体能否理解语音消息和图片?
可以,通过您自己的代码实现。Meta 的负载携带媒体 ID:使用 GET /<media-id> 和该号码的访问令牌下载,然后使用相同的 Authorization 请求头获取返回的 URL,再用您的模型进行转录或描述。自动化只能看到诸如 [voice message] 之类的占位符。
示例可以使用哪些模型?
任何兼容 OpenAI 的 chat completions 端点背后的模型,包括 OpenAI 的模型以及通过 OpenRouter 接入的模型;也可以用您服务商的 SDK 替换 askModel 和 ask_model。easyCoexistence 从不对 AI 计费:由您的服务商直接向您收费。
智能体能否主动发起对话?
只能使用已获批准的模板,通过 type 为 template 的请求发送到同一个发送端点。在 Coexistence 号码上,模板只能通过 API 发送,不能从手机应用发送;Meta 按每条消息向企业自己的 WhatsApp Business Account 计费。
一个智能体能否服务多个号码?
可以。通过 value.metadata.phone_number_id 或 connection.phone_number_id 进行路由,并为每个号码分别保留一个发送端点、一个访问令牌和一个转发密钥,因为每个号码各有其独立的配置。
继续阅读
准备开始了吗?
几分钟即可设置 WhatsApp Coexistence,而不是几个月。应用会继续在手机上运行。
开始免费试用验证时间