创建 utility 模板,获得 Meta 批准,在订单发货或预约临近时发送给单个客户,并跟踪送达和已读状态。
订单发货或预约临近时,您的系统只需调用一次 API,客户就会收到来自您企业的 WhatsApp 消息:“John 您好,您的订单 #1234 已发货。”
随着消息的推进,您会通过 webhook 或查询 API 得到它的状态(已发送、已送达、已读,或失败及原因)。这条消息也会显示在 app2email 活动日志和对话中。
WhatsApp 只允许企业在客户最后一次给您的号码发消息之后的 24 小时内发送自己的自由文本。app2email 为保险起见会提前 15 分钟停止。发货更新或预约提醒通常在客户上次写信的几天之后才发出,所以普通文本消息会被拒绝,并返回 422 outside_24h_window。
模板 是经 Meta 审核并批准的消息文本。它可以随时发送,占位符({{1}}、{{2}}……)中填入您自己的值。
模板有类别。订单、配送、账户和预约更新属于 UTILITY。促销属于 MARKETING。最终类别由 Meta 自己决定,所以请让 utility 模板不含优惠和销售措辞。
whatsapp_payment_issue)。| 权限范围 | 在本指南中的用途 |
|---|---|
templates:manage | 创建和编辑模板(POST /templates、PATCH /templates/{name}) |
messages:read | 读取模板的状态(GET /templates/{name})和消息的状态(GET /messages/{message_id}) |
messages:send | 发送通知(POST /messages) |
webhooks:manage | 添加接收状态事件的 webhook(POST /webhooks) |
默认密钥(在密钥有权限设置之前创建的)没有 templates:manage。请创建一个带有该权限范围的密钥,或使用完全访问(*)。GET /v1/YOUR_NUMBER/me 会显示您当前密钥的权限范围。
先试一试。 您自己号码上的 沙盒密钥(在 API 密钥页面创建的带有沙盒标记的密钥)会真实运行所有检查,但不会向 WhatsApp 发送任何内容。响应带有 "sandbox": true,消息 ID 以 wamid.SANDBOX. 开头,已发送、已送达和已读的 message.status 事件仍会送达。沙盒密钥不能创建模板(403 sandbox_key),所以请用普通密钥创建模板。
完全没有账户时,POST https://api.app2email.com/v1/account/sandbox(不带密钥、不带请求体),或 Management MCP 服务器的 create_sandbox 工具,会给您一个演示号码 12025550100 的 即时沙盒密钥。它有 GET /templates 和 POST /messages,所以您可以把演示号码的某个模板发给它的虚拟客户:12025550101 会回复,12025550103 会失败。请参阅沙盒。
发送带编号占位符的文本,并在 example 中为每个占位符提供一个示例值。Meta 的审核人员会阅读这些示例。名称可以使用小写字母、数字和下划线。
curl -s https://api.app2email.com/v1/YOUR_NUMBER/templates \
-H "Authorization: Bearer $A2E_KEY" \
-H "Content-Type: application/json" \
-d '{
"name": "order_update",
"language": "en",
"category": "UTILITY",
"components": [
{
"type": "BODY",
"text": "Hi {{1}}, your order {{2}} has shipped.",
"example": { "body_text": [["John", "#1234"]] }
}
]
}'const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/templates", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.A2E_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
name: "order_update",
language: "en",
category: "UTILITY",
components: [
{
type: "BODY",
text: "Hi {{1}}, your order {{2}} has shipped.",
example: { body_text: [["John", "#1234"]] },
},
],
}),
});
console.log(res.status, await res.json());import os, requests
res = requests.post(
"https://api.app2email.com/v1/YOUR_NUMBER/templates",
headers={"Authorization": f"Bearer {os.environ['A2E_KEY']}"},
json={
"name": "order_update",
"language": "en",
"category": "UTILITY",
"components": [
{
"type": "BODY",
"text": "Hi {{1}}, your order {{2}} has shipped.",
"example": {"body_text": [["John", "#1234"]]},
}
],
},
)
print(res.status_code, res.json())您会得到的响应(HTTP 201):模板已提交给 Meta 审核。
{
"success": true,
"request_id": "c3ppl",
"template": {
"id": "2234567890",
"name": "order_update",
"language": "en",
"category": "UTILITY",
"status": "PENDING"
},
"note": "Submitted to WhatsApp for review (minutes to a day). You get a template.status_changed webhook event with the result, or GET https://api.app2email.com/v1/4976659348270/templates/order_update."
}对于预约,请用同样的方式再创建一个模板,例如 appointment_reminder,文本为 Hi {{1}}, this is a reminder of your {{2}} tomorrow at {{3}}. Reply to this message if you need to change it.,示例值为 [["Ava", "haircut", "10:30"]]。
模板属于 WhatsApp Business Account:该账户下的每个号码都可以使用它们。
由 Meta 编写的跟踪按钮。 Meta 的模板库有现成的 utility 文本:GET /template-library?topic=ORDER_MANAGEMENT&usecase=SHIPMENT_CONFIRMATION 会列出它们。创建时用 library_template_name 代替 components,并给出其按钮的网站:
{
"name": "my_delivery_update",
"language": "en_US",
"category": "UTILITY",
"library_template_name": "delivery_update_1",
"library_template_button_inputs": [
{
"type": "URL",
"url": {
"base_url": "https://www.example.com/{{1}}",
"url_suffix_example": "https://www.example.com/order/1234"
}
}
]
}审核需要几分钟到一天。您可以通过两种方式得知结果。
template.status_changed webhook 事件(发送给该 WhatsApp Business Account 的每个号码):
{
"id": "evt_Xq3k9m2Lw8Rt5Yp1Zs01",
"type": "template.status_changed",
"created": "2026-11-06T01:00:00.000Z",
"number": "4976659348270",
"data": {
"template": { "name": "order_update", "language": "en", "id": "1234567890123456" },
"status": "APPROVED",
"can_send": true,
"timestamp": "2026-11-06T01:00:00.000Z"
}
}或者主动查询:GET /v1/YOUR_NUMBER/templates/order_update(权限范围 messages:read)。它是从 WhatsApp 读取的,而不是从缓存读取,所以刚刚改变的状态也能看到。
curl -s https://api.app2email.com/v1/YOUR_NUMBER/templates/order_update \
-H "Authorization: Bearer $A2E_KEY"const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/templates/order_update", {
headers: { Authorization: `Bearer ${process.env.A2E_KEY}` },
});
const { versions } = await res.json();
console.log(versions.map((v) => [v.language, v.status, v.rejected_reason]));res = requests.get(
"https://api.app2email.com/v1/YOUR_NUMBER/templates/order_update",
headers={"Authorization": f"Bearer {os.environ['A2E_KEY']}"},
)
for v in res.json()["versions"]:
print(v["language"], v["status"], v.get("rejected_reason"))您会得到的响应: 每种语言在 versions 中有一个条目,包含 status、can_send、它 needs 哪些值,以及一个完整的 example_request,您改好数值后即可发送。
{
"success": true,
"request_id": "k7qtm",
"name": "order_update",
"versions": [
{
"id": "1234567890",
"name": "order_update",
"language": "en",
"category": "UTILITY",
"status": "APPROVED",
"can_send": true,
"needs": { "body": "2 text values" },
"example_request": {
"to": "61412345678",
"type": "template",
"template": {
"name": "order_update",
"language": { "code": "en" },
"components": [
{
"type": "body",
"parameters": [
{ "type": "text", "text": "John" },
{ "type": "text", "text": "#1234" }
]
}
]
}
}
}
]
}被拒绝时是这样的:status 为 REJECTED,can_send 为 false,并且 rejected_reason(在 GET /templates/{name} 中)或 reason(在 template.status_changed 事件中)会说明原因。请修改文本,并用 PATCH /v1/YOUR_NUMBER/templates/order_update 和新的 components 重新提交。只有 APPROVED、REJECTED 或 PAUSED 的模板可以编辑,已批准的模板每天最多编辑一次,30 天内最多 10 次。
如果 Meta 把模板放进了另一个类别,GET /templates/{name} 中的 previous_category 和 correct_category 会显示出来。
每个系统一个 webhook 就够了:号码的每个 webhook 都会收到每个事件,您自己挑选要处理的类型。每个号码最多 5 个。权限范围 webhooks:manage。
curl -s https://api.app2email.com/v1/YOUR_NUMBER/webhooks \
-H "Authorization: Bearer $A2E_KEY" \
-H "Content-Type: application/json" \
-d '{ "url": "https://hooks.example.com/app2email" }'const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/webhooks", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.A2E_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ url: "https://hooks.example.com/app2email" }),
});
const { webhook } = await res.json();
console.log(webhook.id, webhook.secret); // store the secret: it signs every eventres = requests.post(
"https://api.app2email.com/v1/YOUR_NUMBER/webhooks",
headers={"Authorization": f"Bearer {os.environ['A2E_KEY']}"},
json={"url": "https://hooks.example.com/app2email"},
)
webhook = res.json()["webhook"]
print(webhook["id"], webhook["secret"]) # store the secret: it signs every event您会得到的响应:webhook,包含它的 id 和它的 secret(whsec_...)。请把密钥保存在您的服务器上。
还没有公网地址?GET /v1/YOUR_NUMBER/events?wait=25 可以获取同样的事件。请保存响应中的 cursor,并在下次调用时作为 after 传入。
把模板发送到客户的号码(国家代码在前,只写数字),每个占位符按顺序提供一个值。
两个额外设置可以让它适合生产环境:
Idempotency-Key 头:只属于这条通知的值,例如您的订单号加上事件名。如果您的任务运行了两次,或者超时后重试,消息不会被再次发送。callback_data:您自己的简短引用(最多 512 个字符)。它会作为 data.callback_data 出现在这条消息的 message.status 事件中,所以您不必先保存消息 ID,就能把状态与订单对应起来。curl -s https://api.app2email.com/v1/YOUR_NUMBER/messages \
-H "Authorization: Bearer $A2E_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: order-1234-shipped" \
-d '{
"to": "61412345678",
"type": "template",
"template": {
"name": "order_update",
"language": { "code": "en" },
"components": [
{
"type": "body",
"parameters": [
{ "type": "text", "text": "John" },
{ "type": "text", "text": "#1234" }
]
}
]
},
"callback_data": "order-1234"
}'async function sendShipped(order) {
const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/messages", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.A2E_KEY}`,
"Content-Type": "application/json",
"Idempotency-Key": `order-${order.id}-shipped`,
},
body: JSON.stringify({
to: order.phone, // "61412345678"
type: "template",
template: {
name: "order_update",
language: { code: "en" },
components: [
{
type: "body",
parameters: [
{ type: "text", text: order.firstName },
{ type: "text", text: `#${order.id}` },
],
},
],
},
callback_data: `order-${order.id}`,
}),
});
const body = await res.json();
if (!res.ok) throw new Error(`${body.error.code}: ${body.error.how_to_fix}`);
return body.message_id; // keep it with the order
}def send_shipped(order):
res = requests.post(
"https://api.app2email.com/v1/YOUR_NUMBER/messages",
headers={
"Authorization": f"Bearer {os.environ['A2E_KEY']}",
"Idempotency-Key": f"order-{order['id']}-shipped",
},
json={
"to": order["phone"], # "61412345678"
"type": "template",
"template": {
"name": "order_update",
"language": {"code": "en"},
"components": [
{
"type": "body",
"parameters": [
{"type": "text", "text": order["first_name"]},
{"type": "text", "text": f"#{order['id']}"},
],
}
],
},
"callback_data": f"order-{order['id']}",
},
)
body = res.json()
if not res.ok:
raise RuntimeError(f"{body['error']['code']}: {body['error']['how_to_fix']}")
return body["message_id"] # keep it with the order您会得到的响应(HTTP 200):WhatsApp 已接受这条消息。text 是客户看到的消息内容。
{
"success": true,
"request_id": "kxrkf",
"message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=",
"status": "accepted",
"from": "4976659348270",
"to": "61412345678",
"template": { "name": "order_update", "language": "en", "category": "UTILITY" },
"text": "Hi John, your order #1234 has shipped.",
"conversation_url": "https://www.app2email.com/conversation/61412345678_4976659348270_...",
"note": "accepted by WhatsApp. delivery and read status appear in your app2email Activity Log (WhatsApp sent).",
"contacts": [{ "input": "61412345678", "wa_id": "61412345678" }]
}在开发时,请在请求体中加入 "dry_run": true。所有内容都会像真实发送一样被检查(模板值、号码、Do Not Call 名单、月度限额),响应会显示确切的 WhatsApp 消息。不会发送、记录或计数。
调用相同,只是使用 appointment_reminder 模板。您可以现在就从自己的每日任务中发送,也可以用 send_at(带时区的 ISO 8601,1 分钟到 29 天之后)把时间交给 app2email:
{
"to": "61412345678",
"type": "template",
"template": {
"name": "appointment_reminder",
"language": { "code": "en" },
"components": [
{
"type": "body",
"parameters": [
{ "type": "text", "text": "Ava" },
{ "type": "text", "text": "haircut" },
{ "type": "text", "text": "10:30" }
]
}
]
},
"send_at": "2026-12-01T09:00:00+11:00",
"callback_data": "appt-5521"
}定时发送会返回 HTTP 202,带有 status: "scheduled"、scheduled_for 和一个群发 code。所有内容会立即检查,Do Not Call 名单和月度限额在到时间时会再次检查。如果预约被取消,请用 POST /v1/YOUR_NUMBER/broadcasts/{code}/cancel 取消这条消息。
通过 app2email 自己的 Book-and-Pay 创建的预约,无需任何代码就会收到确认和提醒:它会创建自己的 utility 模板,并在窗口关闭时使用它们。请参阅WhatsApp 上的预约预订。
如果模板是带有 文档页眉 获批的,请随每条消息发送 PDF:可以是 app2email 下载的 link,也可以是带有 filename 的 base64 data,或者是来自 POST /media 的媒体 id。省略页眉则会发送模板自带的示例文档。文档最大 100 MB。
{
"to": "61412345678",
"type": "template",
"template": {
"name": "invoice_ready",
"language": { "code": "en" },
"components": [
{
"type": "header",
"parameters": [
{
"type": "document",
"document": { "data": "JVBERi0xLjQKJ...", "filename": "invoice-1234.pdf" }
}
]
},
{
"type": "body",
"parameters": [{ "type": "text", "text": "#1234" }]
}
]
}
}如果模板有 带占位符的 URL 按钮(如上面的模板库那个),请把地址的末尾部分作为按钮组件提供。index 是按钮的位置,从 "0" 开始:
{
"type": "button",
"sub_type": "url",
"index": "0",
"parameters": [{ "type": "text", "text": "order/1234" }]
}不确定模板需要什么?GET /templates/{name} 中的 needs 和 example_request 会列出每个页眉、正文和按钮的值。
客户会看到一条来自您企业名称的消息,内容是模板文本并填入了您的值,如果模板带有文档或按钮,也会一并显示。如果他们回复,24 小时窗口就会开启,您可以用普通消息回复。
在您这一侧,随着消息推进,会收到 message.status 事件。status 是 sent、delivered、read 或 failed(语音消息还有 played,另外还有 clicked 和 deleted)。
{
"id": "evt_Xq3k9m2Lw8Rt5Yp1Zs01",
"type": "message.status",
"created": "2026-11-06T01:00:00.000Z",
"number": "4976659348270",
"data": {
"message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=",
"to": "61412345678",
"status": "delivered",
"timestamp": "2026-11-06T01:00:00.000Z",
"sent_by": "api",
"whatsapp_status": "delivered",
"recipient_user_id": "AU.1234567890123456",
"pricing": { "billable": true, "pricing_model": "PMP", "type": "regular", "category": "utility" },
"callback_data": "order-1234"
}
}无法送达的消息还会以 message.failed 事件到达,数据相同,并带有一个 error,其中包含 Meta 的 code、app2email 的 error_code 和 how_to_fix:
{
"id": "evt_Xq3k9m2Lw8Rt5Yp1Zs01",
"type": "message.failed",
"created": "2026-11-06T01:00:00.000Z",
"number": "4976659348270",
"data": {
"message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=",
"to": "61412345678",
"status": "failed",
"timestamp": "2026-11-06T01:00:00.000Z",
"error": {
"code": 131026,
"message": "Message Undeliverable.",
"title": "Message undeliverable",
"details": "Message Undeliverable.",
"error_code": "recipient_unreachable",
"how_to_fix": "WhatsApp could not deliver to this number. Check it is a WhatsApp number written with its country code (digits only, eg 61412345678), and that the person uses an up to date WhatsApp.",
"is_retriable": false
},
"sent_by": "api",
"whatsapp_status": "failed"
}
}事件可能乱序到达,所以 read 可能先于它的 delivered 到来。请为每个 message_id 保留最靠后的状态,不要退回。
或者主动查询状态: 使用 GET /v1/YOUR_NUMBER/messages/{message_id}(权限范围 messages:read;请对 ID 进行 URL 编码)。它适用于从该号码发送的任何消息,并包含状态、每一步的时间、失败原因,以及客户的回复或按钮点击。
curl -s "https://api.app2email.com/v1/YOUR_NUMBER/messages/wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA%3D" \
-H "Authorization: Bearer $A2E_KEY"const id = encodeURIComponent(messageId);
const res = await fetch(`https://api.app2email.com/v1/YOUR_NUMBER/messages/${id}`, {
headers: { Authorization: `Bearer ${process.env.A2E_KEY}` },
});
const msg = await res.json();
console.log(msg.status, msg.times);from urllib.parse import quote
res = requests.get(
f"https://api.app2email.com/v1/YOUR_NUMBER/messages/{quote(message_id, safe='')}",
headers={"Authorization": f"Bearer {os.environ['A2E_KEY']}"},
)
msg = res.json()
print(msg["status"], msg.get("times"))您会得到的响应: status 是 accepted、sent、delivered、read、failed、deleted、queued 或 unknown 之一。尚未到达的步骤不会出现在 times 中。
{
"success": true,
"request_id": "p4n8w",
"message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=",
"to": "61412345678",
"status": "read",
"sent_by": "api",
"text": "Hi John, your order #1234 has shipped.",
"times": {
"submitted": "2026-11-06T01:00:00Z",
"accepted": "2026-11-06T01:00:01Z",
"sent": "2026-11-06T01:00:02Z",
"delivered": "2026-11-06T01:00:04Z",
"read": "2026-11-06T01:12:40Z"
},
"conversation_url": "https://www.app2email.com/conversation/61412345678_4976659348270_..."
}如果要一次查看多条消息,GET /v1/YOUR_NUMBER/messages?status=failed&since=2026-11-06T00:00:00Z 会列出失败的消息,GET /v1/YOUR_NUMBER/stats?from=&to= 会给出某个时间段内的已发送、已送达、已读和失败数量。
app2email 收取固定的月度套餐费用;每条通知算作套餐中的一条消息,没有按条加价(定价)。Meta 也会对模板消息收费,直接从您 WhatsApp Business Account 上的付款方式扣款。价格取决于模板的类别和客户所在的国家,在大多数国家,utility 模板比营销模板便宜。这也是让订单和预约更新严格保持为纯信息类内容的又一个理由。状态事件中的 pricing 对象会显示 Meta 如何计算每条消息(billable、category),GET /v1/YOUR_NUMBER/usage 中的 meta_pricing 会按类别汇总当月数据并给出参考费用。开始之前如需估算,请使用 WhatsApp 定价计算器。
每个事件都带有头 X-App2email-Signature: t=<unix seconds>,v1=<hex>。v1 的值是 "<t>.<raw body>" 的 HMAC-SHA256,以 webhook 的密钥(whsec_...,包含前缀)为密钥。请检查每个 v1=(轮换之后旧密钥仍保留期间会有两个),对完全按收到时原样的原始请求体进行计算,并拒绝过旧的 t。X-Hub-Signature-256: sha256=<hex>(原始请求体的 HMAC-SHA256,仅使用当前密钥)也在其中,供为 Meta 的 webhook 编写的代码使用。
import crypto from "node:crypto";
import express from "express";
export function verifyWebhook(rawBody, header, secret, toleranceSeconds = 300) {
const t = /(?:^|,)\s*t=(\d+)/.exec(header ?? "")?.[1];
const v1 = [...(header ?? "").matchAll(/(?:^|,)\s*v1=([0-9a-f]+)/g)].map((m) => m[1]);
if (!t || v1.length === 0 || Math.abs(Date.now() / 1000 - Number(t)) > toleranceSeconds) return false;
const expected = crypto.createHmac("sha256", secret).update(t + ".").update(rawBody).digest("hex");
return v1.some((v) => v.length === expected.length && crypto.timingSafeEqual(Buffer.from(v), Buffer.from(expected)));
}
const app = express();
app.post("/app2email", express.raw({ type: "application/json" }), async (req, res) => {
if (!verifyWebhook(req.body, req.get("X-App2email-Signature"), process.env.WEBHOOK_SECRET)) return res.sendStatus(401);
const event = JSON.parse(req.body);
if (await alreadySeen(req.get("X-App2email-Delivery"))) return res.sendStatus(200); // a retry
if (event.type === "message.status") await saveStatus(event.data.callback_data, event.data.message_id, event.data.status, event.data.error);
if (event.type === "template.status_changed") await saveTemplateStatus(event.data.template, event.data.status, event.data.reason);
res.sendStatus(200); // within 10 seconds
});import hashlib, hmac, json, os, re, time
from flask import Flask, request
def verify_webhook(raw_body: 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 "")
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_body, hashlib.sha256).hexdigest()
return any(hmac.compare_digest(v, expected) for v in v1)
app = Flask(__name__)
@app.post("/app2email")
def app2email():
raw = request.get_data()
if not verify_webhook(raw, request.headers.get("X-App2email-Signature"), os.environ["WEBHOOK_SECRET"]):
return "", 401
if already_seen(request.headers.get("X-App2email-Delivery")):
return "", 200 # a retry
event = json.loads(raw)
if event["type"] == "message.status":
d = event["data"]
save_status(d.get("callback_data"), d["message_id"], d["status"], d.get("error"))
return "", 200 # within 10 seconds请在 10 秒内返回 2xx 状态。否则事件会在 10 秒、1 分钟、5 分钟、30 分钟、1、2、4、8 和 16 小时后再次发送。X-App2email-Delivery(事件的 id,evt_...)在每次重试时都相同,所以请保存它,并跳过已处理的事件。耗时的工作请在返回响应之后再做。
发送一个属于通知本身而不是属于这次尝试的 Idempotency-Key 头:order-1234-shipped、appt-5521-reminder。24 小时内用同一个密钥发出的相同请求不会再次发送;它会得到第一次的响应,并带有头 Idempotent-Replayed: true。
422 idempotency_key_reused。对不同的消息请使用新的密钥。409 idempotency_request_in_progress。请等待,并用同一个密钥重试。409 idempotency_request_interrupted。消息可能已经发出:在用新密钥发送之前,请检查 GET /messages?to=61412345678。密钥会保留 24 小时。对于几天之后可能再次运行的任务,还请在您自己的数据库中把 message_id 与订单事件一起保存,并在已有记录时不要发送。
每个响应都带有 X-RateLimit-Limit、X-RateLimit-Remaining、X-RateLimit-Reset(距离恢复满额的秒数)和 X-RateLimit-Policy。超出限制时,您会得到带有 Retry-After 头和 error.retry_after_seconds 的 429 rate_limited:等待相应的时间,然后再次发送同一个请求。
500、502、503 或超时:用逐步变长的等待时间重试几次,并使用同一个 Idempotency-Key。429 too_many_messages_to_recipient 或 429 whatsapp_rate_limit:WhatsApp 自己的限制。请退避几分钟,而不是几秒。429 monthly_limit_reached:套餐的消息已用完。在下一个计费月或升级之前不要重试。4xx:不要原样重试。请根据 error.code 判断,并按 how_to_fix 处理。error.is_retriable 会告诉您同一个请求之后是否可能成功。已批准的模板可以随时发出。普通文本、图片或文档只在客户最后一条消息之后的 24 小时内有效(app2email 会提前 15 分钟停止)。所以当客户回复“Can I change the address?”时,您可以用自由文本回复。GET /v1/YOUR_NUMBER/conversations/61412345678 会显示 window_open 和 window_closes_at。
Do Not Call 名单和 opt-in 规则(/settings/optin)适用于营销模板。Do Not Call 名单上的客户仍然可以收到订单更新之类的 utility 模板。
Meta 自己设定每个模板的类别,并且之后可以更改。如果某个模板变成 MARKETING,Do Not Call 名单和 opt-in 规则就会适用于它,并且按营销计费。请留意 template.status_changed 事件,并让促销内容远离您的通知文本。
WhatsApp 还会根据人们的反应对每个模板的质量打分。quality_score 为 RED 的模板可能被暂停,被暂停的模板会返回 422 template_paused。
每个错误都是包含 error.code、message、how_to_fix 和 request_id 的 JSON,您可以把 request_id 提供给支持团队。所有错误代码请见错误。
| 代码 | 出现时机 | 处理方法 |
|---|---|---|
403 insufficient_scope | 密钥缺少某项权限(details.required_scope) | 按需使用带有 templates:manage、messages:send、messages:read 或 webhooks:manage 的密钥 |
403 sandbox_key | 用沙盒密钥创建或编辑模板 | 模板操作请使用普通密钥 |
400 invalid_template_category | category 不是 MARKETING、UTILITY 或 AUTHENTICATION | 订单和预约更新请使用 UTILITY |
400 invalid_template_components | 某个组件没有 type(HEADER、BODY、FOOTER、BUTTONS) | 组件采用 WhatsApp 自己的格式;请与上面的示例对照 |
409 template_already_exists | 该名称和语言已存在(或正在被删除) | 使用另一个名称或语言 |
422 template_rejected | WhatsApp 没有接受该模板 | 按 whatsapp_error 所说修正后重新发送 |
404 template_not_found | 该名称与账户中的任何模板都不匹配 | 名称为小写且必须完全匹配;请查看 details.available_templates |
422 template_not_approved | 模板处于待审核、被拒绝、已暂停或已停用状态 | 等待批准,或修正它;请检查 GET /templates/{name} |
422 template_parameters_invalid | 值与模板不匹配 | 根据 details.problems 和 example_request 修正请求体 |
422 template_parameter_count_mismatch | Meta 错误 132000:值的数量不对 | 每个占位符发送一个值;请参阅 example_request |
422 template_paused | Meta 错误 132015:因质量低而被暂停 | 使用另一个模板,或编辑这个模板 |
422 outside_24h_window | 您在窗口之外发送了自由文本而不是模板 | 改为发送已批准的模板 |
403 whatsapp_payment_issue | Meta 错误 131042:Meta 无法向您的 WhatsApp 账户扣款 | 在 WhatsApp Manager 中添加或修复付款方式 |
422 recipient_unreachable | Meta 错误 131026 | 检查号码是否带有国家代码并且使用 WhatsApp |
422 media_download_failed | 无法下载文档的 link | 使用无需登录即可打开的链接,或发送 base64 data |
422 idempotency_key_reused | 相同的 Idempotency-Key,不同的请求体 | 对不同的消息使用新的密钥 |
429 rate_limited | 该密钥的调用过多 | 等待 Retry-After 秒,然后重试 |
429 monthly_limit_reached | 本月套餐的消息已用完 | 等待下一个计费月,或升级 |
404 message_not_found | 该号码没有发送过这个 ID 的消息 | 使用发送响应中的 message_id,并进行 URL 编码 |