Skip to content

Blog · WhatsApp and channels

WhatsApp Cloud API with Python: send and receive messages step by step

Send your first message with the WhatsApp Cloud API from Python, verify Meta’s webhook and compare it with doing the same with the meteor-ia SDK.

Equipo editorial de Meteor Published 5 min read

How do I send and receive WhatsApp messages with the Cloud API from Python?

With a POST to https://graph.facebook.com/v26.0/<PHONE_NUMBER_ID>/messages, with your token in the Authorization header and a JSON body with messaging_product “whatsapp”, the destination number and the text. You can only send free-form text within 24 hours of the person’s last message; outside that window, an approved template. To receive, you publish a webhook that answers Meta’s verification (hub.challenge) and checks the X-Hub-Signature-256 signature of each POST with the app secret. If you would rather not manage the Meta app or the webhook, Meteor IA’s meteor-ia SDK sends in two calls and delivers messages to a signed webhook.

This tutorial does the same thing twice. First with Meta’s Cloud API directly, from Python: you send a text, see when a template is needed and receive messages on a webhook that verifies the signature. Then with Meteor IA’s meteor-ia SDK. At the end, a table with what you have to run on each path.

Before you start, on Meta’s side

According to Meta’s getting started guide:

  1. In Meta’s app dashboard you create an app with the Connect with customers through WhatsApp use case and connect it to a WhatsApp Business account.
  2. In API Setup you generate a temporary token, pick the test number as the sender and add your phone as the recipient. The Send message button sends you the hello_world template.
  3. Reply from your phone. That message opens the 24-hour customer service window, and only inside it can you send free-form text.
  4. Save the test number’s Phone Number ID. The temporary token expires quickly: for development, create a system user in your business settings and generate its token with the business_management, whatsapp_business_messaging and whatsapp_business_management permissions.

1. Send a text from Python

The body is the one in Meta’s documentation for text messages. With requests:

import os
import requests

VERSION = "v26.0"  # the latest in Meta's version changelog
PHONE_NUMBER_ID = os.environ["WHATSAPP_PHONE_NUMBER_ID"]
TOKEN = os.environ["WHATSAPP_TOKEN"]

respuesta = requests.post(
    f"https://graph.facebook.com/{VERSION}/{PHONE_NUMBER_ID}/messages",
    headers={"Authorization": f"Bearer {TOKEN}"},
    json={
        "messaging_product": "whatsapp",
        "recipient_type": "individual",
        "to": "+573001234567",
        "type": "text",
        "text": {"body": "Hello from the Cloud API"},
    },
    timeout=30,
)
respuesta.raise_for_status()
print(respuesta.json()["messages"][0]["id"])  # wamid.…

The text allows up to 4,096 characters. If it includes a link and you want WhatsApp to try to show a preview, add "preview_url": True inside text.

2. Messaging first: templates

Outside the 24-hour window, Meta only lets approved templates through. The request changes the type and the block, in the shape Meta’s template documentation shows:

json={
    "messaging_product": "whatsapp",
    "recipient_type": "individual",
    "to": "+573001234567",
    "type": "template",
    "template": {
        "name": "order_confirmation",  # the exact name of your approved template
        "language": {"code": "en_US"},     # the language code it was approved with
        "components": [
            {
                "type": "body",
                "parameters": [
                    {"type": "text", "text": "Ana"},
                    {"type": "text", "text": "PED-1042"},
                ],
            }
        ],
    },
}

Parameters go in the order of the template’s variables.

3. Receive messages: the webhook

Meta talks to your server in two ways, according to its webhooks guide:

  • Verification GET. When you save the URL in the app settings, Meta calls with hub.mode=subscribe, a hub.challenge and the hub.verify_token you typed. If the token matches, you reply 200 with the hub.challenge.
  • POST with each event. It carries the X-Hub-Signature-256: sha256=… header, an HMAC-SHA256 of the body computed with your app’s app secret. If it does not match, you reply with a 400-range error.

With Flask:

import hashlib
import hmac
import os

from flask import Flask, abort, request

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


@app.get("/webhook")
def verificar():
    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 recibir():
    firma = request.headers.get("X-Hub-Signature-256", "")
    esperada = "sha256=" + hmac.new(APP_SECRET, request.get_data(), hashlib.sha256).hexdigest()
    if not hmac.compare_digest(firma, esperada):
        abort(401)

    datos = request.get_json()
    for entrada in datos.get("entry", []):
        for cambio in entrada.get("changes", []):
            for mensaje in cambio["value"].get("messages", []):
                print(mensaje["from"], mensaje.get("text", {}).get("body"))
    return "", 200

The message arrives in entry[].changes[].value.messages[], with from, type and, for text, text.body. Three things from Meta’s guide that people forget:

  1. The URL has to be public with a valid TLS certificate. Self-signed certificates do not work.
  2. Meta retries a failed POST for 7 days: deduplicate by the message id.
  3. There is no API to fetch old webhooks. Whatever you do not store when it arrives is lost.

4. The same with the Meteor IA SDK

With Meteor IA the line is connected once from the dashboard, and the Meta app, its token and Meta’s webhook verification stay out of your code. This is the first message with meteor-ia, in two calls:

  1. Connect WhatsApp to your Meteor IA workspace (dashboard → Canales → WhatsApp).
  2. Create a key in Ajustes → Desarrolladores → Crear API key, live environment, with the contacts:write and channels:send scopes. A met_test_ key does not send WhatsApp.
  3. From your phone, write “hola” to your WhatsApp business number, to open the 24-hour window.
  4. Install the SDK, which has no dependencies beyond the standard library, and run this:
pip install meteor-ia
import os
from meteor_ia import Met

met = Met(os.environ["MET_API_KEY"])

# Creates the contact or, if one already exists with that phone, returns it unchanged.
contacto = met.contacts.create(phone="+573001234567", name="Me")
met.contacts.send_message(contacto["id"], "Hello from the Meteor IA API 👋")

If the 24-hour window is closed, the API replies 409 with code == "service_window_closed". To message someone first, use an approved template: it is in the WhatsApp templates guide on the portal.

Receive messages on a signed webhook

You subscribe once, from a separate script, to the contact.message.received event. The key needs webhooks:manage, conversations:read, runs:execute and channels:send:

met = Met(os.environ["MET_API_KEY"], workspace_id=int(os.environ["MET_WORKSPACE_ID"]))

sub = met.webhooks.subscriptions.create(
    "https://your-server.com/webhooks/met",
    ["contact.message.received"],
)
print(sub["secret"])  # whsec_… shown only once

And on your server, in a complete file, you verify the X-Met-Signature signature with construct_event. Reply 200 right away: Meteor retries if it does not see a 2xx, and a Met can take several seconds to think.

import os
import threading

from flask import Flask, request
from meteor_ia import Met, MetSignatureVerificationError, construct_event

app = Flask(__name__)
met = Met(os.environ["MET_API_KEY"], workspace_id=int(os.environ["MET_WORKSPACE_ID"]))


def contestar(datos):
    run = met.runs.create(datos["content"])
    if run.get("output"):
        met.contacts.send_message(datos["contact_id"], run["output"])


@app.post("/webhooks/met")
def recibir_de_meteor():
    try:
        evento = construct_event(
            request.get_data(),
            request.headers.get("X-Met-Signature", ""),
            os.environ["MET_WEBHOOK_SECRET"],
        )
    except MetSignatureVerificationError:
        return "invalid signature", 400

    if evento["type"] == "contact.message.received":
        threading.Thread(target=contestar, args=(evento["data"],)).start()
    return "", 200

Who answers. If the WhatsApp channel has a Met assigned and the contact’s autopilot is on, the Met answers on its own: you don’t need this webhook to reply, and if your code answers too, the contact gets two messages. This code is for when your logic sits in the middle and the channel has no Met assigned and no linked flow: the event still arrives and your code decides what to answer. Turning autopilot off doesn’t do that: with autopilot off or paused, a send with an API key returns 409 with code == "autopilot_silenced" and nothing goes out. Turning it off (met.contacts.set_autopilot, scope handoff:manage) is for handing the conversation to a person, who answers from the inbox. There is more in the agent that answers WhatsApp recipe.

What you have to run on each path

Cloud API directlyMeteor IA SDK
Connecting the numberYour Meta app, its WhatsApp Business account and the Phone Number IDOnce, from the dashboard (Canales → WhatsApp)
CredentialMeta system user tokenMeteor IA key with scopes
Sending a textPOST to the Graph API with Meta’s bodymet.contacts.send_message
ReceivingWebhook with GET verification and X-Hub-Signature-256 signatureWebhook with X-Met-Signature signature and construct_event
Answering with AIYou build itA Met assigned to the channel, with autopilot, or your code with met.runs.create
What you payThe messages Meta charges forThe Meteor IA plan, the Energy the AI uses and the messages Meta charges for

If you are still deciding, the Cloud API or Meteor guide on the portal compares both paths for builders. For the basics of the API, start with what the WhatsApp Business API is, and what Meta charges per message is in how much the API costs. If you write JavaScript, the same tutorial is with Node.js.

The limits

What this article does NOT answer

We would rather say it here than leave you hunting for something that is not there.

Keep going

What this article mentions, in detail

The integrations, the Mets and the automations named above, each with its own page.

Where it comes from

Sources

Everything this article claims that we did not measure ourselves, with its origin.

Frequently asked

Questions on this topic

The latest in Meta’s version log: v26.0 on December 2, 2026. Some examples already use v27.0, which is not in the log yet; check it before pinning it.

No. Free-form text only goes through within 24 hours of the person’s last message. To message first you need an approved template, with type “template”.

For testing, the temporary token from your app’s API Setup page, which expires quickly. For development, a system user token with the business_management, whatsapp_business_messaging and whatsapp_business_management permissions.

You compute an HMAC-SHA256 of the raw body with your app’s app secret and compare it with what follows “sha256=” in the X-Hub-Signature-256 header. If it does not match, you reply with a 400-range error and do not process it.

No. met_test_ keys do not send WhatsApp. For the first message you need a live key with the contacts:write and channels:send scopes.

Keep reading

Other articles on the same thing

Want to see it running on your operation?

See the API, the SDK and the MCP server, or message us and we will help with your first key.