在获得同意的前提下导入联系人,创建营销模板,发送给同意接收的人,按号码跟踪结果,并跟进回复或点击过的人。
您导入客户名单,Meta 批准一个营销模板,每批只需一次 API 调用即可发送。每位客户都会收到一条来自您企业名称的 WhatsApp 消息:“John 您好,我们的冬季大促从今天开始:全场 20% 折扣,至周日结束。”如果他们不想再收到优惠信息,只需回复 STOP,就再也不会收到。
app2email 只会发送给可以接收的人。Do Not Call 名单上的号码会被跳过,开启 opt-in 规则后,没有 opt-in 记录的人也会被跳过。您可以通过 webhook 事件、API、CSV 文件,以及活动日志中该群发的报告页面,得到每个号码的结果(已接受、已送达、已读、已回复、失败、已跳过)。
GET /compliance/export.csv 会把这三者放在一个文件里。403 whatsapp_payment_issue)。| 权限范围 | 在本指南中的用途 |
|---|---|
contacts:manage | 导入联系人,记录同意,保存细分群体(POST /contacts/import、POST /contacts/{identity}/consent、POST /segments) |
settings:manage | 开启 opt-in 规则并记录 opt-in(PUT /settings/optin、POST /optins) |
dnc:manage | Do Not Call 名单(POST /donotcall、GET /donotcall)和合规导出 |
templates:manage | 创建营销模板(POST /templates) |
messages:send | 发送群发,取消群发,发送跟进消息(POST /messages、POST /broadcasts/{code}/cancel、POST /broadcasts/{code}/retarget) |
messages:read | 模板状态、细分群体的联系人、群发结果、点击、用量、号码健康状况 |
webhooks:manage | 添加接收事件的 webhook(POST /webhooks) |
默认密钥(在密钥有权限设置之前创建的)只有 messages:send、messages:read、dnc:manage 和 webhooks:manage。请创建一个具有上述权限范围的密钥,或使用完全访问(*)。GET /v1/YOUR_NUMBER/me 会显示您当前密钥的权限范围。
先试一试。 您自己号码上的 沙盒密钥(在 API 密钥页面创建的带有沙盒标记的密钥)会真实检查每一次发送,但不会向 WhatsApp 发送任何内容。响应带有 "sandbox": true,消息 ID 以 wamid.SANDBOX. 开头,message.status 事件仍会送达。
请注意:使用沙盒密钥时,导入联系人、保存细分群体、opt-in 和 Do Not Call 名单 会改变您的真实数据。创建模板、PUT /settings/optin 和再营销(带 dry_run 的除外)会返回 403 sandbox_key。
完全没有账户时,POST https://api.app2email.com/v1/account/sandbox(不带密钥、不带请求体),或 Management MCP 服务器的 create_sandbox 工具,会给您一个演示号码 12025550100 的 即时沙盒密钥。它有 MARKETING 模板 weekend_offer,它的虚拟客户 12025550104 会回复 STOP:您会收到 contact.opted_out,之后再向他发送营销模板会返回 403 recipient_opted_out。该密钥只有少数几个调用(GET /templates、POST /messages、GET /events 等),所以本指南中的联系人和群发调用需要您自己号码上的密钥。请参阅沙盒。
发送带有表头行的 CSV 文件。app2email 识别的列有 phone(或 identity、number、mobile)、name(或 first_name + last_name)、tags(用 | 分隔)、consent_marketing(yes 或 no)、consent_source、consent_text、consent_evidence、consent_at 和 source。其他所有列都会成为自定义字段。号码国家代码在前,只写数字。每次调用最多 5000 行。
phone,name,first_name,tags,consent_marketing,consent_source,consent_text,consent_evidence,consent_at
61412345678,John Smith,John,vip|newsletter,yes,web form,"Yes, send me offers on WhatsApp",https://example.com/forms/123,2026-10-01T09:00:00Z
61498765432,Mary Jones,Mary,newsletter,yes,checkout,"Yes, send me offers on WhatsApp",order 5521,2026-10-12T02:30:00Zcurl -s https://api.app2email.com/v1/YOUR_NUMBER/contacts/import \
-H "Authorization: Bearer $A2E_KEY" \
-H "Content-Type: text/csv" \
--data-binary @contacts.csvimport { readFile } from "node:fs/promises";
const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/contacts/import", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.A2E_KEY}`,
"Content-Type": "text/csv",
},
body: await readFile("contacts.csv"),
});
console.log(res.status, await res.json());import os, requests
with open("contacts.csv", "rb") as f:
res = requests.post(
"https://api.app2email.com/v1/YOUR_NUMBER/contacts/import",
headers={
"Authorization": f"Bearer {os.environ['A2E_KEY']}",
"Content-Type": "text/csv",
},
data=f,
)
print(res.status_code, res.json())您会得到的响应: 已保存的行数,以及被跳过的行及其原因。其余的行都会被保存。
{
"success": true,
"request_id": "i2gka",
"rows": 120,
"saved": 118,
"created": 90,
"updated": 28,
"skipped": 2,
"errors": [
{
"row": 7,
"problem": "'0412' must be a WhatsApp number with country code, digits only (8 to 15 digits), or a business-scoped user id like 61.AbC123"
}
],
"note": "Rows with a problem were skipped (the first 50 are listed); the rest were saved."
}同一个调用也接受 application/json:一个采用 POST /contacts 格式的联系人列表。当某人之后表示同意时(网页表单、结账时的复选框),请把它连同证据记录在联系人上:
curl -s https://api.app2email.com/v1/YOUR_NUMBER/contacts/61412345678/consent \
-H "Authorization: Bearer $A2E_KEY" \
-H "Content-Type: application/json" \
-d '{
"marketing": true,
"source": "web form",
"text": "Yes, send me offers on WhatsApp",
"evidence": "https://example.com/forms/123"
}'只记录您确实拥有的同意。
opt-in 规则 是号码的一项设置。开启后,MARKETING 模板只会发送给有 opt-in 记录 的号码。其他人会被跳过,原因为 recipient_not_opted_in。utility 模板和回复不受影响。默认是关闭的。
opt-in 记录与联系人上的同意记录分开保存,所以请在这里也记录每一位表示同意的人。每次调用最多 1000 条,要么全部成功要么全部失败。
curl -s https://api.app2email.com/v1/YOUR_NUMBER/optins \
-H "Authorization: Bearer $A2E_KEY" \
-H "Content-Type: application/json" \
-d '{
"numbers": [
{ "number": "61412345678", "name": "John", "source": "web form", "note": "ticked the box", "at": "2026-10-01T09:00:00Z" },
{ "number": "61498765432", "name": "Mary", "source": "checkout", "at": "2026-10-12T02:30:00Z" }
]
}'
curl -s -X PUT https://api.app2email.com/v1/YOUR_NUMBER/settings/optin \
-H "Authorization: Bearer $A2E_KEY" \
-H "Content-Type: application/json" \
-d '{ "require_optin_for_marketing": true }'const headers = {
Authorization: `Bearer ${process.env.A2E_KEY}`,
"Content-Type": "application/json",
};
await fetch("https://api.app2email.com/v1/YOUR_NUMBER/optins", {
method: "POST",
headers,
body: JSON.stringify({
numbers: [
{ number: "61412345678", name: "John", source: "web form", note: "ticked the box", at: "2026-10-01T09:00:00Z" },
{ number: "61498765432", name: "Mary", source: "checkout", at: "2026-10-12T02:30:00Z" },
],
}),
});
await fetch("https://api.app2email.com/v1/YOUR_NUMBER/settings/optin", {
method: "PUT",
headers,
body: JSON.stringify({ require_optin_for_marketing: true }),
});headers = {"Authorization": f"Bearer {os.environ['A2E_KEY']}"}
requests.post(
"https://api.app2email.com/v1/YOUR_NUMBER/optins",
headers=headers,
json={
"numbers": [
{"number": "61412345678", "name": "John", "source": "web form", "note": "ticked the box", "at": "2026-10-01T09:00:00Z"},
{"number": "61498765432", "name": "Mary", "source": "checkout", "at": "2026-10-12T02:30:00Z"},
]
},
)
requests.put(
"https://api.app2email.com/v1/YOUR_NUMBER/settings/optin",
headers=headers,
json={"require_optin_for_marketing": True},
)您会得到的响应: opt-in 的响应是 {"success": true, "request_id": "o9ahv", "saved": 2},该设置的响应是 {"require_optin_for_marketing": true}。GET /v1/YOUR_NUMBER/optins?number=61412345678 会检查一个号码(opted_in 为 true 或 false)。
无论 opt-in 记录怎么说,营销模板都绝不会发送给 Do Not Call 名单上的号码。回复 STOP 的人会由 app2email 自己添加。请添加那些在别处退订的人(您的商店、您的邮件列表、一次电话)。最多 1000 个号码,要么全部成功要么全部失败。
curl -s https://api.app2email.com/v1/YOUR_NUMBER/donotcall \
-H "Authorization: Bearer $A2E_KEY" \
-H "Content-Type: application/json" \
-d '{
"numbers": [
"61400111222",
{ "number": "61400333444", "name": "Sam", "note": "Unsubscribed in our CRM" }
]
}'const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/donotcall", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.A2E_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
numbers: ["61400111222", { number: "61400333444", name: "Sam", note: "Unsubscribed in our CRM" }],
}),
});
console.log(await res.json());res = requests.post(
"https://api.app2email.com/v1/YOUR_NUMBER/donotcall",
headers={"Authorization": f"Bearer {os.environ['A2E_KEY']}"},
json={"numbers": ["61400111222", {"number": "61400333444", "name": "Sam", "note": "Unsubscribed in our CRM"}]},
)
print(res.json())您会得到的响应: 已 added 的号码、already_on_list 的号码,以及名单中现有的数量。
{
"success": true,
"request_id": "d4nca",
"added": ["61400111222", "61400333444"],
"already_on_list": [],
"count": 37
}GET /v1/YOUR_NUMBER/donotcall?number=61400111222 会检查一个号码(on_list)。DELETE /v1/YOUR_NUMBER/donotcall/61400111222 会把一个号码从名单中移除:只有当对方要求重新接收优惠时才这样做。
写下优惠内容,用带编号的占位符表示名字,在 example 中给出示例值,并加上说明如何停止接收的页脚。STOP 及其各语言翻译都是 app2email 已经识别的退订词。
curl -s https://api.app2email.com/v1/YOUR_NUMBER/templates \
-H "Authorization: Bearer $A2E_KEY" \
-H "Content-Type: application/json" \
-d '{
"name": "winter_sale",
"language": "en",
"category": "MARKETING",
"components": [
{
"type": "BODY",
"text": "Hi {{1}}, our winter sale starts today: 20% off everything until Sunday. Shop now: https://www.example.com/sale",
"example": { "body_text": [["John"]] }
},
{ "type": "FOOTER", "text": "Reply STOP to opt out" }
]
}'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: "winter_sale",
language: "en",
category: "MARKETING",
components: [
{
type: "BODY",
text: "Hi {{1}}, our winter sale starts today: 20% off everything until Sunday. Shop now: https://www.example.com/sale",
example: { body_text: [["John"]] },
},
{ type: "FOOTER", text: "Reply STOP to opt out" },
],
}),
});
console.log(res.status, await res.json());res = requests.post(
"https://api.app2email.com/v1/YOUR_NUMBER/templates",
headers={"Authorization": f"Bearer {os.environ['A2E_KEY']}"},
json={
"name": "winter_sale",
"language": "en",
"category": "MARKETING",
"components": [
{
"type": "BODY",
"text": "Hi {{1}}, our winter sale starts today: 20% off everything until Sunday. Shop now: https://www.example.com/sale",
"example": {"body_text": [["John"]]},
},
{"type": "FOOTER", "text": "Reply STOP to opt out"},
],
},
)
print(res.status_code, res.json())您会得到的响应(HTTP 201):模板已提交给 Meta 审核。
{
"success": true,
"request_id": "c3ppl",
"template": {
"id": "2234567890",
"name": "winter_sale",
"language": "en",
"category": "MARKETING",
"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/winter_sale."
}审核需要几分钟到一天。template.status_changed 事件会告诉您结果(status 为 APPROVED 且 can_send: true,或 REJECTED 并带有 reason),也可以查询 GET /v1/YOUR_NUMBER/templates/winter_sale。它的 example_request 是一个可以直接复制的完整发送请求,而 quality_score(GREEN、YELLOW 或 RED)之后会显示人们对它的反应。完整的审核流程请参阅用模板发送订单和预约通知。
模板属于 WhatsApp Business Account:该账户下的每个号码都可以使用它们。
细分群体是对您的联系人保存的筛选条件。每个条件都必须满足:tags_any、tags_all、consent_marketing、last_inbound_days(在最近 N 天内给您写过信)和 search。最多 100 个细分群体。
curl -s https://api.app2email.com/v1/YOUR_NUMBER/segments \
-H "Authorization: Bearer $A2E_KEY" \
-H "Content-Type: application/json" \
-d '{
"name": "Newsletter, consented",
"filter": { "tags_any": ["newsletter"], "consent_marketing": true }
}'const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/segments", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.A2E_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
name: "Newsletter, consented",
filter: { tags_any: ["newsletter"], consent_marketing: true },
}),
});
const { segment } = await res.json();
console.log(segment.id, segment.contacts);res = requests.post(
"https://api.app2email.com/v1/YOUR_NUMBER/segments",
headers={"Authorization": f"Bearer {os.environ['A2E_KEY']}"},
json={"name": "Newsletter, consented", "filter": {"tags_any": ["newsletter"], "consent_marketing": True}},
)
segment = res.json()["segment"]
print(segment["id"], segment["contacts"])您会得到的响应(HTTP 201):该细分群体,以及目前匹配的联系人数量。
{
"success": true,
"request_id": "s5gmt",
"segment": {
"id": 12,
"name": "Newsletter, consented",
"filter": { "tags_any": ["newsletter"], "consent_marketing": true },
"contacts": 240,
"created": "2026-11-21T01:00:00Z",
"updated": "2026-11-21T01:00:00Z"
}
}GET /v1/YOUR_NUMBER/segments/12/contacts?limit=200 会分页列出它匹配的联系人(next_cursor)。细分群体是筛选条件,而不是副本:撤回同意的联系人会从中移出。
recipients 为每个号码提供各自的值:这里是导入时的名字。每批发送一个请求,最多 max_numbers_per_request 个号码(见 GET /usage 和 GET /me;即群发上限,最多 1000)。
"background": true 会在所有内容检查完毕后立即返回响应,并在之后发送。campaign_name 是该群发在活动日志“群发”下的名称。Idempotency-Key 头属于这一批:如果您的任务在 24 小时内运行了两次,这一批不会被再次发送。curl -s https://api.app2email.com/v1/YOUR_NUMBER/messages \
-H "Authorization: Bearer $A2E_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: winter-sale-2026-batch-0" \
-d '{
"type": "template",
"campaign_name": "Winter sale 2026",
"background": true,
"template": { "name": "winter_sale", "language": { "code": "en" } },
"recipients": [
{
"to": "61412345678",
"components": [{ "type": "body", "parameters": [{ "type": "text", "text": "John" }] }]
},
{
"to": "61498765432",
"components": [{ "type": "body", "parameters": [{ "type": "text", "text": "Mary" }] }]
}
]
}'const BASE = "https://api.app2email.com/v1/YOUR_NUMBER";
const headers = {
Authorization: `Bearer ${process.env.A2E_KEY}`,
"Content-Type": "application/json",
};
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
async function call(path, init = {}) {
for (;;) {
const res = await fetch(BASE + path, { ...init, headers: { ...headers, ...init.headers } });
if (res.status === 429) {
const body = await res.json();
if (body.error.code !== "rate_limited") throw new Error(`${body.error.code}: ${body.error.how_to_fix}`);
await sleep(Number(res.headers.get("Retry-After") ?? 5) * 1000);
continue;
}
const body = await res.json();
if (!res.ok) throw new Error(`${body.error.code}: ${body.error.how_to_fix}`);
return body;
}
}
// 1. Everyone the segment matches, page by page
const contacts = [];
let cursor = "";
do {
const page = await call(`/segments/12/contacts?limit=200${cursor ? `&cursor=${encodeURIComponent(cursor)}` : ""}`);
contacts.push(...page.contacts);
cursor = page.next_cursor;
} while (cursor);
// 2. The most numbers per request
const { max_numbers_per_request: max } = await call("/usage");
// 3. One request per batch, each with its own Idempotency-Key
for (let i = 0, n = 0; i < contacts.length; i += max, n++) {
const batch = contacts.slice(i, i + max);
const body = await call("/messages", {
method: "POST",
headers: { "Idempotency-Key": `winter-sale-2026-batch-${n}` },
body: JSON.stringify({
type: "template",
campaign_name: `Winter sale 2026 (${n + 1})`,
background: true,
template: { name: "winter_sale", language: { code: "en" } },
recipients: batch.map((c) => ({
to: c.identity,
components: [
{ type: "body", parameters: [{ type: "text", text: c.custom_fields?.first_name || c.name || "there" }] },
],
})),
}),
});
if (body.status === "pending_approval") console.log("waiting for approval:", body.approval.url);
else console.log(body.status, body.broadcast.code, body.queued, body.skipped);
}import os, time, requests
BASE = "https://api.app2email.com/v1/YOUR_NUMBER"
HEADERS = {"Authorization": f"Bearer {os.environ['A2E_KEY']}"}
def call(method, path, **kw):
while True:
res = requests.request(method, BASE + path, headers={**HEADERS, **kw.pop("headers", {})}, **kw)
body = res.json()
if res.status_code == 429 and body["error"]["code"] == "rate_limited":
time.sleep(int(res.headers.get("Retry-After", "5")))
continue
if not res.ok:
raise RuntimeError(f"{body['error']['code']}: {body['error']['how_to_fix']}")
return body
# 1. Everyone the segment matches, page by page
contacts, cursor = [], None
while True:
page = call("GET", "/segments/12/contacts", params={"limit": 200, **({"cursor": cursor} if cursor else {})})
contacts += page["contacts"]
cursor = page.get("next_cursor")
if not cursor:
break
# 2. The most numbers per request
size = call("GET", "/usage")["max_numbers_per_request"]
# 3. One request per batch, each with its own Idempotency-Key
for n, i in enumerate(range(0, len(contacts), size)):
batch = contacts[i : i + size]
body = call(
"POST",
"/messages",
headers={"Idempotency-Key": f"winter-sale-2026-batch-{n}"},
json={
"type": "template",
"campaign_name": f"Winter sale 2026 ({n + 1})",
"background": True,
"template": {"name": "winter_sale", "language": {"code": "en"}},
"recipients": [
{
"to": c["identity"],
"components": [
{
"type": "body",
"parameters": [
{"type": "text", "text": c.get("custom_fields", {}).get("first_name") or c.get("name") or "there"}
],
}
],
}
for c in batch
],
},
)
if body["status"] == "pending_approval":
print("waiting for approval:", body["approval"]["url"])
else:
print(body["status"], body["broadcast"]["code"], body.get("queued"), body.get("skipped"))您会得到的响应(HTTP 202):检查已通过,发送已开始。请保存 broadcast.code:之后所有关于这次群发的调用都会用到它。
{
"success": true,
"request_id": "t7wpe",
"status": "queued",
"from": "4976659348270",
"template": { "name": "winter_sale", "language": "en", "category": "MARKETING" },
"broadcast": {
"name": "Winter sale 2026",
"code": "k3XbQ9rTzP2mWv7a1c9e",
"report_url": "https://www.app2email.com/dashboard/log/broadcast/k3XbQ9rTzP2mWv7a1c9e",
"status_url": "https://api.app2email.com/v1/4976659348270/broadcasts/k3XbQ9rTzP2mWv7a1c9e"
},
"recipients": 2,
"queued": 2,
"skipped": 0,
"results": [],
"note": "Sending in the background. GET broadcast.status_url for progress and the result for each number, or use the broadcast.completed webhook."
}在发送任何内容之前,每个号码都会被检查。Do Not Call 名单上的号码,以及(开启 opt-in 规则时)没有 opt-in 记录的号码,会被跳过并计数,不会发送。
先测试。 在同一个请求体中加入 "dry_run": true。所有内容都会像真实发送一样被检查(模板值、号码、Do Not Call 名单、opt-in 规则、月度限额),响应会按号码显示确切的 WhatsApp 消息。不会发送、记录或计数,Idempotency-Key 也会被忽略。
直接发给细分群体。 用 "segment": "Newsletter, consented"(它的 id 或准确名称)代替 recipients,可以在一次调用中发送给该细分群体的每个联系人。对于使用 命名 占位符({{first_name}},用 "parameter_format": "NAMED" 创建)的模板,值取自每个联系人:带有 parameter_name 而没有 text 的参数会从联系人的 custom_fields 填充(name 来自联系人的姓名)。
{
"segment": "Newsletter, consented",
"type": "template",
"campaign_name": "November offer",
"template": {
"name": "november_offer",
"language": { "code": "en" },
"components": [
{ "type": "body", "parameters": [{ "type": "text", "parameter_name": "first_name" }] }
]
}
}在同一个请求体中加入 send_at(带时区的 ISO 8601,1 分钟到 29 天之后)。在您客户所在时区的早晨发送,通常比半夜发送效果更好。
{
"type": "template",
"campaign_name": "Winter sale 2026",
"template": { "name": "winter_sale", "language": { "code": "en" } },
"recipients": [
{ "to": "61412345678", "components": [{ "type": "body", "parameters": [{ "type": "text", "text": "John" }] }] }
],
"send_at": "2026-12-01T09:00:00+11:00"
}响应为 HTTP 202,带有 status: "scheduled"、scheduled_for(UTC)、scheduled(消息数量)和群发 code。所有内容会立即检查,Do Not Call 名单和月度限额在到时间时会再次检查,所以期间说了 STOP 的人不会收到。
群发发送期间,GET /v1/YOUR_NUMBER/broadcasts/{code} 会实时更新。
curl -s https://api.app2email.com/v1/YOUR_NUMBER/broadcasts/k3XbQ9rTzP2mWv7a1c9e \
-H "Authorization: Bearer $A2E_KEY"
# one row per message, for a spreadsheet
curl -s https://api.app2email.com/v1/YOUR_NUMBER/broadcasts/k3XbQ9rTzP2mWv7a1c9e/results.csv \
-H "Authorization: Bearer $A2E_KEY" -o winter-sale.csvconst res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/broadcasts/k3XbQ9rTzP2mWv7a1c9e", {
headers: { Authorization: `Bearer ${process.env.A2E_KEY}` },
});
const { broadcast, counts } = await res.json();
console.log(broadcast.status, counts);res = requests.get(
"https://api.app2email.com/v1/YOUR_NUMBER/broadcasts/k3XbQ9rTzP2mWv7a1c9e",
headers={"Authorization": f"Bearer {os.environ['A2E_KEY']}"},
)
body = res.json()
print(body["broadcast"]["status"], body["counts"])您会得到的响应: 群发本身、它的计数,以及每个号码的一条结果。status 是 scheduled、inprogress、completed、cancelled、missed、interrupted、pending 或 unknown。每条结果是消息本身(带有 status、times 和客户的 reply),或者是带有 reason 的 skipped、not_sent 或 pending。
{
"success": true,
"request_id": "b6rsl",
"broadcast": {
"code": "k3XbQ9rTzP2mWv7a1c9e",
"name": "Winter sale 2026",
"created": "2026-12-01T09:00:00Z",
"status": "completed",
"sent_by": "api",
"template": { "name": "winter_sale", "language": "en" },
"report_url": "https://www.app2email.com/dashboard/log/broadcast/k3XbQ9rTzP2mWv7a1c9e"
},
"counts": {
"numbers": 240,
"skipped_do_not_call": 3,
"skipped_monthly_limit": 0,
"posted": 237,
"accepted": 236,
"sent": 236,
"delivered": 229,
"read": 171,
"failed": 1,
"replied": 19,
"opted_out": 2
},
"results": [
{
"message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=",
"to": "61412345678",
"status": "read",
"sent_by": "api",
"broadcast_code": "k3XbQ9rTzP2mWv7a1c9e",
"text": "Hi John, our winter sale starts today: 20% off everything until Sunday. Shop now: https://www.example.com/sale",
"times": {
"submitted": "2026-12-01T09:00:00Z",
"accepted": "2026-12-01T09:00:01Z",
"sent": "2026-12-01T09:00:02Z",
"delivered": "2026-12-01T09:00:04Z",
"read": "2026-12-01T09:14:40Z"
},
"reply": { "at": "2026-12-01T09:15:10Z", "text": "Do you have it in blue?" },
"conversation_url": "https://www.app2email.com/conversation/61412345678_4976659348270_..."
},
{ "to": "61400111222", "status": "skipped", "reason": "On the Do Not Call list" }
]
}results.csv 每条消息一行:号码、状态、message_id、每一步的时间、回复和错误(如果跟踪了链接,还有 clicks 和 first_click_at)。以 =、+、- 或 @ 开头的值前面会加一个 ',这样电子表格不会把它们当作公式运行。GET /v1/YOUR_NUMBER/broadcasts 会列出您最近的群发,最新的在前。
优惠里的价格写错了?POST /v1/YOUR_NUMBER/broadcasts/{code}/cancel(权限范围 messages:send)会停止一个已安排或仍在发送的 API 群发。
curl -s -X POST https://api.app2email.com/v1/YOUR_NUMBER/broadcasts/k3XbQ9rTzP2mWv7a1c9e/cancel \
-H "Authorization: Bearer $A2E_KEY"const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/broadcasts/k3XbQ9rTzP2mWv7a1c9e/cancel", {
method: "POST",
headers: { Authorization: `Bearer ${process.env.A2E_KEY}` },
});
console.log(res.status, await res.json());res = requests.post(
"https://api.app2email.com/v1/YOUR_NUMBER/broadcasts/k3XbQ9rTzP2mWv7a1c9e/cancel",
headers={"Authorization": f"Bearer {os.environ['A2E_KEY']}"},
)
print(res.status_code, res.json())您会得到的响应: 已安排的群发返回 HTTP 200(没有发送任何内容),正在发送的群发返回 HTTP 202:已经交给 WhatsApp 的消息保持已发送状态,其余的不会发送。
{
"success": true,
"request_id": "u1nqd",
"broadcast": { "code": "k3XbQ9rTzP2mWv7a1c9e", "status": "cancelling" },
"note": "Cancelling. Messages already handed to WhatsApp stay sent; the rest are not sent. GET https://api.app2email.com/v1/4976659348270/broadcasts/k3XbQ9rTzP2mWv7a1c9e shows the result."
}随后会有一个带有 status: "cancelled" 的 broadcast.completed 事件。已结束的群发,以及从控制台启动的群发,会返回 409 broadcast_not_cancellable。
API 群发: 请根据结果自行构建下一份名单。GET /broadcasts/{code} 中的每条结果都有消息的 status 和客户的 reply,所以您可以挑出,例如,读过优惠但没有回复的所有人,然后像上面那样用 POST /messages 给他们发送第二个模板。
const { results } = await (await fetch(`${BASE}/broadcasts/k3XbQ9rTzP2mWv7a1c9e`, { headers })).json();
const readNoReply = results.filter((r) => r.status === "read" && !r.reply).map((r) => r.to);在控制台的群发页面启动的群发 还有两项 API 可以使用的功能:
https://www.app2email.com/l/<code>。GET /broadcasts/{code}/clicks 会给出总点击数、唯一点击数、点击率和每位收件人的点击(链接预览和爬虫不计入)。同样的数字也在 GET /broadcasts/{code} 的 clicks 中,每次点击还会收到一个 link.clicked 事件。POST /broadcasts/{code}/retarget 会为一个 audience 创建一个使用相同模板、值和媒体的新群发:not_read、read_not_clicked、clicked、replied(在发送后 7 天内回复)或 not_replied。请先用 dry_run 统计数量:curl -s https://api.app2email.com/v1/YOUR_NUMBER/broadcasts/k3XbQ9rTzP2mWv7/retarget \
-H "Authorization: Bearer $A2E_KEY" \
-H "Content-Type: application/json" \
-d '{ "audience": "read_not_clicked", "dry_run": true }'const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/broadcasts/k3XbQ9rTzP2mWv7/retarget", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.A2E_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ audience: "read_not_clicked", dry_run: true }),
});
console.log(await res.json());res = requests.post(
"https://api.app2email.com/v1/YOUR_NUMBER/broadcasts/k3XbQ9rTzP2mWv7/retarget",
headers={"Authorization": f"Bearer {os.environ['A2E_KEY']}"},
json={"audience": "read_not_clicked", "dry_run": True},
)
print(res.json())您会得到的响应: 带有 dry_run 时是数量(HTTP 200)。不带时是 HTTP 202 和新的群发,它会在后台发送。
{
"success": true,
"request_id": "c3rtg",
"audience": "read_not_clicked",
"recipients": 131,
"broadcast": {
"code": "Mx8Pq2Lw5Rt7Yz3",
"name": "Summer sale - read not clicked",
"status": "inprogress",
"status_url": "https://api.app2email.com/v1/4976659348270/broadcasts/Mx8Pq2Lw5Rt7Yz3",
"report_url": "https://www.app2email.com/dashboard/log/broadcast/Mx8Pq2Lw5Rt7Yz3"
},
"note": "The new broadcast is sending in the background."
}Do Not Call 名单和套餐限额会再次检查,密钥的审批上限和每日上限同样适用。再营销、恢复和重试只适用于控制台群发:API 名单会返回 403 broadcast_not_resumable。
跟进消息是另一条营销消息,会再次计费。请把它发给一小群感兴趣的人(clicked、replied),而不是所有忽略了第一条的人。
客户会看到一条来自您企业名称的消息,其中有优惠内容、他们的名字,以及页脚“回复 STOP 即可退订”。如果他们回复,24 小时窗口就会开启,您可以通过 API 或电子邮件用自由文本回复。
在您这一侧,会收到这些事件(用 POST /v1/YOUR_NUMBER/webhooks 和公网 https url 添加 webhook;权限范围 webhooks:manage)。还没有公网地址?GET /v1/YOUR_NUMBER/events?wait=25 会给出同样的事件。
message.status 对应每条消息,随着它的推进依次出现:sent、delivered、read 或 failed。broadcast_code 说明它属于哪次群发,pricing.category 说明 Meta 如何计算它。
{
"id": "evt_Xq3k9m2Lw8Rt5Yp1Zs01",
"type": "message.status",
"created": "2026-12-01T09:00:04.000Z",
"number": "4976659348270",
"data": {
"message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=",
"to": "61412345678",
"status": "delivered",
"timestamp": "2026-12-01T09:00:04.000Z",
"sent_by": "api",
"broadcast_code": "k3XbQ9rTzP2mWv7a1c9e",
"whatsapp_status": "delivered",
"recipient_user_id": "AU.1234567890123456",
"pricing": { "billable": true, "pricing_model": "PMP", "type": "regular", "category": "marketing" }
}
}message.failed 在消息无法送达时出现。营销中您会遇到的一个是 Meta 错误 131049:因为这个人最近收到了很多营销消息,WhatsApp 扣留了这条消息。请不要在 24 小时内重新发送;过早重试会让封锁持续更久。
{
"id": "evt_Pa3k9m2Lw8Rt5Yp1Zs011",
"type": "message.failed",
"created": "2026-12-01T09:00:03.000Z",
"number": "4976659348270",
"data": {
"message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=",
"to": "61412345678",
"status": "failed",
"timestamp": "2026-12-01T09:00:03.000Z",
"sent_by": "broadcast",
"whatsapp_status": "failed",
"error": {
"code": 131049,
"message": "This message was not delivered to maintain healthy ecosystem engagement.",
"title": "This message was not delivered to maintain healthy ecosystem engagement.",
"error_code": "marketing_per_user_limit",
"how_to_fix": "WhatsApp held this marketing message back: the person has had many marketing messages lately. Do not send it again within 24 hours, because retrying sooner keeps the block longer.",
"is_retriable": false,
"retry_after_seconds": 86400
}
}
}message.received 在客户回复时出现:键入的回复为 text,点击的按钮为 button。
contact.opted_out 在客户把自己加入 Do Not Call 名单时出现。source 是 stop_promotions(他们点击了“Stop promotions”)、whatsapp_stop 或 keyword(他们发送了退订词)。
{
"id": "evt_Xq3k9m2Lw8Rt5Yp1Zs01",
"type": "contact.opted_out",
"created": "2026-12-01T09:20:00.000Z",
"number": "4976659348270",
"data": {
"number": "61412345678",
"name": "John Smith",
"source": "stop_promotions",
"detail": "Stop promotions",
"timestamp": "2026-12-01T09:20:00.000Z"
}
}link.clicked 对应已跟踪链接上的每次点击(控制台群发)。对于该收件人的链接,第一次点击时 first_click 为 true。
{
"id": "evt_Cmp3k9m2Lw8Rt5Yp1Zs01",
"type": "link.clicked",
"created": "2026-11-19T01:00:00.000Z",
"number": "4976659348270",
"data": {
"contact": "61412345678",
"url": "https://example.com/sale",
"broadcast_code": "k3XbQ9rTzP2mWv7",
"sequence_id": null,
"step_id": null,
"first_click": true,
"clicks": 1,
"browser": "Chrome",
"timestamp": "2026-11-19T01:00:00.000Z"
}
}broadcast.completed 每次群发一个,在群发结束、被取消或错过预定时间时出现。
{
"id": "evt_Xq3k9m2Lw8Rt5Yp1Zs01",
"type": "broadcast.completed",
"created": "2026-12-01T09:04:00.000Z",
"number": "4976659348270",
"data": {
"code": "k3XbQ9rTzP2mWv7a1c9e",
"name": "Winter sale 2026",
"status": "completed",
"sent_by": "api",
"numbers": 240,
"posted": 237,
"accepted": 236,
"errors": 1,
"skipped_do_not_call": 3,
"skipped_monthly_limit": 0,
"status_url": "https://api.app2email.com/v1/4976659348270/broadcasts/k3XbQ9rTzP2mWv7a1c9e",
"report_url": "https://www.app2email.com/dashboard/log/broadcast/k3XbQ9rTzP2mWv7a1c9e"
}
}GET /v1/YOUR_NUMBER/stats?from=&to= 会汇总某个时间段内、跨多次群发的已发送、已送达、已读、失败和已回复的数量和比率。
两笔账单:
skipped_monthly_limit),或返回 429 monthly_limit_reached。发送前请用 WhatsApp 定价计算器估算。发送之后,GET /v1/YOUR_NUMBER/usage 中的 meta_pricing 会按 Meta 的类别统计当前计费月的消息并给出参考费用,GET /v1/YOUR_NUMBER/usage/meta 则按天给出。
一旦 Meta 为您的账户开通了其 Marketing Messages API,营销模板默认就会走那条路径(号码的设置 messages.marketing_route,auto)。GET /v1/YOUR_NUMBER/marketing 会显示路径,发送响应中的 sent_via 会说明一条消息走了哪条路径。您的请求不需要任何改变。
WhatsApp 会观察人们对您消息的反应。大量屏蔽和举报会降低您的 质量评级。随后:
quality_score(在 GET /templates/{name} 中)会变为 YELLOW,然后是 RED,RED 的模板可能被暂停(422 template_paused,Meta 错误 132015);paused_by_meta,原因在 status_notes 中);解决原因后,用 POST /broadcasts/{code}/resume 继续。GET /v1/YOUR_NUMBER/health(权限范围 messages:read)会显示号码的 quality_rating 和 messaging_limit:
{
"success": true,
"request_id": "h7q2m",
"health": {
"can_send_message": "AVAILABLE",
"quality_rating": "GREEN",
"messaging_limit": "TIER_2K",
"throughput": "STANDARD",
"status": "CONNECTED",
"name_status": "APPROVED",
"account_mode": "LIVE"
},
"fetched_at": "2026-11-06T01:00:00.000Z"
}如何保持绿色:
last_inbound_days),并在发送其余部分之前观察第一部分的已读和退订情况。每个事件都带有头 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);
if (await alreadySeen(req.get("X-App2email-Delivery"))) return res.sendStatus(200); // a retry
const event = JSON.parse(req.body);
res.sendStatus(200); // answer within 10 seconds, then do the work
switch (event.type) {
case "message.status":
case "message.failed":
await saveStatus(event.data.broadcast_code, event.data.to, event.data.message_id, event.data.status, event.data.error);
break;
case "contact.opted_out":
await markUnsubscribed(event.data.number, event.data.source); // in your CRM too
break;
case "broadcast.completed":
await saveBroadcastTotals(event.data);
break;
}
});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)
queue.put(event) # handle it after answering
return "", 200 # within 10 seconds请在 10 秒内返回 2xx 状态。否则事件会在 10 秒、1 分钟、5 分钟、30 分钟、1、2、4、8 和 16 小时后再次发送。X-App2email-Delivery(事件的 id,evt_...)在每次重试时都相同,所以请保存它,并跳过已处理的事件。
事件可能乱序到达:read 可能先于它的 delivered 到来。请为每个 message_id 保留最靠后的状态,不要退回。对于群发,请用 broadcast_code 和 to 作为记录的键。
给每一批一个属于这次活动和这一批,而不是属于这次尝试的 Idempotency-Key:winter-sale-2026-batch-0、winter-sale-2026-batch-1。24 小时内用同一个密钥发出的相同请求不会再次发送;它会得到第一次的响应,并带有头 Idempotent-Replayed: true。
422 idempotency_key_reused。请保持各批的顺序不变,或者为新名单使用新的密钥。409 idempotency_request_in_progress。请等待,并用同一个密钥重试。409 idempotency_request_interrupted。可能有部分消息已经发出:在用新密钥发送之前,请检查 GET /broadcasts。密钥会保留 24 小时。还请在您的数据库中保存每一批的 broadcast.code,并且不要发送已经有这个 code 的批次。
请每批一次调用发送一个名单,而不是每个号码调用一次。每个响应都带有 X-RateLimit-Limit、X-RateLimit-Remaining、X-RateLimit-Reset(距离恢复满额的秒数)和 X-RateLimit-Policy;GET /me 中的 limits 会显示密钥的 requests_per_second 和 burst。超出限制时,您会得到带有 Retry-After 头和 error.retry_after_seconds 的 429 rate_limited:等待相应的时间,然后再次发送同一个请求。
500、502、503 或超时:用逐步变长的等待时间重试几次,并使用同一个 Idempotency-Key。429 whatsapp_rate_limit 或 429 too_many_messages_to_recipient:WhatsApp 自己的限制。请退避几分钟,而不是几秒。429 monthly_limit_reached、429 monthly_cap_reached 或 429 daily_cap_reached:套餐、号码或密钥的某项限额。在它重置之前不要重试,或者提高它。4xx:不要原样重试。请根据 error.code 判断,并按 how_to_fix 处理。error.is_retriable 会告诉您同一个请求之后是否可能成功。密钥可以有每日上限和审批关卡(GET /me 会显示它们)。发送给的联系人超过关卡允许的数量时,会返回 HTTP 202,带有 status: "pending_approval" 和 approval.url:这不是错误。由真人在控制台上批准,随后会出现 approval.resolved 事件,消息再发出。在此期间不要用另一种方式发送同一份名单。对于发送营销消息的密钥,这是一道很好的安全网。
contact.opted_out 会通知您。用 PUT /v1/YOUR_NUMBER/settings/number 和 {"compliance": {"stop_keywords_extra": ["UNSUBSCRIBE"]}} 添加您自己的退订词(权限范围 settings:manage)。POST /contacts/{identity}/consent,带 "marketing": false),这样带有 consent_marketing: true 的细分群体就会把他们排除在外;如果他们在别处退订了,也请把他们放进 Do Not Call 名单。403 recipient_stopped_marketing(Meta 错误 131050)。如果他们重新开启,会收到带有 change: "marketing_resumed" 的 contact.updated。GET /v1/YOUR_NUMBER/compliance/export.csv(权限范围 dnc:manage)会把同意记录、Do Not Call 名单和 opt-in 合并成一个文件,这些记录是 Spam Act 2003 期望您能够出示的。群发使用的是模板,所以可以随时发出。客户回复后,24 小时窗口就会开启,您可以用普通文本、图片或按钮回复(app2email 会提前 15 分钟停止)。GET /v1/YOUR_NUMBER/conversations/61412345678 会显示 window_state 和 window_closes_at。如果他们最后一条消息就是退订本身,那么回复会返回 403 recipient_opted_out,直到他们再次写信。
每个错误都是包含 error.code、message、how_to_fix 和 request_id 的 JSON,您可以把 request_id 提供给支持团队。所有错误代码请见错误,限制请见限制。
| 代码 | 出现时机 | 处理方法 |
|---|---|---|
403 insufficient_scope | 密钥缺少某项权限(details.required_scope) | 使用具有上表中权限范围的密钥 |
403 sandbox_key | 用沙盒密钥创建模板、调用 PUT /settings/optin 或再营销 | 这些调用请使用普通密钥 |
400 invalid_csv | CSV 没有表头行,或没有联系人行 | 发送一个表头行和至少一行数据,最多 5000 行 |
400 invalid_template_category | category 不是 MARKETING、UTILITY 或 AUTHENTICATION | 促销请使用 MARKETING |
422 template_not_approved | 模板处于待审核、被拒绝、已暂停或已停用状态 | 等待批准,或修正它;请检查 GET /templates/{name} |
422 template_parameters_invalid | 值与模板不匹配 | 根据 details.problems 和 example_request 修正请求体 |
422 template_paused | Meta 错误 132015:因质量低而被暂停 | 使用另一个模板,或编辑这个模板;发送给更少、更匹配的人 |
400 too_many_recipients | 号码数量超过该号码在一次请求中允许发送的数量 | 按 details.max_recipients 拆分成多批 |
400 to_and_recipients | 同时使用了 to 和 recipients | 只使用其中一个 |
400 segment_and_recipients | segment 与 to、recipient 或 recipients 同时使用 | 只使用 segment |
400 segment_empty | 该细分群体没有匹配的联系人 | 检查 GET /segments/{id}/contacts,添加联系人或修改筛选条件 |
404 segment_not_found | 没有该 id 或名称的细分群体 | GET /segments 会列出它们;请使用 id 或准确的名称 |
403 recipient_opted_out | 只有一个号码,并且它在 Do Not Call 名单上 | 不要向他们发送营销消息;在名单中它会被跳过 |
403 recipient_not_opted_in | 只有一个号码,opt-in 规则已开启,而它没有 opt-in 记录 | 先用 POST /optins 记录他们的同意;在名单中它会被跳过 |
403 recipient_stopped_marketing | Meta 错误 131050:他们在 WhatsApp 中关闭了您的营销 | 不要向他们发送营销模板 |
422 marketing_per_user_limit | Meta 错误 131049:他们最近收到了很多营销消息 | 24 小时内不要重新发送 |
403 messaging_limit_restricted | Meta 错误 131064:Meta 因模板类别错误而降低了消息上限 | 检查您的模板类别;上限会在 Meta 规定的期限之后恢复 |
403 whatsapp_payment_issue | Meta 错误 131042:Meta 无法向您的 WhatsApp 账户扣款 | 在 WhatsApp Manager 中添加或修复付款方式 |
400 send_at_too_far | send_at 在 29 天之后 | 使用从现在起 1 分钟到 29 天之内、带时区的时间 |
422 idempotency_key_reused | 相同的 Idempotency-Key,不同的请求体 | 对不同的名单使用新的密钥 |
429 rate_limited | 该密钥的调用过多 | 等待 Retry-After 秒,然后重试 |
429 whatsapp_rate_limit | WhatsApp 的速率限制(Meta 130429、131048 等) | 放慢速度,一分钟或更久之后再试 |
429 monthly_limit_reached | 本月套餐的消息已用完 | 等待下一个计费月,或升级 |
429 daily_cap_reached | 密钥的每日上限 | 等到 UTC 午夜,或提高上限 |
409 broadcast_not_cancellable | 群发已结束、已被取消,或是在控制台启动的 | 只有已安排或仍在发送的 API 发送才能被取消 |
403 broadcast_not_resumable | 对 API 名单执行再营销、恢复或重试 | 对于 API 名单,请用 POST /messages 重新发送您想要的号码 |
400 invalid_retarget_audience | audience 不是这五个值之一 | 使用 not_read、read_not_clicked、clicked、replied 或 not_replied |
409 broadcast_nothing_to_send | 该受众中已没有人 | 无需处理 |
403 campaign_approval_needed | 再营销发送的数量会超过密钥的审批上限 | 从控制台启动,或使用没有审批上限的密钥 |