WhatsApp API for developers: Cloud API, Python, webhooks and n8n

Developers reach WhatsApp in two ways. Meta’s Cloud API: a system-user token, POST /<phone-number-id>/messages on the Graph API, and a webhook server that answers Meta’s verification and checks X-Hub-Signature-256. A platform API such as Autochatix: one scoped API key in X-API-Key, a send endpoint, and signed outbound webhooks, while the inbox and bot handle replies.

When to call Meta directly, the steps and a template example in curl and Python (Meta’s API, placeholders only), webhook verification and signatures, the Autochatix API and webhooks, and n8n, MCP and Odoo.

Start free trial Discuss your setup

Two ways to reach WhatsApp from code

A developer who wants WhatsApp in a product has two routes, and the right one depends on how much you want to build:

Calling Meta’s Cloud API directly vs a platform’s API
Meta Cloud API, directlyA platform API (Autochatix)
You getSend and receive messages; templates; media; webhooksThe same sending, plus the inbox, bot builder, AI agent, CRM, campaigns and billing your team uses
You buildToken handling, a public webhook server, storage, retries, an inbox if people need to replyOnly the trigger in your system and, if needed, a webhook receiver
AuthSystem-user access tokenX-API-Key header with a scoped key
Meta’s chargesBilled by Meta to your WhatsApp Business AccountSame Meta rates, paid from a prepaid wallet with each deduction listed
Best whenWhatsApp is a feature of your own software and you have backend engineersA business wants its systems to trigger messages that its team and bot then handle

Both run on the same official API, so both follow the same Meta rules: approved templates outside the 24-hour window, opt-in, messaging limits per number and the WhatsApp Business Messaging Policy. For more ideas, read WhatsApp automation examples and costs. Building an app around WhatsApp? See mobile app development.

Calling the WhatsApp Cloud API directly

The steps below follow Meta’s get-started guide, read 14 November 2026:

  1. Create an app in the Meta App Dashboard with the WhatsApp use case and connect it to a WhatsApp Business Account.
  2. Generate a temporary access token in API Setup and send a test message from Meta’s test number. Meta says the temporary token “expires quickly”, so it is only for the first test.
  3. Create a system user and generate a permanent token with whatsapp_business_messaging, whatsapp_business_management and business_management.
  4. Set up a webhook endpoint and subscribe to the messages field, which carries incoming messages and the status of the messages you send.
  5. Register your own business phone number and get your templates approved before you send to customers.

Reply with a text message (Meta’s API). Inside the 24-hour customer service window you can send free-form text. This is the shape on Meta’s get-started page (checked 28 November 2026):

curl 'https://graph.facebook.com/v23.0/<BUSINESS_PHONE_NUMBER_ID>/messages' \
  -H 'Content-Type: application/json' \
  -H 'Authorization: Bearer <SYSTEM_USER_ACCESS_TOKEN>' \
  -d '{
  "messaging_product": "whatsapp",
  "recipient_type": "individual",
  "to": "<CUSTOMER_PHONE_NUMBER>",
  "type": "text",
  "text": { "body": "Hello! Your booking is confirmed." }
}'

What each field means: messaging_product is always "whatsapp"; recipient_type is "individual" for a one-to-one chat; to is the customer’s number with its country code (if the + is missing, Meta adds your business’s country code); type picks the kind of message; and text.body is what the customer reads. An optional "preview_url": true inside text shows a link preview. For a customer who reaches you through a WhatsApp username, Meta’s send-messages page uses recipient with the business-scoped user ID (BSUID) instead of to.

Send a template (Meta’s API). Messages go to POST /<BUSINESS_PHONE_NUMBER_ID>/messages on the Graph API. The body below is Meta’s template example from its templates overview; Meta’s get-started page uses Graph API v23.0, and its send-messages page uses a newer version, so use the version your app is on. Positional parameters must be in the same order as {{1}}, {{2}} in the template.

curl 'https://graph.facebook.com/v23.0/<BUSINESS_PHONE_NUMBER_ID>/messages' \
  -H 'Content-Type: application/json' \
  -H 'Authorization: Bearer <SYSTEM_USER_ACCESS_TOKEN>' \
  -d '{
    "messaging_product": "whatsapp",
    "recipient_type": "individual",
    "to": "<CUSTOMER_PHONE_NUMBER>",
    "type": "template",
    "template": {
      "name": "order_confirmation",
      "language": { "code": "en_US" },
      "components": [
        { "type": "body", "parameters": [
          { "type": "text", "text": "Jessica" },
          { "type": "text", "text": "SKBUP2-4CPIG9" }
        ] }
      ]
    }
  }'

The same call in Python (requests), with the token read from the environment, never written in code:

import os, requests

# Meta's Cloud API. Placeholders only: keep the token in an environment variable.
PHONE_NUMBER_ID = os.environ["WA_PHONE_NUMBER_ID"]
TOKEN = os.environ["WA_SYSTEM_USER_TOKEN"]

resp = requests.post(
    f"https://graph.facebook.com/v23.0/{PHONE_NUMBER_ID}/messages",
    headers={"Authorization": f"Bearer {TOKEN}"},
    json={
        "messaging_product": "whatsapp",
        "recipient_type": "individual",
        "to": "<CUSTOMER_PHONE_NUMBER>",
        "type": "template",
        "template": {
            "name": "order_confirmation",
            "language": {"code": "en_US"},
            "components": [{"type": "body", "parameters": [
                {"type": "text", "text": "Jessica"},
                {"type": "text", "text": "SKBUP2-4CPIG9"},
            ]}],
        },
    },
    timeout=15,
)
print(resp.status_code, resp.json())

Named variables. If the template was created with named variables instead of {{1}}, {{2}}, each entry in parameters also carries "parameter_name", as in Meta’s templates overview. Either way the template must be approved before Meta will send it (see template approval); an unapproved name or a wrong language code returns error 132001.

Only a template can start a conversation or reach someone outside the 24-hour customer service window; free-form text, media and interactive messages are for replies inside it. Need the whole system built? See our custom software development service.

Receiving messages: Meta webhooks done right

From Meta’s webhooks overview and its endpoint guide:

  • Verification. Meta calls your URL with hub.mode=subscribe, hub.verify_token and hub.challenge. If the token matches the one you set, answer 200 with the challenge value.
  • Signatures. Every POST carries X-Hub-Signature-256: sha256=…, an HMAC-SHA256 of the body keyed with your app secret. Reject anything that does not match.
  • Retries and duplicates. If you do not answer 200, Meta retries immediately and then less often for up to 7 days, so the same event can arrive twice. Deduplicate by message ID.
  • Batching and size. One POST can carry up to 1,000 updates, but Meta says batching is not guaranteed; handle one or many. A payload can be up to 3 MB.
  • Certificates. Self-signed certificates are not supported; use a real HTTPS certificate. Meta also supports mutual TLS (mTLS) if you want both sides to present certificates.
# Webhook verification (GET) and signature check (POST), per Meta's docs.
import hmac, hashlib, os
from flask import Flask, request, abort

app = Flask(__name__)
VERIFY_TOKEN = os.environ["WA_VERIFY_TOKEN"]
APP_SECRET = os.environ["META_APP_SECRET"].encode()

@app.get("/webhook")
def verify():
    if (request.args.get("hub.mode") == "subscribe"
            and request.args.get("hub.verify_token") == VERIFY_TOKEN):
        return request.args.get("hub.challenge", ""), 200
    abort(403)

@app.post("/webhook")
def receive():
    sent = request.headers.get("X-Hub-Signature-256", "").removeprefix("sha256=")
    expected = hmac.new(APP_SECRET, request.get_data(), hashlib.sha256).hexdigest()
    if not hmac.compare_digest(sent, expected):
        abort(403)
    payload = request.get_json()
    # Store the event, deduplicate by message id, then do the slow work elsewhere.
    return "", 200

Answer quickly and do the slow work (database writes, AI calls, sending replies) after you have returned 200, or Meta’s retries will pile up.

The same receiver in Node.js with Express. The signature is checked on the raw request bytes, before the JSON is parsed: JSON that has been parsed and written out again will not match Meta’s hash, which is the most common reason a correct secret still fails. We ran this example against signed and unsigned test requests: the right token returns the challenge, a wrong token or signature gets 403.

// Webhook verification (GET) and signature check (POST) in Node.js (Express), per Meta's docs.
const crypto = require("crypto");
const express = require("express");

const app = express();
const VERIFY_TOKEN = process.env.WA_VERIFY_TOKEN;
const APP_SECRET = process.env.META_APP_SECRET;

app.get("/webhook", (req, res) => {
  if (req.query["hub.mode"] === "subscribe" && req.query["hub.verify_token"] === VERIFY_TOKEN) {
    return res.status(200).send(req.query["hub.challenge"]);
  }
  res.sendStatus(403);
});

// express.raw keeps the exact bytes Meta signed; parse the JSON only after the check.
app.post("/webhook", express.raw({ type: "application/json" }), (req, res) => {
  const sent = (req.get("X-Hub-Signature-256") || "").replace(/^sha256=/, "");
  const expected = crypto.createHmac("sha256", APP_SECRET).update(req.body).digest("hex");
  const valid = sent.length === expected.length &&
    crypto.timingSafeEqual(Buffer.from(sent), Buffer.from(expected));
  if (!valid) return res.sendStatus(403);

  const payload = JSON.parse(req.body.toString("utf8"));
  // Store the event, deduplicate by message id, then do the slow work elsewhere.
  res.sendStatus(200);
});

app.listen(3000);

Common WhatsApp Cloud API errors and what to do

A failed request, or a failed message status in your webhook, carries an error code. These 23 come from Meta’s WhatsApp error codes page, checked 28 November 2026. The meanings are Meta’s; the advice is Meta’s where it gives one (marked “Meta”) and ours otherwise.

WhatsApp Cloud API error codes, meanings and fixes
CodeWhat it meansWhat to do
130429Rate limit hit: the Cloud API throughput for your number has been reached.Try again later or send less often (Meta).
131000The message failed because of an unknown error.Try again; if it keeps happening, open a Direct Support ticket (Meta).
131005Permission was not granted or has been removed.Check the token’s permissions and that the system user still has the WhatsApp Business Account assigned.
131008A required parameter is missing.Compare the body with the required fields for that message type.
131009One or more parameter values are invalid.Check the phone number format, IDs, template name and language code.
131026The message could not be delivered: for example, the number is not on WhatsApp or the person has not accepted WhatsApp’s terms.Do not retry in a loop. Confirm the number and reach the customer another way.
131031The WhatsApp Business Account is restricted or disabled for a policy violation.Read the notice in WhatsApp Manager; see error 131031.
131042A payment method problem, such as a credit line over its limit or a suspended account.Fix the payment method in Meta Business settings, then resend.
131047More than 24 hours have passed since the customer last replied.Send an approved template instead (Meta); see the 24-hour window.
131048Messages from this number are restricted (spam rate limit).Slow down and look at your quality rating before sending more.
131049Not delivered “to maintain healthy ecosystem engagement”.Send later; Meta says a retry does not guarantee delivery. See error 131049.
131050The customer has chosen to stop receiving marketing messages.Stop marketing sends to this person; see opt-out list hygiene.
131051Unsupported message type.Use a message type the Cloud API supports.
131053The media in the message could not be uploaded.Check the file type, size and that the URL is public; for images, see the image size checker.
131056Too many messages from your number to the same person in a short time (pair rate limit).Space out messages to that person and wait before retrying.
131064Messaging is limited because of template classification violations.Review your template categories; see template quality and paused templates.
132000The number of variable values does not match the template.Send exactly one value per variable, in order.
132001The template does not exist in that language or is not approved.Check the name, language code and status in WhatsApp Manager.
132005The translated text is too long.Shorten the variable values.
132007The template content breaks a WhatsApp policy.Edit and resubmit the template; see template approval.
132012Variable values are formatted incorrectly.Match each parameter’s type and format to the template.
133010The phone number is not registered on the WhatsApp Business Platform.Register the number before trying again (Meta).
130403Your business has blocked this person on WhatsApp.Unblock them before you message them.

Older posts also mention codes such as 131030 and 470. They are not on Meta’s current list, so check a code against that page before you build handling for it.

Limits worth knowing before you build

  • Throughput. When your number reaches its Cloud API throughput, requests fail with 130429. A number used with both the WhatsApp Business app and the Cloud API (coexistence) has a fixed 20 messages per second, per Meta.
  • Pace to one person. Many messages to the same person in a short time fail with 131056, even when your overall throughput is fine.
  • Messaging limits. How many different people a number can start conversations with in 24 hours depends on its tier; see WhatsApp messaging limits.
  • The 24-hour window. Free-form text, media and interactive messages work only within 24 hours of the customer’s last message. After that, only an approved template goes through (131047).
  • Cost. Meta charges per delivered template by category; replies inside the window are service messages. Rates for India are in WhatsApp Business API pricing, and what the Cloud API itself costs is in is the WhatsApp Cloud API free?
  • Identity. Plan for customers who write from a username: Meta sends a business-scoped user ID, and you reply with recipient (see the BSUID section below).

Still setting up your number? Start with how to get the WhatsApp Business API.

The Autochatix API: send from your system, let the team and bot handle the rest

If your business already runs on Autochatix, your code does not need Meta tokens or a webhook server. Create an API key in Autochatix (keys are stored as hashes and shown once), give it only the scopes it needs, and call the public API at https://api.autochatix.com/api/v1 with the key in the X-API-Key header.

Autochatix public API, by scope (from the current release)
ScopeEndpoints
messages.sendPOST /messages/text, /messages/media, /messages/template, /messages/auth-otp
templates.readGET /templates
channels.readGET /channels (pick which WhatsApp number sends); GET /sms/channels for SMS senders
hooks.manageGET /hooks/events, /hooks/sample/:event, /hooks/subscriptions; POST /hooks/subscribe; DELETE /hooks/subscribe/:id
sms.sendPOST /sms/send; GET /sms/status/:id (shows whether the SMS was sent or failed; SMS is outgoing only)

Send an approved template (Autochatix API). to and templateName are required; bodyParams fill the variables in order; channelId picks the number if you have more than one.

curl 'https://api.autochatix.com/api/v1/messages/template' \
  -H 'Content-Type: application/json' \
  -H 'X-API-Key: <YOUR_AUTOCHATIX_API_KEY>' \
  -d '{
    "to": "<CUSTOMER_PHONE_NUMBER>",
    "templateName": "order_confirmation",
    "language": "en_US",
    "bodyParams": ["Jessica", "SKBUP2-4CPIG9"]
  }'

The message appears in the team inbox like any other, so a reply from the customer is handled by your bot or your agents, not by your code. Send endpoints are rate limited, and Meta’s messaging limit for the number still applies.

Outbound webhooks. Autochatix can call your endpoint on six events: order.created, cart.abandoned, contact.created, deal.stage_changed, booking.created and ticket.sla_breached. Each request carries X-AutoChatix-Event, X-AutoChatix-Timestamp and X-AutoChatix-Signature, an HMAC-SHA256 of timestamp + "." + raw body keyed with your webhook secret:

import hmac, hashlib

def is_from_autochatix(raw_body: bytes, headers, secret: str) -> bool:
    ts = headers.get("X-AutoChatix-Timestamp", "")
    sent = headers.get("X-AutoChatix-Signature", "").removeprefix("sha256=")
    signed = f"{ts}.".encode() + raw_body
    expected = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest()
    return hmac.compare_digest(sent, expected)

Delivery is one attempt with an 8-second timeout; failures are logged and an endpoint that keeps failing is disabled, so build your own recovery for anything critical. Details: API and webhooks and how to connect an API or webhook.

n8n, Make and other automation tools

“n8n WhatsApp automation” and “n8n WhatsApp AI agent” are common searches. Any tool that can make an HTTP request and receive one can work with WhatsApp through either route above:

  • Sending: an HTTP Request node calling Meta’s /messages endpoint with your system-user token, or the Autochatix /api/v1/messages/template endpoint with an API key.
  • Receiving: a Webhook node as the endpoint. With Meta directly, it must answer the verification challenge and check signatures; with Autochatix outbound webhooks, it should check the X-AutoChatix-Signature.

Autochatix does not ship an n8n node or Make app today; the HTTP route above is how to connect. Before building an “AI agent” in n8n, check whether you need one: Autochatix already has an AI agent that answers from your documents and hands over to people (AI agent), and Meta’s AI Providers policy restricts general-purpose AI assistants on WhatsApp (see WhatsApp AI agent pricing).

MCP servers, Odoo and ERPs

MCP. Meta’s WhatsApp developer documentation that we read on 14 November 2026 lists no official MCP (Model Context Protocol) server, and Autochatix does not offer one. Community MCP servers for WhatsApp exist; check which API they use. Anything that drives a personal WhatsApp account rather than the official API breaks WhatsApp’s terms and puts the number at risk.

Odoo and other ERPs. Autochatix has no native Odoo connector. The usual pattern is that the ERP calls the send endpoint when a document changes state (invoice posted, order shipped) and receives Autochatix webhooks for orders or bookings. Plan it like any integration: which event, which template, who owns opt-in, and what happens when a send fails. Our integration pages for Zoho CRM and WooCommerce show the scoping questions. Deciding between code, Zapier or a platform first? See WhatsApp API integration: cost and options.

Before you go live: a developer checklist

  • Tokens and API keys live in a secret store or environment variables, never in code, URLs, logs or screenshots.
  • Every template you send is approved, in the right category, with variables in the right order.
  • You send marketing templates only to people who opted in, and you honour opt-outs.
  • Your webhook receiver checks signatures, answers 200 fast, and deduplicates.
  • You handle errors: a failed send is logged and retried or flagged, not silently dropped.
  • You know the number’s messaging limit before a big send (messaging limits).
  • You tested with your own number first, including what happens when the customer replies.

See this part of the workflow

flow builder — local product interface with sample data
A quick tour of the Autochatix workspace, recorded locally with sample data. A paused sample trigger and reply canvas; no live delivery is asserted.
template manager — local product interface with sample data
A quick tour of the Autochatix workspace, recorded locally with sample data. Template creation form and preview; no Meta approval is asserted.
team inbox — local product interface with sample data
A quick tour of the Autochatix workspace, recorded locally with sample data. Sample contact context, status and assignment controls; no two-operator handoff is asserted.
api webhooks — local product interface with sample data
A quick tour of the Autochatix workspace, recorded locally with sample data. Outbound-webhook configuration entry; no delivery, retry or replay is demonstrated.
onboarding — local product interface with sample data
A quick tour of the Autochatix workspace, recorded locally with sample data. Sample account profile; not a live onboarding or verification result.
wallet — local product interface with sample data
A quick tour of the Autochatix workspace, recorded locally with sample data. A fixture wallet balance and zero usage; not real funds or customer charges.

WhatsApp usernames and BSUIDs: plan identity changes without unsafe contact merges

A username is not a universal phone-number lookup key. Meta's Business-Scoped User ID (BSUID) behavior is documented for specific API surfaces; validate each endpoint before changing a CRM.

For username-based customer identification API behavior, user-ID migration planning, or a WhatsApp username rollout checklist, inspect the webhook payloads and API operation references available to your own Meta app. A compatibility audit must be performed per endpoint and API version; one BSUID-enabled Meta Business Agent call does not prove general username support. Meta's current Business Agent changelog describes selected operations.

Keep separate fields for phone number, business-scoped ID and display name; record when a value was observed; make matching reversible; and never merge records solely because names or usernames look alike. Username contact matching in a CRM requires a stable tenant-scoped identifier, not a public username guess. Identity reconciliation and contact merge after migration need a reversible link and human review.

Meta's dates and username rules, in plain terms: WhatsApp usernames for business: what changes and when.

Test phone-present and phone-absent events, messaging without a phone-number lookup, repeat delivery, retries, changed profile labels, legacy records and messages from people who have used a username. Include conversation identity changes in API webhooks and customer-service lookup flows. The 2026 user-profile identifier changes make forward-compatible tests useful, but do not assume a username is returned in every webhook or searchable through an API.

Autochatix's current contact and webhook workflows are phone/E.164 based. BSUID ingestion, username matching, CRM identity reconciliation and contact migration are not currently supported product features. This guide is an API planning checklist, not a compatibility audit or migration service.

Frequently asked questions

Autochatix

Let’s talk about your business

Leave your number and the Autochatix team will call you to discuss your requirements.

Choose your country and enter your number, or include + and your country code.

By requesting a callback, you ask Autochatix to call this number about your enquiry. Privacy Policy.