WhatsApp· 6 min basahin

Magpadala ng WhatsApp message gamit ang Python at Cloud API


Para magpadala ng WhatsApp message mula sa Python, isang requests.post lang ang kailangan sa https://graph.facebook.com/v26.0/<PHONE_NUMBER_ID>/messages, may Bearer token sa Authorization header at JSON body. Sa loob ng customer service window, puwedeng plain text ang body. Sa labas nito, approved na template lang ang tinatanggap ng Meta. Kapag matagumpay ang call, may ibinabalik itong ID sa messages[0].id. Ang ibig sabihin ng ID na iyon, tinanggap ng Meta ang message. Iniuulat ang delivery mamaya, sa pamamagitan ng webhook.

Ano ang kailangan mo bago ang unang call

Tatlong value ang kailangan mo: isang access token, ang ID ng business phone number at isang bersyon ng Graph API. Nagbibigay ng phone number ID ang test number sa App Dashboard. Sinasabi ng get-started page ng Meta na “itabi ang test phone number ID at Messaging account ID mo para magamit mamaya” (Meta get started, na-access noong 2026-11-03). Nasa gabay sa Cloud API test number ang buong walkthrough.

Ang pansamantalang token mula sa page na iyon ay “mabilis mag-expire”, at walang ibinibigay na tagal ang Meta. Para sa anumang iiwan mong tumatakbo, gumamit ng system user token, na tinalakay sa mga access token ng Cloud API.

Para sa bersyon, v26.0 ang ginagamit ng mga send sample ng Meta (Meta text messages, na-access noong 2026-11-03). Ayon sa Graph API changelog, inilabas ang v26.0 noong 2026-07-29 at wala pa itong itinakdang end date (Graph API changelog, na-access noong 2026-11-03). v23.0 pa rin ang ipinapakita ng get-started page, at available ito hanggang 2027-10-08. Ilagay ang bersyon sa isang environment variable para config change lang ang pag-upgrade.

pip install requests
export WHATSAPP_TOKEN="ACCESS_TOKEN"
export PHONE_NUMBER_ID="PHONE_NUMBER_ID"
export GRAPH_VERSION="v26.0"

Ang script

Nagpapadala ang file na ito ng text o template, nire-retry ang dalawang rate-limit code at ipini-print ang message ID. Wala itong kailangan bukod sa requests.

# send_whatsapp.py
import os
import sys
import time

import requests

TOKEN = os.environ["WHATSAPP_TOKEN"]
PHONE_NUMBER_ID = os.environ["PHONE_NUMBER_ID"]
GRAPH_VERSION = os.environ.get("GRAPH_VERSION", "v26.0")
URL = f"https://graph.facebook.com/{GRAPH_VERSION}/{PHONE_NUMBER_ID}/messages"

RETRY_CODES = {130429, 131056}  # throughput and pair rate: wait, then retry


class WhatsAppError(Exception):
    def __init__(self, status, error):
        self.status = status
        self.error = error or {}
        self.code = self.error.get("code")
        details = self.error.get("error_data", {}).get("details", "")
        super().__init__(
            f"HTTP {status}, code {self.code}: {self.error.get('message')} {details}"
        )


def post_message(payload):
    r = requests.post(
        URL,
        json=payload,
        headers={"Authorization": f"Bearer {TOKEN}"},
        timeout=10,
    )
    try:
        data = r.json()
    except requests.exceptions.JSONDecodeError:
        r.raise_for_status()  # a non-JSON error page raises HTTPError here
        raise
    if not r.ok or "error" in data:
        raise WhatsAppError(r.status_code, data.get("error"))
    return data


def send(payload, attempts=4):
    for attempt in range(attempts):
        try:
            return post_message(payload)
        except WhatsAppError as e:
            if e.code not in RETRY_CODES or attempt == attempts - 1:
                raise
            time.sleep(2 ** attempt)


def text_payload(to, body):
    return {
        "messaging_product": "whatsapp",
        "recipient_type": "individual",
        "to": to,
        "type": "text",
        "text": {"preview_url": False, "body": body},
    }


def template_payload(to, name, language, params):
    template = {"name": name, "language": {"code": language}}
    if params:  # name=value becomes a named parameter, a bare value a positional one
        parameters = []
        for p in params:
            key, sep, value = p.partition("=")
            if sep:
                parameters.append({"type": "text", "parameter_name": key, "text": value})
            else:
                parameters.append({"type": "text", "text": p})
        template["components"] = [{"type": "body", "parameters": parameters}]
    return {
        "messaging_product": "whatsapp",
        "recipient_type": "individual",
        "to": to,
        "type": "template",
        "template": template,
    }


if __name__ == "__main__":
    if len(sys.argv) < 4 or (sys.argv[1] == "template" and len(sys.argv) < 5):
        sys.exit("usage: send_whatsapp.py text TO BODY | template TO NAME LANGUAGE [PARAMS...]")
    kind, to = sys.argv[1], sys.argv[2]
    if kind == "text":
        payload = text_payload(to, sys.argv[3])
    else:
        payload = template_payload(to, sys.argv[3], sys.argv[4], sys.argv[5:])
    try:
        data = send(payload)
    except WhatsAppError as e:
        print(e, file=sys.stderr)
        if e.code == 131047:
            print("Window closed: send an approved template instead.", file=sys.stderr)
        elif e.code == 190:
            print("Token expired: create a new access token.", file=sys.stderr)
        sys.exit(1)
    message = data["messages"][0]
    print("accepted:", message["id"], message.get("message_status", ""))
    print("wa_id:", data["contacts"][0]["wa_id"])

Ang json=payload ang nag-e-encode ng dict at nagse-set ng header para sa iyo. Sinasabi ng Requests docs na kapag nagpasa ka ng string sa data=json.dumps(...), “HINDI nito idadagdag ang Content-Type header” (Requests quickstart).

Pinili ng script na ito ang 10-segundong timeout. Walang dinodokumentong client timeout ang Meta, at nagbababala ang Requests na “kung walang tahasang itinakdang timeout, hindi nagta-time out ang mga request.” Sinasabi rin ng Requests na ang Authorization header na itinakda sa headers= ay “mao-override kung may credentials na nakatakda sa .netrc”. Kung sa iisang machine lang pumapalya ang authentication, tingnan ang file na iyon.

Magpadala ng text message sa loob ng window

Sinusunod ng text payload ang text message reference ng Meta. Hanggang 4096 character ang tinatanggap ng body. Kapag true ang preview_url, susubukan ng WhatsApp client na mag-render ng preview ng unang URL, na dapat magsimula sa http:// o https://.

python send_whatsapp.py text +16505551234 "Your order shipped"

Dumadaan lang ang free-form text sa loob ng 24-oras na window na nagbubukas kapag sumulat sa iyo ang user. Ganito ito sinasabi ng get-started page ng Meta: “Pinapayagan ka ng 24-oras na window na ito na magpadala ng mga non-template message sa mga user sa WhatsApp.” I-format ang to number sa E.164 na may country code; nasa gabay sa E.164 normalization ang mga edge case.

Kapag matagumpay ang call, ipi-print nito ang ID at ang wa_id. Ganito ang hitsura ng response na dinodokumento ng Meta:

{
  "messaging_product": "whatsapp",
  "contacts": [
    {
      "input": "+16505551234",
      "wa_id": "16505551234"
    }
  ],
  "messages": [
    {
      "id": "wamid.HBgLMTY0NjcwNDM1OTUVAgARGBI1RjQyNUE3NEYxMzAzMzQ5MkEA"
    }
  ]
}

Magpadala ng template sa labas ng window

Sa labas ng window, kailangan mo ng template. Sinasabi ng template overview ng Meta na “Ang mga template message lang ang uri ng message na maipapadala sa mga user ng WhatsApp sa labas ng customer service window” (Meta template fundamentals, na-access noong 2026-11-03). Dapat APPROVED ang template, at ipinapadala mo ito gamit ang language code kung saan ito ginawa.

Gumagamit ang halimbawa ng Meta ng template na order_confirmation na may dalawang named body variable. Palitan ang pangalan at mga parameter ng isa sa sarili mong approved na template:

python send_whatsapp.py template +16505551234 order_confirmation en_US first_name=Jessica order_number=SKBUP2-4CPIG9

Binubuo ng script ang parehong body na ipinapakita ng Meta, na may parameter_name sa bawat entry. Para sa template na may positional na {{1}} variable, magpasa ng mga bare value (Jessica SKBUP2-4CPIG9), at hindi na isasama ng script ang parameter_name. Binabasa bilang named ang positional value na may =, kaya baguhin ang parser kung puwedeng magkaroon nito ang mga value mo. Tinalakay sa Mga template variable: positional at named parameter ang mga header at button parameter.

Basahin ang response

I-store ang messages[0].id. Dala ng bawat status webhook para sa message na iyon ang parehong ID, at iyon ang paraan para maitugma mo ang sent, delivered, read at failed pabalik sa record mo (mga status webhook).

Naglilista rin ang messages reference ng Meta ng message_status field sa messages[] (Meta Messages API reference, na-access noong 2026-11-03). Hindi ito ipinapakita ng text message sample, kaya binabasa ito ng script gamit ang .get().

message_status Paglalarawan ng Meta
accepted “Tinanggap na ng WhatsApp ang message at pinoproseso na ito”
held_for_quality_assessment “Pinipigil muna ang message para sa quality assessment bago ang delivery”
paused “Naka-pause ang delivery ng message”

Ibinabalik ng contacts[0].input ang number na ipinadala mo, at ang wa_id ang WhatsApp ID. Sinasabi ng Meta na “maaaring hindi laging magkatugma ang ID at phone number ng isang WhatsApp user” (Meta text message webhook, na-access noong 2026-11-03). I-key ang mga contact mo sa kung ano ang kailangan mo, at i-store ang dalawa.

Kung magpapadala ka ng ilang message nang sunud-sunod, sinasabi ng Meta na “hindi garantisado ang pagkakasunod-sunod ng pag-deliver ng mga message” (Meta send messages, na-access noong 2026-11-03). Para sa isang sequence, hintayin ang delivered webhook ng isang message bago mo ipadala ang susunod. May pattern para dito sa mga webhook na wala sa pagkakasunod-sunod.

Hawakan ang mga error response

Bumabalik ang mga error bilang error object. Ito ang halimbawa ng Meta para sa throughput limit (Meta error codes, na-access noong 2026-11-03):

{
  "error": {
    "message": "(#130429) Rate limit hit",
    "type": "OAuthException",
    "code": 130429,
    "error_data": {
      "messaging_product": "whatsapp",
      "details": "Cloud API message throughput has been reached."
    },
    "error_subcode": 2494055,
    "fbtrace_id": "Az8or2yhqkZfEZ-_4Qn_Bam"
  }
}

Mag-branch ayon sa error.code. Ganito ang payo ng Meta: “Buuin ang error handling ng app mo sa paligid ng mga error code sa halip na mga subcode o HTTP response status code.” Deprecated na ang error_subcode at hindi na ito ibinabalik mula v16.0 pataas. I-log ang fbtrace_id, dahil hinihingi ito ng Direct Support ng Meta.

Code Details ng Meta Ano ang gagawin (script o ikaw)
131047 “More than 24 hours have passed since the recipient last replied to the sender number.” Magpadala ng template (error 131047)
190 “Your access token has expired.” Gumawa ng bagong token
130429 “Cloud API message throughput has been reached.” Maghintay at mag-retry
131056 “Too many messages sent from the sender phone number to the same recipient phone number in a short period of time.” Maghintay at mag-retry sa recipient na iyon
132000 “The number of variable parameter values included in the request did not match…” Ayusin ang mga parameter
132001 “The template does not exist in the specified language or the template has not been approved.” Tingnan ang pangalan, language at status
131026 “Unable to deliver message.” Huwag mag-retry (error 131026)

Maiikling placeholder lang ang 1, 2 at 4 na segundong paghihintay sa send(). Nasa mga rate limit ng Cloud API ang pacing ng Meta para sa 131056.

Hindi lahat ng error ay dumarating sa HTTP response. Sinasabi ng Meta na ibinabalik ang mga error “nang synchronous bilang Graph API response,” o “nang asynchronous sa pamamagitan ng Webhook, o minsan sa parehong paraan”, at inirerekomenda nitong bantayan ang dalawa. Ang 131047 na lumalabas lang sa failed status webhook ay hindi kailanman aabot sa except branch ng script. Hawakan ang parehong mga code sa webhook consumer mo, at hanapin ang iba sa reference ng mga error code ng Cloud API.

Ang Z-API Omni team