通过带签名的 webhook 接收 WhatsApp 消息,用您自己的代码回答常见问题,并在客户要求时把对话转交给真人。
在本指南中,您将构建一个小型 WhatsApp 机器人,它回答有关营业时间和价格的问题,并在客户要求时把对话转交给真人。
客户看到的内容: 他们给您的 WhatsApp 号码发消息,消息出现蓝色对勾,显示“正在输入...”,一秒钟后收到回复。当他们写下“can I talk to a person?”时,机器人会说会有真人来回复,从那时起只有您的团队回复。
您看到的内容: 每条消息和回复都在 app2email 收件箱和活动日志中,每条回复的送达和已读对勾都以 webhook 事件的形式出现,机器人转交对话时还会有对话摘要。
这个机器人不到 100 行 Node.js(Express)或 Python(Flask)代码。它会校验 webhook 签名,忽略已处理的事件,可以安全重试,并遵守 24 小时回复窗口。
POST,事件为 message.received。POST /messages 发送回复。message.status 事件。您的 URL 必须在 10 秒内返回 2xx 状态。否则 app2email 会稍后再次发送同一个事件,所以短暂的中断不会丢失任何内容。
plan_not_allowed;服务已暂停时会返回 403 service_not_live。请参阅入门指南。| 权限范围 | 机器人为什么需要它 |
|---|---|
messages:send | 发送回复(POST /messages),把消息标记为已读(POST /messages/read),把对话转交给真人(PUT /conversations/{contact}/owner) |
messages:read | 查询对话:负责人和回复窗口(GET /conversations/{contact}) |
webhooks:manage | 注册一次 webhook(POST /webhooks)。您也可以不写代码,在 API 密钥页面的 Webhooks 下添加 |
上线前先试一试。 沙盒密钥(带有沙盒标记的密钥,在 API 密钥页面创建)会针对您自己的号码运行所有检查,不会向 WhatsApp 发送任何内容:响应带有 "sandbox": true,消息 ID 以 wamid.SANDBOX. 开头,message.status 事件仍会送达。完全没有账户时,即时沙盒会给您一个演示号码 12025550100 的密钥,附带虚拟客户:使用 POST https://api.app2email.com/v1/account/sandbox(不带密钥、不带请求体),或 Management MCP 服务器的 create_sandbox 工具。它没有 webhook:请改用 GET /events?wait=25 读取事件(见常见问题)。详情:沙盒。
GET /me 对任何有效密钥都可用,并会显示它的权限范围和限制。在每个请求中,YOUR_NUMBER 是您发送消息所用的 WhatsApp 号码:国家代码在前,只写数字。
curl https://api.app2email.com/v1/YOUR_NUMBER/me \
-H "Authorization: Bearer YOUR_API_KEY"const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/me", {
headers: { Authorization: `Bearer ${process.env.API_KEY}` },
});
console.log(await res.json());import os, requests
res = requests.get("https://api.app2email.com/v1/YOUR_NUMBER/me",
headers={"Authorization": f"Bearer {os.environ['API_KEY']}"}, timeout=10)
print(res.json())您会得到的响应:
{
"success": true,
"request_id": "a7k3p",
"key_valid": true,
"api_version": "v1",
"number": "4976659348270",
"plan": "standard_5000",
"service_status": "LIVE",
"key": { "name": "WhatsApp bot", "scopes": ["messages:read", "messages:send"], "ip_allow": "" },
"limits": { "max_numbers_per_request": 1000, "requests_per_second": 20, "burst": 50, "rate_limit_mode": "enforce", "webhooks_max": 5 }
}service_status 必须是 LIVE,key.scopes 必须列出上表中的权限范围(或用 * 表示完全访问)。
app2email 只能把事件发送到公网 https 地址。开发期间,可以用隧道把一个地址转发到您的电脑。先在 3000 端口启动机器人(代码在下文),然后在第二个终端中运行:
# ngrok (https://ngrok.com)
ngrok http 3000
# or Cloudflare's cloudflared, no account needed for a quick tunnel
cloudflared tunnel --url http://localhost:3000两者都会打印一个 https 地址,例如 https://a1b2-203-0-113-7.ngrok-free.app。您的 webhook URL 就是这个地址加上 /webhook。快速隧道每次启动时可能会得到新地址:发生这种情况时,请用 PATCH /webhooks/{id} 和新的 url 更新 webhook。
无法使用隧道?GET /events?wait=25 可以在没有公网地址的情况下获取同样的事件(见常见问题)。
一次调用即可。响应中包含为每个事件签名的 签名密钥(whsec_...):请和您的 API 密钥放在一起保存,例如放在环境变量 WEBHOOK_SECRET 中。
curl -X POST https://api.app2email.com/v1/YOUR_NUMBER/webhooks \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"url": "https://a1b2-203-0-113-7.ngrok-free.app/webhook"}'const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/webhooks", {
method: "POST",
headers: { Authorization: `Bearer ${process.env.API_KEY}`, "Content-Type": "application/json" },
body: JSON.stringify({ url: "https://a1b2-203-0-113-7.ngrok-free.app/webhook" }),
});
const { webhook } = await res.json();
console.log(webhook.id, webhook.secret);import os, requests
res = requests.post("https://api.app2email.com/v1/YOUR_NUMBER/webhooks",
headers={"Authorization": f"Bearer {os.environ['API_KEY']}"},
json={"url": "https://a1b2-203-0-113-7.ngrok-free.app/webhook"}, timeout=10)
webhook = res.json()["webhook"]
print(webhook["id"], webhook["secret"])您会得到的响应(201 Created;已缩短:响应还会在 events 中列出所有事件类型):
{
"success": true,
"request_id": "w8hk2",
"webhook": {
"id": "wh_a1b2c3d4e5f6g7h8",
"url": "https://a1b2-203-0-113-7.ngrok-free.app/webhook",
"secret": "whsec_...",
"created": "2026-11-21T09:00:00.000Z",
"active": true,
"format": "app2email"
}
}再次注册同一个 URL 会返回 200,并带有相同的 id 和密钥,所以这个调用可以安全地重复执行。一个号码最多有 5 个 webhook,每个 webhook 都会收到每个事件:您的代码按 type 挑出要处理的类型,对其余的返回 2xx。本指南中请保持 format 为 app2email(默认值)。
POST /webhooks/{id}/test 会立刻发送一个带签名的示例,并告诉您您的 URL 是如何响应的。使用 {"type": "message.received"} 可以得到该事件的示例。
curl -X POST https://api.app2email.com/v1/YOUR_NUMBER/webhooks/wh_a1b2c3d4e5f6g7h8/test \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"type": "message.received"}'您会得到的响应(已缩短):
{
"success": true,
"request_id": "t3ws9",
"delivered": true,
"http_status": 200,
"response_ms": 38
}delivered: true 表示您的 URL 在 10 秒内返回了 2xx。测试事件带有 "test": true 和头 X-App2email-Test: true,其示例联系人是虚构的,所以下面的机器人会校验签名、记录事件,但不会回复它。每个号码每小时最多 30 次测试。然后用您自己的手机给您的号码发一条真实消息:机器人会回复。
每个调用都发往 https://api.app2email.com/v1/YOUR_NUMBER,并带有 Authorization: Bearer YOUR_API_KEY。
这是您的 URL 收到的 message.received 事件的请求体(一条文本消息):
{
"id": "evt_Xq3k9m2Lw8Rt5Yp1Zs01",
"type": "message.received",
"created": "2026-11-06T01:00:00.000Z",
"number": "4976659348270",
"data": {
"message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=",
"from": "61412345678",
"name": "Sample Contact",
"type": "text",
"text": "What are your opening hours?",
"conversation_url": "https://www.app2email.com/conversation/61412345678_4976659348270_SAMPLEk3XbQ9rTzP2mW",
"timestamp": "2026-11-06T01:00:00.000Z",
"from_user_id": "AU.1234567890123456"
}
}id(也在头 X-App2email-Delivery 中)在每次重试时都相同:您按它去重。data.from 是客户的号码。使用 WhatsApp 用户名的联系人可能带有 from_user_id 而没有号码;这个 ID 在任何可以用号码的地方都可以使用。data.type 是 text、image、audio、interactive(点击了回复按钮或列表行,带有 interactive.id)、button(模板的快速回复按钮,带有 button.payload)等等。机器人回复文本和点击,其余的交给您的团队。GET /conversations/{contact}(权限范围 messages:read)会告诉您谁在处理这个对话,以及现在是否可以发送自由格式的回复。
curl https://api.app2email.com/v1/YOUR_NUMBER/conversations/61412345678 \
-H "Authorization: Bearer YOUR_API_KEY"您会得到的响应:
{
"success": true,
"request_id": "c9slm",
"contact": "61412345678",
"identity_type": "phone",
"phone": "61412345678",
"name": "John",
"window_state": "open",
"window_open": true,
"window_closes_at": "2026-11-07T00:45:00Z",
"last_inbound_at": "2026-11-06T01:00:00Z",
"messages": 12,
"owner": "",
"conversation_url": "https://www.app2email.com/conversation/61412345678_4976659348270_..."
}正常处理时,owner 为空。当它是 human 或 paused 时,表示有真人负责这个对话,机器人保持沉默;whatsapp_ai 表示由 WhatsApp 自己的 AI 代理负责。
POST /messages/read(权限范围 messages:send)会把消息标记为已读,并且在带有 "typing": true 时显示输入指示器,最长 25 秒,或者直到您的回复到达。它是免费的:不计入您的套餐,也不受 24 小时窗口限制。
curl -X POST https://api.app2email.com/v1/YOUR_NUMBER/messages/read \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=", "typing": true}'您会得到的响应:
{
"success": true,
"request_id": "k2rdq",
"message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=",
"status": "read",
"typing_indicator": true
}带有 "type": "text" 的 POST /messages(权限范围 messages:send)会在回复窗口开启期间,向一个联系人发送自由格式的消息。
| 部分 | 要填写的内容 |
|---|---|
| 发给谁 | to:客户的号码(data.from),或他们的 from_user_id |
| 哪种消息 | type:普通回复用 text。在窗口之外:template |
| 内容是什么 | text.body:您的回复。text.preview_url:设为 true 可显示链接预览 |
| 您的密钥 | 头 Authorization: Bearer YOUR_API_KEY |
| 避免重复 | 头 Idempotency-Key:只属于这条回复的值,例如 text- 加上客户的 message_id。24 小时内用同一个密钥发出的相同请求不会再次发送 |
curl -X POST https://api.app2email.com/v1/YOUR_NUMBER/messages \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: text-wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=" \
-d '{"to": "61412345678", "type": "text", "text": {"body": "We are open Monday to Friday, 9 am to 5 pm.", "preview_url": false}}'const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/messages", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.API_KEY}`,
"Content-Type": "application/json",
"Idempotency-Key": `text-${messageId}`,
},
body: JSON.stringify({
to: "61412345678",
type: "text",
text: { body: "We are open Monday to Friday, 9 am to 5 pm.", preview_url: false },
}),
});
console.log(res.status, await res.json());res = requests.post(
"https://api.app2email.com/v1/YOUR_NUMBER/messages",
headers={"Authorization": f"Bearer {os.environ['API_KEY']}", "Idempotency-Key": f"text-{message_id}"},
json={"to": "61412345678", "type": "text",
"text": {"body": "We are open Monday to Friday, 9 am to 5 pm.", "preview_url": False}},
timeout=10,
)
print(res.status_code, res.json())您会得到的响应(200):
{
"success": true,
"request_id": "kxrkf",
"message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=",
"status": "accepted",
"type": "text",
"from": "4976659348270",
"to": "61412345678",
"window_closes_at": "2026-11-07T00:45:00Z",
"conversation_url": "https://www.app2email.com/conversation/61412345678_4976659348270_...",
"contacts": [{ "input": "61412345678", "wa_id": "61412345678" }]
}accepted 表示 WhatsApp 已接收这条消息。是否送达和被读取,之后会以 message.status 事件告知。带有相同 Idempotency-Key 的重复请求会再次得到这个相同的响应,并带有头 Idempotent-Replayed: true,不会发送两次。
失败时,响应带有 success: false 和一个 error 对象。请根据 error.code 判断,不要根据消息文本判断:
{
"success": false,
"request_id": "q2v8n",
"error": {
"code": "outside_24h_window",
"message": "The contact has not written to this number in the last 24 hours (or never), so only a template message can be sent.",
"how_to_fix": "Send an approved template message instead (\"type\": \"template\"). When the contact answers, normal messages work again for 24 hours.",
"documentation_url": "https://www.app2email.com/docs/api/errors#outside_24h_window",
"is_retriable": false
}
}调用过多会返回 429 rate_limited,并带有 Retry-After 头:
HTTP/1.1 429 Too Many Requests
Retry-After: 2
X-RateLimit-Limit: 50
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 2
{"success": false, "request_id": "r5lmt", "error": {"code": "rate_limited", "message": "Too many requests for this key.", "how_to_fix": "Wait, then send again.", "documentation_url": "https://www.app2email.com/docs/api/errors#rate_limited", "is_retriable": true, "retry_after_seconds": 2}}当客户要求找真人时,调用 PUT /conversations/{contact}/owner(权限范围 messages:send),带上 "owner": "human"、一个简短的 reason 和一个 summary。之后 app2email 的自动回复和其他代理都会不再理会这个联系人,通过电子邮件接收消息的人会看到摘要,每个 webhook 都会收到 conversation.owner_changed。until_minutes 可以让它变成临时的:到时间后,对话会自动恢复正常处理。
curl -X PUT https://api.app2email.com/v1/YOUR_NUMBER/conversations/61412345678/owner \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"owner": "human", "reason": "customer asked for a person", "summary": "Wants to move the delivery to Monday.", "until_minutes": 240}'响应中包含更新后的 conversation(字段与 GET /conversations/{contact} 相同)。
两个版本做的事情相同:校验签名,跳过测试事件和已处理的事件,跳过真人负责的对话,用输入指示器标记已读,遇到“person”时转交给真人,回答关键词,并在窗口关闭时改用模板。请先设置三个环境变量:NUMBER(您的 WhatsApp 号码,数字)、API_KEY 和 WEBHOOK_SECRET(第 3 步中的 whsec_... 值)。
// Node.js 18 or newer. npm install express then node bot.mjs
import crypto from "node:crypto";
import express from "express";
const { NUMBER, API_KEY, WEBHOOK_SECRET, PORT = 3000 } = process.env;
const API = `https://api.app2email.com/v1/${NUMBER}`;
const FALLBACK = { name: "hello_world", language: { code: "en_US" } }; // an approved template without placeholders
const RETRY_LATER = new Set(["rate_limited", "whatsapp_rate_limit", "too_many_messages_to_recipient"]);
const done = new Set(); // handled event ids: use a database table or Redis in production
const ANSWERS = [
[/\b(hours?|open|opening|closed)\b/i, "We are open Monday to Friday, 9 am to 5 pm, and Saturday 10 am to 2 pm."],
[/\b(prices?|cost|how much)\b/i, "A standard service is $49, an express service $79. Full list: https://example.com/prices"],
];
const HUMAN = /\b(human|person|someone|staff)\b/i;
const MENU = "Hi! I can tell you our opening hours or our prices. Type 'person' to talk to the team.";
function verify(raw, header, secret) {
const t = /(?:^|,)\s*t=(\d+)/.exec(header ?? "")?.[1];
const v1 = [...(header ?? "").matchAll(/(?:^|,)\s*v1=([0-9a-f]+)/g)].map((m) => m[1]); // two during a secret change
if (!t || v1.length === 0 || Math.abs(Date.now() / 1000 - Number(t)) > 300) return false;
const expected = crypto.createHmac("sha256", secret).update(t + ".").update(raw).digest("hex");
return v1.some((v) => v.length === expected.length && crypto.timingSafeEqual(Buffer.from(v), Buffer.from(expected)));
}
async function api(method, path, body, idempotencyKey) {
for (let attempt = 1; ; attempt++) {
const res = await fetch(API + path, {
method,
signal: AbortSignal.timeout(4000),
headers: { Authorization: `Bearer ${API_KEY}`, "Content-Type": "application/json",
...(idempotencyKey ? { "Idempotency-Key": idempotencyKey } : {}) },
body: body ? JSON.stringify(body) : undefined,
});
const json = await res.json();
if (res.ok) return json;
const code = json.error?.code;
const wait = Number(res.headers.get("Retry-After") ?? 1);
if (code === "rate_limited" && attempt < 3 && wait <= 3) { await new Promise((r) => setTimeout(r, wait * 1000)); continue; }
if (res.status >= 500 || RETRY_LATER.has(code)) throw new Error(`${code} ${json.request_id}`);
console.warn(method, path, code, json.error?.how_to_fix, json.request_id);
return json;
}
}
async function reply(to, windowOpen, body, inReplyTo) {
if (windowOpen) {
const sent = await api("POST", "/messages", { to, type: "text", text: { body } }, `text-${inReplyTo}`);
if (sent.error?.code !== "outside_24h_window") return sent;
}
return api("POST", "/messages", { to, type: "template", template: FALLBACK }, `tpl-${inReplyTo}`);
}
async function handle(m) {
if (!["text", "interactive", "button"].includes(m.type)) return; // photos, voice notes ...: for the team
const contact = encodeURIComponent(m.from || m.from_user_id);
const text = m.interactive?.id || m.button?.payload || m.text || "";
const conv = await api("GET", `/conversations/${contact}`);
if (["human", "paused", "whatsapp_ai"].includes(conv.owner)) return; // someone else has this chat
await api("POST", "/messages/read", { message_id: m.message_id, typing: true });
const open = conv.window_open !== false;
if (HUMAN.test(text)) {
await api("PUT", `/conversations/${contact}/owner`, {
owner: "human", reason: "customer asked for a person", summary: text.slice(0, 300), until_minutes: 240 });
return reply(m.from || m.from_user_id, open, "Thanks! A person from our team will answer you here soon.", m.message_id);
}
const hit = ANSWERS.find(([pattern]) => pattern.test(text));
return reply(m.from || m.from_user_id, open, hit ? hit[1] : MENU, m.message_id);
}
const app = express();
app.post("/webhook", express.raw({ type: "application/json" }), async (req, res) => {
if (!verify(req.body, req.get("X-App2email-Signature"), WEBHOOK_SECRET)) return res.sendStatus(401);
const event = JSON.parse(req.body);
if (event.test) { console.log("test event ok:", event.type); return res.sendStatus(200); }
if (event.type !== "message.received" || done.has(event.id)) return res.sendStatus(200);
try {
await handle(event.data);
done.add(event.id); // only after it worked: a failed event comes again
res.sendStatus(200);
} catch (err) {
console.error("not handled, app2email will send it again:", event.id, err.message);
res.sendStatus(503);
}
});
app.listen(PORT, () => console.log(`bot on http://localhost:${PORT}/webhook`));# Python 3.9 or newer. pip install flask requests then flask --app bot run --port 3000
import hashlib, hmac, json, os, re, time
import requests
from flask import Flask, request
NUMBER, API_KEY, SECRET = os.environ["NUMBER"], os.environ["API_KEY"], os.environ["WEBHOOK_SECRET"]
API = f"https://api.app2email.com/v1/{NUMBER}"
FALLBACK = {"name": "hello_world", "language": {"code": "en_US"}} # an approved template without placeholders
RETRY_LATER = {"rate_limited", "whatsapp_rate_limit", "too_many_messages_to_recipient"}
done = set() # handled event ids: use a database table or Redis in production
ANSWERS = [
(re.compile(r"\b(hours?|open|opening|closed)\b", re.I), "We are open Monday to Friday, 9 am to 5 pm, and Saturday 10 am to 2 pm."),
(re.compile(r"\b(prices?|cost|how much)\b", re.I), "A standard service is $49, an express service $79. Full list: https://example.com/prices"),
]
HUMAN = re.compile(r"\b(human|person|someone|staff)\b", re.I)
MENU = "Hi! I can tell you our opening hours or our prices. Type 'person' to talk to the team."
def verify(raw: bytes, header: str, secret: str, tolerance: int = 300) -> bool:
t = re.search(r"(?:^|,)\s*t=(\d+)", header or "")
v1 = re.findall(r"(?:^|,)\s*v1=([0-9a-f]+)", header or "") # two during a secret change
if not t or not v1 or abs(time.time() - int(t.group(1))) > tolerance:
return False
expected = hmac.new(secret.encode(), t.group(1).encode() + b"." + raw, hashlib.sha256).hexdigest()
return any(hmac.compare_digest(v, expected) for v in v1)
def api(method, path, body=None, idempotency_key=None):
headers = {"Authorization": f"Bearer {API_KEY}"}
if idempotency_key:
headers["Idempotency-Key"] = idempotency_key
for attempt in (1, 2, 3):
res = requests.request(method, API + path, json=body, headers=headers, timeout=4)
data = res.json()
if res.ok:
return data
code = data.get("error", {}).get("code")
wait = int(res.headers.get("Retry-After", "1"))
if code == "rate_limited" and attempt < 3 and wait <= 3:
time.sleep(wait)
continue
if res.status_code >= 500 or code in RETRY_LATER:
raise RuntimeError(f"{code} {data.get('request_id')}")
print("not done:", method, path, code, data.get("error", {}).get("how_to_fix"), data.get("request_id"))
return data
def reply(to, window_open, body, in_reply_to):
if window_open:
sent = api("POST", "/messages", {"to": to, "type": "text", "text": {"body": body}}, f"text-{in_reply_to}")
if sent.get("error", {}).get("code") != "outside_24h_window":
return sent
return api("POST", "/messages", {"to": to, "type": "template", "template": FALLBACK}, f"tpl-{in_reply_to}")
def handle(m):
if m.get("type") not in ("text", "interactive", "button"):
return # photos, voice notes ...: for the team
contact = m.get("from") or m.get("from_user_id")
text = (m.get("interactive") or {}).get("id") or (m.get("button") or {}).get("payload") or m.get("text") or ""
conv = api("GET", f"/conversations/{contact}")
if conv.get("owner") in ("human", "paused", "whatsapp_ai"):
return # someone else has this chat
api("POST", "/messages/read", {"message_id": m["message_id"], "typing": True})
window_open = conv.get("window_open") is not False
if HUMAN.search(text):
api("PUT", f"/conversations/{contact}/owner", {"owner": "human", "reason": "customer asked for a person",
"summary": text[:300], "until_minutes": 240})
return reply(contact, window_open, "Thanks! A person from our team will answer you here soon.", m["message_id"])
answer = next((a for pattern, a in ANSWERS if pattern.search(text)), MENU)
return reply(contact, window_open, answer, m["message_id"])
app = Flask(__name__)
@app.post("/webhook")
def webhook():
raw = request.get_data()
if not verify(raw, request.headers.get("X-App2email-Signature"), SECRET):
return "bad signature", 401
event = json.loads(raw)
if event.get("test"):
print("test event ok:", event["type"])
return "", 200
if event["type"] != "message.received" or event["id"] in done:
return "", 200
try:
handle(event["data"])
except Exception as err:
print("not handled, app2email will send it again:", event["id"], err)
return "", 503
done.add(event["id"]) # only after it worked: a failed event comes again
return "", 200为什么这样设计:
express.raw、request.get_data())。Idempotency-Key 确保即使第一次尝试已经走到了发送这一步,重试也绝不会把同一条回复发送两次。rate_limited 会在请求内部等待(最多 3 秒,以便遵守 10 秒的限制)。更长的情况交回给 app2email 的重试机制。how_to_fix 和 request_id 记录下来,事件则返回 200,这样它不会一直回来。FALLBACK 是 hello_world,因为即时沙盒里有它。在您自己的号码上,请填入您某个已批准模板的名称和语言(GET /templates 会列出它们,每个都附带完整的 example_request)。message.status:sent,然后是 delivered,再是 read。{
"id": "evt_Xq3k9m2Lw8Rt5Yp1Zs02",
"type": "message.status",
"created": "2026-11-06T01:00:03.000Z",
"number": "4976659348270",
"data": {
"message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=",
"to": "61412345678",
"status": "delivered",
"timestamp": "2026-11-06T01:00:03.000Z",
"sent_by": "api",
"whatsapp_status": "delivered"
}
}失败的回复会以带有 status: "failed" 和 error 对象的 message.status 到达(code 是 Meta 的代码,error_code 是 app2email 的代码),同时也会以 message.failed 到达。
当客户写下“can I talk to a person?”时,他们会收到“A person from our team will answer you here soon”,而您的 webhook 会收到:
{
"id": "evt_Xq3k9m2Lw8Rt5Yp1Zs03",
"type": "conversation.owner_changed",
"created": "2026-11-06T01:02:00.000Z",
"number": "4976659348270",
"data": {
"contact": "61412345678",
"owner": "human",
"previous_owner": "",
"reason": "customer asked for a person",
"summary": "can I talk to a person?",
"until": "2026-11-06T05:02:00.000Z",
"set_by": "api",
"timestamp": "2026-11-06T01:02:00.000Z"
}
}真人可以在收件箱中、通过电子邮件或通过 API 回复。机器人在下一条消息时会看到负责人是 human,并保持沉默。
交还给机器人:until_minutes 之后,负责人会自动恢复为空。真人也可以更早地用 PUT /conversations/{contact}/owner 和 {"owner": ""} 把对话交还,这会再次发送 conversation.owner_changed。真人负责对话期间,不要在代码中把对话收回。
在客户最后一条消息之后的 24 小时内,WhatsApp 允许您发送自由格式的消息(文本、图片、按钮)。app2email 会提前 15 分钟停止;window_closes_at 是准确时间。在那之后,只有已批准的模板才能重新开启对话。
几秒内就回复的机器人几乎总是在窗口之内。事件延迟送达时就要注意了:重试会持续大约 32 小时,所以对昨天消息的回复可能需要用模板。机器人在写入前会检查 window_open,如果发送返回 422 outside_24h_window,仍然会改用模板。
Do Not Call 名单不适用于自由格式的回复,因为是客户先给您写的信。例外情况:如果他们最后一条消息就是退订本身,那么回复会返回 403 recipient_opted_out,直到他们再次写信。
校验每个事件。 头 X-App2email-Signature 的格式是 t=<unix seconds>,v1=<hex>:以 webhook 的密钥(whsec_...,包含前缀)为密钥,对文本 t、一个点和原始请求体计算 HMAC-SHA256。检查每个 v1=(在使用 keep_old_for_hours 执行 POST /webhooks/{id}/rotate-secret 之后的一段时间内会有两个),用恒定时间比较,并拒绝早于 5 分钟的 t。如果您的代码已经校验 Meta 的 webhook,那么 X-Hub-Signature-256(sha256= 加上原始请求体的 HMAC-SHA256,与 Meta 的签名方式相同)也在其中;它不含时间,并且只使用当前密钥。
快速响应。 在 10 秒内返回 2xx。不会跟随重定向。对于耗时的工作(数据库、AI 模型),请先存储事件,返回 200,再从会自行重试的队列中处理。
去重。 请把每个已处理事件的事件 id(X-App2email-Delivery)至少保留两天:重试会持续大约 32 小时。当您运行多个进程时,请把它保存在数据库或 Redis 中,而不是内存里。事件也可能乱序到达:请使用 data.timestamp,而不是它们到达的顺序。
每条回复只发送一次。 给每个 POST /messages 一个由客户的 message_id 构建的 Idempotency-Key。24 小时内相同的密钥和相同的请求体:会返回第一次的响应,并带有 Idempotent-Replayed: true。相同的密钥、不同的请求体:422 idempotency_key_reused。409 idempotency_request_in_progress:请等待,并用同一个密钥重试。
遵守限制。 每个响应都带有 X-RateLimit-Limit、X-RateLimit-Remaining、X-RateLimit-Reset(距离恢复满额的秒数)和 X-RateLimit-Policy;GET /me 会显示您密钥的 limits。超出限制时:429 rate_limited,带有 Retry-After 和 error.retry_after_seconds。WhatsApp 自己的限制(429 whatsapp_rate_limit、too_many_messages_to_recipient)需要等待几分钟,而不是几秒。429 monthly_limit_reached 和 daily_cap_reached 现在不值得重试(retry_after_seconds 会告诉您直到何时):请通知真人。
保持 webhook 开启。 如果连续 20 个事件在最初 4 次尝试内都没有送达(时间跨度至少 24 小时),app2email 会关闭该 webhook。GET /webhooks/{id}/deliveries?status=failed 会显示哪些失败以及原因;带有 {"active": true} 的 PATCH /webhooks/{id} 会重新开启它,POST /webhooks/{id}/deliveries/{event_id}/redeliver 会重新发送一个事件。
真人负责对话时不要打扰客户。 在每次回复之前检查 owner(human、paused 和 whatsapp_ai 表示:不要回复),并在客户提出要求时转交给真人。
每个号码只有一个回复者。 号码的自动回复(新联系人收到的第一条回复)、对话自动化和 AI 回复也会看到每一条消息。请检查控制台,避免新联系人收到两条第一回复。
把客户的文本当作数据。 它是由客户写的。绝不要把它当作命令运行,如果把它传给 AI 模型,请让它与您的指令分开。
最小权限。 机器人的密钥只需要 messages:send 和 messages:read。把它保存在服务器上,绝不放进网页或日志。密钥可以限制在您服务器的 IP 地址范围内、设置每日上限,或设为到期失效。
| 您看到的现象 | 原因 | 解决方法 |
|---|---|---|
| 您的机器人对每个事件都返回 401 | 签名不匹配 | 使用这个 webhook 的 whsec_... 密钥并带上它的前缀;检查原始请求体,要在任何 JSON 解析器处理它之前;检查服务器时钟(t 必须在 5 分钟之内) |
401 missing_api_key、invalid_api_key、api_key_revoked | 没有密钥、密钥错误或密钥已过时 | 发送 Authorization: Bearer YOUR_API_KEY,使用 API 密钥页面上列出的密钥,并在 URL 中使用该密钥对应的号码 |
403 insufficient_scope | 密钥缺少某项权限(details.required_scope) | 创建具有 messages:send 和 messages:read 的密钥(注册 webhook 还需要 webhooks:manage) |
403 plan_not_allowed、service_not_live | 没有付费套餐,或服务已暂停 | 选择套餐;已暂停的服务可在“设置”页面通过“Go Live”恢复上线 |
422 invalid_webhook_url | URL 不是公网 https 地址 | 使用您隧道或服务器的 https 地址,并带上路径(/webhook) |
409 webhook_url_in_use | 该号码的另一个 webhook 已使用这个 URL | 用 PATCH 修改那个 webhook,或删除其中一个 |
400 too_many_webhooks | 该号码已有 5 个 webhook | 删除一个不再使用的 |
422 outside_24h_window | 客户上次写信是在 24 小时之前 | 发送已批准的模板 |
404 template_not_found、422 template_not_approved | 备用模板的名称或语言有误,或者尚未获得批准 | 从 GET /templates 中选择状态为 APPROVED 的模板 |
422 template_parameters_invalid | 备用模板含有占位符 | 使用不含占位符的模板,或按其 example_request 的方式填写 |
403 recipient_opted_out | 客户最后一条消息就是退订 | 在他们再次写信之前不要回复 |
429 rate_limited | 该密钥的调用过多 | 等待 Retry-After 秒,然后重试 |
429 whatsapp_rate_limit、too_many_messages_to_recipient | WhatsApp 的限制 | 退避几分钟 |
429 too_many_tests | 一小时内超过 30 个测试事件 | 等待,或者改用您手机发出的消息来测试 |
403 not_in_instant_sandbox | 演示号码没有这个调用(例如 webhook) | 在演示号码上改用 GET /events,或使用您自己号码上的沙盒密钥 |
| 完全没有事件到达 | webhook 已被关闭,或隧道的地址变了 | GET /webhooks 会显示 active 和最近一次投递;用 PATCH 设置新的 url 或 {"active": true} |
每个响应都带有 request_id。GET /requests/{id} 会显示为它记录的内容,support@app2email.com 也能查到它。所有错误代码请见错误。
ai.answered 和 ai.handover。只有在对话没有负责人,且没有应用或自动化回复过时,它才会回复客户,所以请为每个号码选择一个回复者。请参阅 AI 回复设置。https://api.app2email.com/mcp 把同样的调用作为工具提供(send_text、mark_read、get_conversation、set_conversation_owner、list_events、wait_for_message 等)。请参阅用 MCP 让 AI 代理运行您的 WhatsApp 和 MCP。可以。POST https://api.app2email.com/v1/account/sandbox(不带密钥、不带请求体)会返回一个演示号码 12025550100 的即时沙盒密钥(a2es_...,有效期 7 天)。它的虚拟客户包括 Ava(12025550101,回复每一条消息)和 Eve(12025550105,要求找真人)。它支持 GET /conversations/{contact}、PUT /conversations/{contact}/owner、POST /messages 和 GET /events,所以机器人的逻辑可以在那里运行,而且它有用作备用的 hello_world 模板。它没有 webhook:请用 GET /events 读取事件(见下一个问题)。POST /messages/read 也不在其中;它会返回 403 not_in_instant_sandbox,机器人会记录下来并继续运行。不会有任何内容发到 WhatsApp。
可以:GET /events?wait=25(权限范围 messages:read)会保持响应,直到有事件到达,最多 25 秒。每个事件都与 webhook 收到的 JSON 相同,id 也相同。请保存响应中的 cursor,并在下次调用时作为 after 传入;跳过您已处理的 id,因为响应丢失后事件可能再次出现。types=message.received 只返回收到的消息。第一次调用会开启该号码的事件流;事件会保留 72 小时。
let after = "now";
for (;;) {
const page = await api("GET", `/events?wait=25&types=message.received&after=${after}`);
for (const event of page.events ?? []) if (!done.has(event.id)) { await handle(event.data); done.add(event.id); }
after = page.cursor ?? after;
}可以,在 24 小时窗口之内。发送 "type": "interactive",带有最多 3 个回复按钮,或最多 10 行的列表。给按钮使用机器人已经能理解的 id,点击会以 message.received 到达,其中 type 为 interactive,并带有 interactive.id:
{
"to": "61412345678",
"type": "interactive",
"interactive": {
"type": "button",
"body": { "text": "What would you like to know?" },
"action": {
"buttons": [
{ "type": "reply", "reply": { "id": "hours", "title": "Opening hours" } },
{ "type": "reply", "reply": { "id": "prices", "title": "Prices" } },
{ "type": "reply", "reply": { "id": "person", "title": "Talk to a person" } }
]
}
}
}机器人发送的每条回复都算作您 app2email 套餐中的一条消息。标记为已读和输入指示器是免费的。Meta 直接向您收费:窗口内的回复属于服务消息(每个号码每月前 1,000 条免费),模板按每条消息收费。GET /usage 会显示本月已用和剩余的数量,并在 meta_pricing 中按 Meta 的类别给出明细。
它们会以 message.received 到达,type 为 image、audio、document 等,并带有 media_url:app2email 会保留一份副本,由 GET /media/{message_id} 提供。上面的机器人把它们留给您的团队处理;您也可以在其中一条到达时立刻转交对话。
可以在控制台的收件箱中、通过电子邮件(开启邮件转发时)或通过 API 回复。当 until_minutes 用完时,对话会回到机器人手中,也可以更早地用 PUT /conversations/{contact}/owner 和 {"owner": ""} 交还。
可以:带有 "format": "meta" 的 webhook 会把来自 WhatsApp 的内容作为 Meta 自己的请求体(entry[].changes[])收到,签名方式相同。app2email 自己的事件,例如 conversation.owner_changed,保留 app2email 的信封格式。本指南使用默认的 app2email 格式。
WhatsApp 正在转向使用带有业务范围用户 ID 的用户名(类似 AU.1234567890123456)。这样的事件可能带有 from_user_id 而没有 from。把这个 id 放在 to 中:它在任何可以用号码的地方都有效,包括 /conversations/{contact}。上面的机器人已经这样做了。