登录开始免费试用
Meta Tech Provider

WhatsApp 消息如何到达您的服务器:直连或托管,以及验证签名

通过 easyCoexistence 连接的每个号码都有一种入站模式。直达您的系统(直连):Meta 将其 Webhook 发送到您的 HTTPS 端点,URL 中的密钥即为凭证,自动化功能关闭。通过 easyCoexistence(托管):Meta 将消息投递给 easyCoexistence,自动化可以回复;可选的 Forward URL 会收到 Meta 的原始值及连接详情,并带有 X-EC-Signature 签名,供您验证。

7 attempts

每次转发投递的尝试次数及间隔:1 分钟、5 分钟、30 分钟、2 小时、6 小时和 24 小时,总计约 33 小时。

10 s

每次转发尝试等待 2xx 响应的时长,超时即视为失败。

5 min

签名中 t 的建议时效上限;重试会重新签名,因此正常投递都在该范围内。

7 days

对于非 HTTP 200 的响应,Meta 重试直连 Webhook 的时长,这可能导致消息重复。

3 MB

Meta 发送的 Webhook 负载最大体积,包括历史数据分块。

30 days

托管号码的运行日志保留时长,包括消息与回复文本;消息文本本身保留 30、90 或 365 天,由您选择。

直连与托管有什么区别?

这是 Meta 投递号码消息 Webhook 的位置。托管模式,显示为“通过 easyCoexistence”,表示 Meta 将消息投递给 easyCoexistence。easyCoexistence 会检查 Meta 的签名,运行您的自动化,为 Conversations 保存聊天记录;如果您设置了 Forward URL,则会将每个 Meta 变更连同仅您持有的密钥签名后转发给您。直连模式,显示为“直达您的系统”,表示 easyCoexistence 会把您的 HTTPS 端点设置为该号码 WhatsApp Business 账户上的 Webhook 覆盖地址,因此 Meta 直接向您投递,消息不会经过 easyCoexistence。

监控所依赖的运营类 Webhook,例如 account_update 和质量变更,在两种模式下都仍由 easyCoexistence 接收,因此无论哪种模式,警报都能继续工作。

Managed: Through easyCoexistenceDirect: Straight to your system
Meta delivers toeasyCoexistence, which verifies Meta's signatureYour HTTPS endpoint
AutomationsRun on the numberOff
Your copyOptional Forward URL, one Meta change per POSTMeta's envelope, unchanged
Proof it is genuineX-EC-Signature, HMAC-SHA256 with the number's secretA long random secret in the URL path
Failed deliveries7 attempts over about 33 hoursMeta retries for up to 7 days
History importNot requestedRequested when saved within 24 hours of connecting
Kept by easyCoexistenceMessage text 30, 90 or 365 days, run logs 30 daysNothing

如何在两种模式之间切换号码?

在号码页面的“入站消息去向”卡片中,当前模式以两个选项显示:“通过 easyCoexistence”和“直达您的系统”。在“将入站消息路由到您自己的 Webhook”卡片中保存 Webhook 目标,或通过 set_webhook_destination 保存,号码会切换为直连。选择“通过 easyCoexistence”会立即在 Meta 端删除该目标,因此请将同一 URL 添加为 Forward URL,以继续接收消息。号码离开托管模式时,排队中的转发会被丢弃;未设置 Webhook URL 的号码连接后默认为托管模式。

在您的 AI 中,set_inbound_mode 可在一次调用中切换模式并设置转发,并且只返回一次转发密钥:

set_inbound_mode: arguments and result
// set_inbound_mode arguments
{
  "connection_id": "3f2a9c1e-7b4d-4e8a-9c2f-1a2b3c4d5e6f",
  "mode": "managed",
  "forward_url": "https://agent.example.com/ec/forward"
}

// result: forward_secret is shown once
{
  "connection_id": "3f2a9c1e-7b4d-4e8a-9c2f-1a2b3c4d5e6f",
  "mode": "managed",
  "forward_url": "https://agent.example.com/ec/forward",
  "forward_secret": "whsec_Qm9vbXRoZXNlY3JldHNhcmVmYWtlMTIz",
  "secret_note": "Shown once. Verify X-EC-Signature: t=<unix>,v1=<hex HMAC-SHA256 of \"<t>.<raw body>\"> with it; the body's value is Meta's original payload.",
  "direct_destination": null
}

转发的 POST 包含什么内容?

每个请求包含一个 Meta 变更,并且做了包装,而不是 Meta 的 object、entry 和 changes 外层结构。id 是投递 ID,同时在 X-EC-Delivery 中重复出现,并且在重试时保持不变。event 是 Meta 字段名,即 messages、smb_message_echoes、history 或 smb_app_state_sync,同时在 X-EC-Event 中重复出现。received_at 是 easyCoexistence 从 Meta 接收该变更的时间,connection 标识号码,value 则与 Meta 发送的内容完全一致,因此为 Meta 负载编写的解析代码可直接用于此数据。投递状态位于 messages 事件中,即 value.statuses 下。

A forwarded messages event: headers and body
POST /ec/forward HTTP/1.1
Content-Type: application/json
User-Agent: easyCoexistence-forward/1
X-EC-Event: messages
X-EC-Delivery: 8c1d7e52-0f4b-4a3e-9d61-2b7f5a9e0c13
X-EC-Signature: t=1794405732,v1=<64 hex characters>

{
  "id": "8c1d7e52-0f4b-4a3e-9d61-2b7f5a9e0c13",
  "event": "messages",
  "received_at": "2026-11-11T14:02:11.482Z",
  "connection": {
    "id": "3f2a9c1e-7b4d-4e8a-9c2f-1a2b3c4d5e6f",
    "phone": "+1 631-555-0142",
    "phone_number_id": "106540352242922",
    "waba_id": "102290129340398",
    "external_ref": null
  },
  "value": {
    "messaging_product": "whatsapp",
    "metadata": { "display_phone_number": "16315550142", "phone_number_id": "106540352242922" },
    "contacts": [{ "profile": { "name": "Ana Souza" }, "wa_id": "5511987654321", "user_id": "BR.13491208655302741918" }],
    "messages": [{
      "from": "5511987654321",
      "from_user_id": "BR.13491208655302741918",
      "id": "wamid.HBgNNTUxMTk4NzY1NDMyMRUCABIYFjNFQjBDNzE4RjQ2QjI5RDkxQTNFAA==",
      "timestamp": "1794405731",
      "type": "text",
      "text": { "body": "Do you deliver on Sundays?" }
    }]
  }
}

如何在 Node.js 中验证 X-EC-Signature?

将请求头解析为 t=<Unix 秒数>,v1=<64 个十六进制字符>。如果 t 与您的时钟相差超过 5 分钟,则拒绝该请求。使用完整的转发密钥(以 UTF-8 文本形式)作为密钥,对 t、一个点号和原始请求体计算 HMAC-SHA256,然后以恒定时间比较结果与 v1。只有在验证通过后才解析 JSON。请在 10 秒内返回 2xx,之后再处理业务逻辑,并记录您已接受的投递 ID,以免重试被重复处理。

forward-receiver.mjs (Node.js, no dependencies)
// forward-receiver.mjs: node forward-receiver.mjs (no dependencies)
import crypto from "node:crypto";
import http from "node:http";

const SECRET = process.env.EC_FORWARD_SECRET; // the whole whsec_... string is the HMAC key
const taken = new Set(); // delivery ids already accepted: use a database in production

export function verifyEcSignature(raw, header, secret = SECRET, maxAgeSec = 300) {
  const m = /^t=(\d+),v1=([0-9a-f]{64})$/.exec(String(header ?? "").trim());
  if (!m || !secret) return false;
  if (Math.abs(Math.floor(Date.now() / 1000) - Number(m[1])) > maxAgeSec) return false;
  const mac = crypto.createHmac("sha256", secret).update(`${m[1]}.`).update(raw).digest();
  return crypto.timingSafeEqual(mac, Buffer.from(m[2], "hex"));
}

http.createServer((req, res) => {
  const chunks = [];
  req.on("data", (c) => chunks.push(c));
  req.on("end", () => {
    const raw = Buffer.concat(chunks);
    if (req.method !== "POST" || !verifyEcSignature(raw, req.headers["x-ec-signature"])) {
      res.writeHead(401).end();
      return;
    }
    res.writeHead(200).end(); // a 2xx within 10 s, before any work
    const d = JSON.parse(raw.toString("utf8"));
    if (taken.has(d.id)) return; // a retry of a delivery already accepted
    taken.add(d.id);
    // d.event is the Meta field (messages, smb_message_echoes, history, smb_app_state_sync)
    // d.value is Meta's change value, unchanged; queue it for your worker here.
    console.log(d.event, d.connection.phone_number_id, Object.keys(d.value));
  });
}).listen(process.env.PORT ?? 3000);

如何在 Python 中验证?

使用标准库执行相同的四项检查:用严格的模式匹配请求头,检查 t 的时效,用 hmac.new 对 t、一个点号和原始字节计算签名,并使用 hmac.compare_digest 比较。在 FastAPI 中,原始请求体来自 await request.body(),BackgroundTasks 会在 200 发送之后运行任务。在 Flask 中请使用 request.get_data(),切勿用 json.dumps 重建请求体,因为 Python 默认的分隔符会添加空格,签名就无法匹配。

forward_receiver.py (FastAPI)
# forward_receiver.py: pip install fastapi uvicorn, then uvicorn forward_receiver:app
import hashlib, hmac, json, os, re, time
from fastapi import BackgroundTasks, FastAPI, Request, Response

app = FastAPI()
SECRET = os.environ["EC_FORWARD_SECRET"].encode()  # the whole whsec_... string, as bytes
SIGNATURE = re.compile(r"t=([0-9]+),v1=([0-9a-f]{64})")
taken = set()  # delivery ids already accepted: use a database in production

def verify_ec_signature(raw: bytes, header: str, max_age: int = 300) -> bool:
    m = SIGNATURE.fullmatch(header.strip())
    if not m or abs(int(time.time()) - int(m[1])) > max_age:
        return False
    mac = hmac.new(SECRET, m[1].encode() + b"." + raw, hashlib.sha256).hexdigest()
    return hmac.compare_digest(mac, m[2])

def process(delivery: dict) -> None:
    if delivery["id"] in taken:  # a retry of a delivery already accepted
        return
    taken.add(delivery["id"])
    print(delivery["event"], delivery["connection"]["phone_number_id"], list(delivery["value"]))

@app.post("/ec/forward")
async def forward(request: Request, tasks: BackgroundTasks):
    raw = await request.body()
    if not verify_ec_signature(raw, request.headers.get("x-ec-signature", "")):
        return Response(status_code=401)
    tasks.add_task(process, json.loads(raw))  # runs after the 200 goes out
    return Response(status_code=200)

失败的投递如何重试?

只要您的端点在 10 秒内返回任意 2xx,转发即视为已投递。其他任何结果,包括超时、4xx、5xx,或未被跟随的重定向,都会在约 1 分钟、5 分钟、30 分钟、2 小时、6 小时和 24 小时后安排下一次尝试;第七次尝试后放弃该投递。每次尝试都会以新的 t 重新签名,且 URL 必须是公开的 HTTPS,保存时以及每次发送前都会进行检查。投递按从旧到新的顺序发出,但被重试的投递可能晚于较新的投递到达,因此请按 Meta 的时间戳排序。

在直连目标上,重试由 Meta 完成:除 HTTP 200 外的任何响应,都会在最长 7 天内以逐渐降低的频率重试,这些重试可能重复消息。在两种模式下,都请以 Meta 的消息 ID 去重,因为 Meta 重新投递的变更会以新的投递 ID 再次被转发。

直连端点如何确认 POST 来自 Meta?

不能依靠 X-Hub-Signature-256。Meta 使用拥有该订阅的应用的应用密钥签名,对于在此连接的号码,该应用是 easyCoexistence 的应用,且该密钥并不共享,因此用您自己的 Meta 应用密钥检查此请求头,会拒绝正常的投递。验证令牌只会在 Meta 的 GET 握手期间证明一次端点的身份。以下方法可以替代:

  • 在回调 URL 路径中加入 32 个或更多随机字符,并拒绝没有它们的请求;如需轮换,请保存新的 URL。
  • 使用通用接收器,例如 n8n Webhook 节点,而不是需要您自己 Meta 应用的 WhatsApp 触发器。
  • 使用该号码的访问令牌按 ID 从 Meta 下载媒体,因此伪造的 ID 会直接失败。
  • 在自托管服务器上,可选择仅允许 Meta 的网络,即 AS32934 所宣告的路由。
  • 或者切换为托管模式并设置 Forward URL,由 X-EC-Signature 证明每个 POST 的真实性。

常见错误

  • 把为 Meta 信封编写的代码原样指向 Forward URL。转发每次只携带一个变更:请读取 event 和 value,而不是 object、entry 和 changes。
  • 等待 X-EC-Event 为 statuses。投递状态位于 messages 事件中的 value.statuses 里,而在应用中输入的回复则以 smb_message_echoes 形式到达。
  • 先处理再回复。转发会等待 10 秒,之后同一投递会以新的 t 再次到达;应先返回 2xx,再从队列中处理。
  • 切换为托管后仍假定旧 URL 会接收消息。直连目标会在那一刻被删除;请在同一次 set_inbound_mode 调用中传入 forward_url。
使用 EasyCoexistence 完成这些操作

easyCoexistence 通过 Coexistence 将 WhatsApp Business 应用号码连接到 Meta 的 Cloud API,并让您按号码选择消息的去向:要么由 Meta 直接发送到您的服务器,要么经由 easyCoexistence 转发,以便自动化可以回复,并将带签名的副本送达您的 Forward URL。监控和警报在两种模式下都可用。每个号码每月 US$ 9 起,号码越多越便宜,最低降至 US$ 0.75,并提供 3 天免费试用。

常见问题

服务器能看到自动化的回复内容吗?

看不到文本。Meta 会以状态(已发送、已送达、已读)的形式在 messages 事件中报告 API 发送,并附带消息 ID;回复的文本本身保存在自动化的运行日志中,在“运行”标签页保留 30 天,在 Conversations 中则按您选择的时长保留。

如何轮换转发密钥?

在号码页面点击“新建密钥”,或调用 set_inbound_mode 并将 rotate_secret 设为 true。新密钥只显示一次,并从此刻起为所有内容签名,包括旧投递的重试,因此请立即更新您的服务器。

Forward URL 是否需要 Meta 的 GET 握手?

不需要。只有直连目标由 Meta 调用,并且必须回显 hub.challenge。Forward URL 由 easyCoexistence 调用,且只接收已签名的 POST。

同一号码能否同时设置直连目标和 Forward URL?

不能。Forward URL 只在号码为托管模式时生效,保存直连目标会使其切换为直连。Forward URL 及其密钥会被保留,因此切回托管后转发会恢复。

继续阅读

准备开始了吗?

几分钟即可设置 WhatsApp Coexistence,而不是几个月。应用会继续在手机上运行。

开始免费试用

验证时间