Log inStart Free Trial
Meta Tech Provider

Build a WhatsApp AI agent in Node.js and Python on a Coexistence number

Receive the number's messages either forwarded with an HMAC signature you verify (X-EC-Signature) or straight from Meta's webhook with a secret in the URL. Then skip any message id already handled, stay quiet on a chat where an echo shows a person replied from the phone, and send your model's answer through the Cloud API only within 24 hours of the customer's last message.

easyCoexistence connects the number the business keeps using in the WhatsApp Business app to Meta's Cloud API, gives your code its credentials through get_api_credentials, and routes messages straight from Meta to your server or through a signed forward with automations on.

5 min

Largest gap to accept between the signature's t and your clock; every retry is signed again with a fresh t.

10 s

How long a forwarded POST waits for a 2xx before easyCoexistence schedules a retry of that delivery.

7 days

How long Meta retries a direct webhook that did not get HTTP 200, which can deliver the same message twice.

24 hours

Customer service window after the user's last message; outside it, Meta accepts only template messages.

20 mps

Fixed throughput of a number used with both the WhatsApp Business app and the Cloud API.

Which route should a coded agent use?

Forwarded means the number stays in Automations on mode: Meta delivers to easyCoexistence, automations can still run, and a signed copy of each Meta change goes to your Forward URL. A variant needs no forward at all: an automation's Call my webhook step POSTs the message to your endpoint and sends whatever {"reply"} you return within 20 seconds, with dedupe, the phone pause and the 24-hour check done for you.

Direct means Meta posts its own webhook straight to your endpoint, set with set_webhook_destination, and easyCoexistence never sees the messages. Automations are off for that number, so every guard is yours, and so is the 6-month history import when the destination is saved within 24 hours of connecting. The samples below handle all three entry points with one shared core.

Forwarded, signedDirect from Meta
Number modeAutomations on (managed)Direct to your server
BodyOne Meta change: id, event, received_at, connection, valueMeta's envelope: object, entry, changes
AuthenticationX-EC-Signature, HMAC-SHA256 with a per-number secretA secret in the URL path
AcknowledgeAny 2xx within 10 secondsHTTP 200; Meta retries other codes
Retries7 attempts over about 33 hoursUp to 7 days
ReplyGraph API, or {"reply"} to a Call my webhook stepGraph API
History importNot requestedRequested if saved within 24 hours of connecting

What does the agent do with a message, in Node.js?

agent.mjs holds the logic both routes share. It records the customer's last message time, steps back for 4 hours on a chat when an smb_message_echoes event shows someone answered from the WhatsApp Business app (the default easyCoexistence automations use), skips a message id it has already handled, and sends only inside the 24-hour window. The window is measured from the message's own timestamp, not from when it reached you, since a retried delivery can arrive hours late.

Users are keyed by BSUID (from_user_id, or to_user_id on echoes) with the phone number as fallback, and a user known only by BSUID is answered with recipient instead of to. The model call uses any OpenAI-compatible chat completions API; swap in your provider's SDK if you prefer.

agent.mjs: the shared logic
// agent.mjs: what the agent does with one Meta change, whichever route brought it.
const DAY = 24 * 3600 * 1000;
const PAUSE = 4 * 3600 * 1000;   // quiet time after a person replies (automations default to 4 h)
const seen = new Set();          // handled ids: use Redis or your database in production
const lastInbound = new Map();   // user -> ms of their last message
const quietUntil = new Map();    // user -> ms until which a person has the chat

export function firstTime(id) {
  if (seen.has(id)) return false;
  seen.add(id);
  return true;
}

export async function handleChange(field, value) {
  if (field === "smb_message_echoes") {
    // Someone answered from the WhatsApp Business app: step back on that chat.
    for (const e of value.message_echoes ?? []) {
      quietUntil.set(e.to_user_id ?? e.to, Number(e.timestamp) * 1000 + PAUSE);
    }
    return;
  }
  if (field !== "messages") return;              // statuses ride in value.statuses: ignored here
  for (const m of value.messages ?? []) {
    if (!firstTime(m.id)) continue;               // Meta delivered this message before
    const user = m.from_user_id ?? m.from;        // BSUID first, phone number as fallback
    lastInbound.set(user, Math.max(Number(m.timestamp) * 1000, lastInbound.get(user) ?? 0));
    if ((quietUntil.get(user) ?? 0) > Date.now()) continue; // a person has this chat
    if (m.type !== "text") continue;              // media: fetch it by id first (see the FAQ)
    const reply = await askModel([{ role: "user", content: m.text.body }]);
    if (!reply) continue;
    if (Date.now() - lastInbound.get(user) >= DAY) continue; // window closed: template only
    await sendText({ phone: m.from, bsuid: m.from_user_id }, reply);
  }
}

// Any OpenAI-compatible chat completions API (OpenAI, OpenRouter...).
export async function askModel(turns) {
  const res = await fetch(`${process.env.AI_BASE_URL}/chat/completions`, {
    method: "POST",
    headers: { Authorization: `Bearer ${process.env.AI_KEY}`, "Content-Type": "application/json" },
    body: JSON.stringify({
      model: process.env.AI_MODEL,
      messages: [{ role: "system", content: process.env.AI_INSTRUCTIONS ?? "Answer briefly." }, ...turns],
    }),
  });
  if (!res.ok) throw new Error(`AI provider answered ${res.status}`);
  const data = await res.json();
  return data.choices?.[0]?.message?.content?.trim() ?? "";
}

// send_endpoint and access_token come from get_api_credentials.
async function sendText({ phone, bsuid }, text) {
  const res = await fetch(process.env.SEND_ENDPOINT, {
    method: "POST",
    headers: { Authorization: `Bearer ${process.env.WA_TOKEN}`, "Content-Type": "application/json" },
    body: JSON.stringify({
      messaging_product: "whatsapp",
      recipient_type: "individual",
      ...(phone ? { to: phone } : { recipient: bsuid }), // a BSUID-only user gets recipient
      type: "text",
      text: { body: text.slice(0, 4096) },
    }),
  });
  if (!res.ok) throw new Error(`Graph API answered ${res.status}: ${await res.text()}`);
}

How do you verify and route events in Node.js?

server.mjs exposes the three entry points. /ec/forward takes a managed number's forwards: it verifies X-EC-Signature on the raw bytes with the number's forward secret, answers 200 before any work, and skips a delivery id it has already accepted, because a retry carries the same id with a fresh signature. The body's event is Meta's field name and value is Meta's change, unchanged. /ec/agent answers a Call my webhook step, signed with that automation's own Signing secret, and turns history into chat turns. /meta/:secret is the direct route: it answers Meta's GET handshake with the raw hub.challenge and accepts POSTs only on the secret path.

The HMAC key is the whole secret, whsec_ prefix included, as UTF-8 text. express.raw keeps the bytes intact, and its 5 MB limit leaves room for Meta payloads of up to 3 MB.

server.mjs: verification and routes (Express)
// server.mjs: Node 18+, npm i express, then node server.mjs
import crypto from "node:crypto";
import express from "express";
import { askModel, firstTime, handleChange } from "./agent.mjs";

const app = express();

// X-EC-Signature: t=<unix>,v1=<hex HMAC-SHA256 of "<t>.<raw body>">, keyed with the whole secret.
export function verifyEc(raw, header, secret, toleranceSec = 300) {
  const m = /^t=(\d+),v1=([0-9a-f]{64})$/.exec(String(header ?? "").trim());
  if (!m || !Buffer.isBuffer(raw) || !secret) return false;
  if (Math.abs(Date.now() / 1000 - Number(m[1])) > toleranceSec) return false; // stale or replayed
  const expected = crypto.createHmac("sha256", secret).update(`${m[1]}.`).update(raw).digest();
  return crypto.timingSafeEqual(expected, Buffer.from(m[2], "hex"));
}

function sameSecret(a, b) {
  const x = Buffer.from(String(a)), y = Buffer.from(String(b ?? ""));
  return x.length === y.length && crypto.timingSafeEqual(x, y);
}

// Route A, forwarded: a managed number's Forward URL. One Meta change per POST.
app.post("/ec/forward", express.raw({ type: "*/*", limit: "5mb" }), (req, res) => {
  if (!verifyEc(req.body, req.get("X-EC-Signature"), process.env.EC_FORWARD_SECRET)) return res.sendStatus(401);
  res.sendStatus(200);                                   // acknowledge inside 10 s, then work
  const d = JSON.parse(req.body.toString("utf8"));
  if (!firstTime(`delivery:${d.id}`)) return;            // a retry of a delivery already taken
  handleChange(d.event, d.value).catch(console.error);   // d.event is the Meta field name
});

// Route A, synchronous: a "Call my webhook" step. Answer {"reply"} within 20 s.
app.post("/ec/agent", express.raw({ type: "*/*", limit: "1mb" }), async (req, res) => {
  if (!verifyEc(req.body, req.get("X-EC-Signature"), process.env.EC_AUTOMATION_SECRET)) return res.sendStatus(401);
  const step = JSON.parse(req.body.toString("utf8"));
  const turns = step.history.map((h) => ({ role: h.direction === "in" ? "user" : "assistant", content: h.text }));
  while (turns[0]?.role === "assistant") turns.shift();
  if (!turns.length) turns.push({ role: "user", content: step.message?.text ?? "" }); // tests carry no history
  res.json({ reply: await askModel(turns) });            // step.dry_run is true on "Test it"
});

// Route B, direct: Meta's own envelope. The secret path is the credential.
app.get("/meta/:secret", (req, res) => {
  if (!sameSecret(req.params.secret, process.env.PATH_SECRET)) return res.sendStatus(404);
  if (req.query["hub.mode"] === "subscribe" && req.query["hub.verify_token"] === process.env.VERIFY_TOKEN) {
    return res.type("text/plain").send(String(req.query["hub.challenge"]));
  }
  res.sendStatus(403);
});

app.post("/meta/:secret", express.json({ limit: "5mb" }), (req, res) => {
  if (!sameSecret(req.params.secret, process.env.PATH_SECRET)) return res.sendStatus(404);
  res.sendStatus(200);                                   // Meta retries anything but 200
  for (const entry of req.body.entry ?? []) {
    for (const change of entry.changes ?? []) handleChange(change.field, change.value).catch(console.error);
  }
});

app.listen(process.env.PORT ?? 3000);

How does the same agent look in Python?

One Flask file with the same three routes and the same rules. request.get_data() returns the raw body for the HMAC, hmac.compare_digest does the constant-time comparison, and the work runs on a background thread after the 200, so neither easyCoexistence nor Meta waits on your model. Run it with flask --app agent run while developing and behind gunicorn or another WSGI server in production.

The in-memory set and dictionaries suit one process. With several workers or instances, move them to Redis or your database, using a set-if-absent write with an expiry for message ids, or two workers will answer the same message.

agent.py: the whole agent (Flask)
# agent.py: pip install flask requests, then flask --app agent run
import hashlib, hmac, json, os, re, threading, time
import requests
from flask import Flask, abort, request

app = Flask(__name__)
DAY, PAUSE = 24 * 3600, 4 * 3600
seen, last_inbound, quiet_until = set(), {}, {}  # use Redis or a database in production
lock = threading.Lock()

def verify_ec(raw: bytes, header: str, secret: str, tolerance: int = 300) -> bool:
    m = re.fullmatch(r"t=([0-9]+),v1=([0-9a-f]{64})", (header or "").strip())
    if not m or not secret or abs(time.time() - int(m[1])) > tolerance:
        return False
    expected = hmac.new(secret.encode(), m[1].encode() + b"." + raw, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, m[2])

def first_time(key: str) -> bool:
    with lock:
        if key in seen:
            return False
        seen.add(key)
        return True

def ask_model(turns: list) -> str:  # any OpenAI-compatible chat completions API
    r = requests.post(f"{os.environ['AI_BASE_URL']}/chat/completions", timeout=30,
                      headers={"Authorization": f"Bearer {os.environ['AI_KEY']}"},
                      json={"model": os.environ["AI_MODEL"], "messages": [
                          {"role": "system", "content": os.environ.get("AI_INSTRUCTIONS", "Answer briefly.")}, *turns]})
    r.raise_for_status()
    return (r.json()["choices"][0]["message"]["content"] or "").strip()

def send_text(phone, bsuid, text: str) -> None:  # SEND_ENDPOINT and WA_TOKEN: get_api_credentials
    to = {"to": phone} if phone else {"recipient": bsuid}
    r = requests.post(os.environ["SEND_ENDPOINT"], timeout=15,
                      headers={"Authorization": f"Bearer {os.environ['WA_TOKEN']}"},
                      json={"messaging_product": "whatsapp", "recipient_type": "individual", **to,
                            "type": "text", "text": {"body": text[:4096]}})
    r.raise_for_status()

def handle_change(field: str, value: dict) -> None:
    if field == "smb_message_echoes":  # a person answered from the app: step back
        for e in value.get("message_echoes", []):
            quiet_until[e.get("to_user_id") or e.get("to")] = int(e["timestamp"]) + PAUSE
        return
    if field != "messages":
        return
    for m in value.get("messages", []):
        if not first_time(m["id"]):  # Meta delivered this message before
            continue
        user = m.get("from_user_id") or m.get("from")
        last_inbound[user] = max(int(m["timestamp"]), last_inbound.get(user, 0))
        if quiet_until.get(user, 0) > time.time() or m.get("type") != "text":
            continue
        reply = ask_model([{"role": "user", "content": m["text"]["body"]}])
        if reply and time.time() - last_inbound[user] < DAY:  # past 24 h: template only
            send_text(m.get("from"), m.get("from_user_id"), reply)

def later(field, value):
    threading.Thread(target=handle_change, args=(field, value), daemon=True).start()

@app.post("/ec/forward")  # route A: a managed number's Forward URL
def forward():
    raw = request.get_data()
    if not verify_ec(raw, request.headers.get("X-EC-Signature", ""), os.environ["EC_FORWARD_SECRET"]):
        abort(401)
    d = json.loads(raw)
    if first_time("delivery:" + d["id"]):  # skip retries of a delivery already taken
        later(d["event"], d["value"])
    return "", 200

@app.post("/ec/agent")  # route A: a "Call my webhook" step, answer within 20 s
def agent_step():
    raw = request.get_data()
    if not verify_ec(raw, request.headers.get("X-EC-Signature", ""), os.environ["EC_AUTOMATION_SECRET"]):
        abort(401)
    step = json.loads(raw)
    turns = [{"role": "user" if h["direction"] == "in" else "assistant", "content": h["text"]}
             for h in step["history"]]
    while turns and turns[0]["role"] == "assistant":
        turns.pop(0)
    turns = turns or [{"role": "user", "content": step["message"]["text"] or ""}]
    return {"reply": ask_model(turns)}

@app.get("/meta/<secret>")  # route B: Meta's GET handshake
def meta_handshake(secret):
    if not hmac.compare_digest(secret.encode(), os.environ["PATH_SECRET"].encode()):
        abort(404)
    if (request.args.get("hub.mode") == "subscribe"
            and request.args.get("hub.verify_token") == os.environ["VERIFY_TOKEN"]):
        return request.args.get("hub.challenge", ""), 200, {"Content-Type": "text/plain"}
    abort(403)

@app.post("/meta/<secret>")  # route B: Meta's envelope, straight from Meta
def meta_events(secret):
    if not hmac.compare_digest(secret.encode(), os.environ["PATH_SECRET"].encode()):
        abort(404)
    for entry in (request.get_json(silent=True) or {}).get("entry", []):
        for change in entry.get("changes", []):
            later(change.get("field"), change.get("value", {}))
    return "", 200

How do you avoid duplicate replies?

Duplicates have six common causes, and the samples above handle the first five:

  • Meta's retries. A direct webhook is retried for up to 7 days after anything but HTTP 200; keep a store of message ids and skip ids already handled.
  • Forward retries. easyCoexistence retries a delivery that got no 2xx within 10 seconds, with the same id; skip ids already accepted, then dedupe on the message id, since a change Meta redelivers is forwarded again under a new id.
  • Slow acknowledgements. Answer first and work afterwards; a handler that waits on the model times out, and the same event comes back.
  • A person on the phone. An smb_message_echoes event means someone answered from the app; stay quiet on that chat for a few hours.
  • Several workers. In-memory sets do not span processes; move the stores to Redis or your database.
  • Two responders. An AI-reply automation and your own agent on the same chats both answer, and your Graph API sends are not echoes, so they do not pause automations. Pick one responder per number.

Where do the secrets and credentials come from?

From the dashboard or the MCP connector, and they belong only in your server's environment. get_api_credentials returns graph_api_base, waba_id, phone_number_id, send_endpoint and access_token, the business's own token; the number's page shows the same values under Plug in your own system. If access_token is null, reconnect the number from a computer with Reconnect to issue a token. Treat the token like a password, because anyone holding it can message as the business.

EC_FORWARD_SECRETShown once when you save a Forward URL, or returned once by set_inbound_mode; New secret rotates it
EC_AUTOMATION_SECRETSigning secret on the automation's page, under its Call my webhook step
SEND_ENDPOINT, WA_TOKENsend_endpoint and access_token from get_api_credentials
PATH_SECRET, VERIFY_TOKENDirect route: 32 or more random characters in the URL, and the handshake token you chose
AI_BASE_URL, AI_KEY, AI_MODELAny OpenAI-compatible API, such as https://api.openai.com/v1 or https://openrouter.ai/api/v1

Common mistakes

  • Checking the HMAC on re-serialized JSON. Python's json.dumps adds spaces after separators by default, so a body parsed and dumped again no longer matches; verify the raw bytes.
  • Base64-decoding the secret or dropping its whsec_ prefix. The key is the whole string as UTF-8 text, exactly as it was shown to you once.
  • Validating X-Hub-Signature-256 on the direct route with your own Meta app secret. Meta signs with easyCoexistence's app secret, which is not shared, so genuine events fail; authenticate with the path secret.
  • Reading the window from arrival time. A forward retried hours later still carries Meta's original timestamp; compare against it, or the agent replies after 24 hours and Meta refuses the send.
Doing this with EasyCoexistence

Every number is monitored 24/7, with alerts when a connection drops. US$ 9 down to US$ 0.75 per number per month, falling as you add numbers, with the first 3 days free.

easyCoexistence is a multichannel API and MCP server that connects AI agents such as Claude and ChatGPT to WhatsApp, Instagram, TikTok, Facebook and more. On WhatsApp it uses Coexistence: the business keeps using its number in the WhatsApp Business app while the AI works through Meta's official API.

Frequently asked questions

Can the agent understand voice notes and photos?

Yes, with your own code. Meta's payload carries the media id: download it with GET /<media-id> and the number's token, fetch the returned URL with the same Authorization header, then transcribe or describe it with your model. Automations only see placeholders such as [voice message].

Which models can the samples use?

Any model behind an OpenAI-compatible chat completions endpoint, including OpenAI's and those reached through OpenRouter, or replace askModel and ask_model with your provider's SDK. easyCoexistence never bills for AI: your provider bills you directly.

Can the agent start a conversation?

Only with an approved template, sent with type template to the same send endpoint. On a Coexistence number templates go out through the API only, never from the phone app, and Meta bills them per message to the business's own WhatsApp Business Account.

Does one agent serve several numbers?

Yes. Route by value.metadata.phone_number_id or connection.phone_number_id, and keep a send endpoint, a token and a forward secret per number, since each number has its own.

Keep reading

Ready to get started?

Set up WhatsApp Coexistence in minutes, not months. The app keeps working on the phone.

Start Free Trial

Verified on