WhatsApp· 5 min basahin

Magpadala at tumanggap ng location at contact message sa WhatsApp


Para magpadala ng location sa WhatsApp, gamitin ang "type": "location" at isang location object na may latitude at longitude bilang string, kasama ang optional na name at address. Ang mga contact card ay gumagamit ng "type": "contacts" at isang contacts array. Kapag nag-share ang user ng alinman sa dalawa sa iyo, ibinabalik ng messages webhook ang parehong mga object, at JSON number na ang mga coordinate.

Service message ang tatlong uri ng message sa post na ito. Sinasabi ng send guide ng Meta na kapag nagsara na ang customer service window (24 oras), “pre-approved na template message lang ang puwede mong ipadala” (send messages ng Meta, na-access noong 2026-11-04). Sa labas ng window, pumapalya ang mga send na ito nang may error 131047.

Magpadala ng location

Apat na field ang tinatanggap ng location object (location messages ng Meta, na-access noong 2026-11-04). Required na string sa decimal degrees ang latitude at longitude. Optional ang name at address, at walang nakasaad na length limit ang Meta para sa alinman. Ito ang body ng halimbawa ng Meta.

{
  "messaging_product": "whatsapp",
  "recipient_type": "individual",
  "to": "+16505551234",
  "type": "location",
  "location": {
    "latitude": "37.44216251868683",
    "longitude": "-122.16153582049394",
    "name": "Philz Coffee",
    "address": "101 Forest Ave, Palo Alto, CA 94301"
  }
}

Karaniwan ang anyo ng response: nasa contacts[0].wa_id ang recipient at nasa messages[0].id ang message ID. Ibig sabihin ng ID na iyon, tinanggap ng Meta ang send. Darating mamaya ang delivery bilang status webhook.

Hingin sa user ang location niya

Nagpapakita ang location request message ng button na nagbubukas sa location sharing screen ng WhatsApp. Interactive message ito na naka-set ang interactive.type sa location_request_message at ang action.name sa send_location (location request messages ng Meta, na-access noong 2026-11-04). Hanggang 1024 character ang body text. Ito ang body ng halimbawa ng Meta, inalis sa curl call nito, kung saan naka-shell-escape ang apostrophe.

{
  "messaging_product": "whatsapp",
  "recipient_type": "individual",
  "type": "interactive",
  "to": "+16505551234",
  "interactive": {
    "type": "location_request_message",
    "body": {
      "text": "Let's start with your pickup. You can either manually *enter an address* or *share your current location*."
    },
    "action": {
      "name": "send_location"
    }
  }
}

Ordinaryong type: location message ang sagot. May dala itong context object na ang id ay ID ng request mo, kaya maitutugma mo ang sagot sa tanong na ipinadala mo. Lumalabas lang ang address at name kung piliin ng user na i-share ang mga ito. Nasa interactive buttons at list messages ang ibang interactive type at ang mga limit nila.

Magpadala ng contact card

Kailangan ng bawat entry sa contacts ng name na may formatted_name (contacts messages ng Meta, na-access noong 2026-11-04). Optional ang addresses, birthday (YYYY-MM-DD), emails, org, phones at urls. Minamarkahan ng Messages API reference ang contact object ng “Additional Properties: Not allowed” (Messages API reference ng Meta, na-access noong 2026-11-04). Ang mga nakalistang field lang ang ipadala.

Binabago ng wa_id sa isang phone entry ang nakikita ng recipient. Kapag mayroon nito, may Message at Save contact na button ang card. Sinasabi ng Meta na “kapag inalis mo ang wa_id property, papalitan ang dalawang button ng Invite to WhatsApp na button”.

Pinapayagan ng Meta ang “hanggang 257 contact” bawat message at inirerekomenda nitong magpadala nang mas kaunti. Ang mga address, birthday at email ay “maaaring hindi suportado ng recipient, lalo na sa primary device niya”. Umasa sa name at phone entry, at ituring na dagdag ang iba na baka hindi lumabas.

Magpadala at mag-parse mula sa Python

Ipinapadala ng script na ito ang tatlong uri ng message at pina-parse ang papasok na location at contacts webhook. Sinusundan ng mga send payload ang mga halimbawa ng Meta. Ang contact sender ay minimal na card na binuo mula sa field reference, may pangalan at isang phone. Kailangan nito ng Python 3.9 o mas bago at ng requests.

# location_contacts.py
import json
import os
import sys

import requests

GRAPH_VERSION = os.environ.get("GRAPH_VERSION", "v26.0")


def post_message(payload):
    url = (
        f"https://graph.facebook.com/{GRAPH_VERSION}/"
        f"{os.environ['PHONE_NUMBER_ID']}/messages"
    )
    headers = {"Authorization": f"Bearer {os.environ['WHATSAPP_TOKEN']}"}
    r = requests.post(url, json=payload, headers=headers, timeout=10)
    try:
        data = r.json()
    except ValueError:  # a non-JSON error page
        r.raise_for_status()
        raise
    if not r.ok or "error" in data:
        err = data.get("error", {})
        sys.exit(f"HTTP {r.status_code}, code {err.get('code')}: {err.get('message')}")
    return data["messages"][0]["id"]


def base(to, kind):
    return {"messaging_product": "whatsapp", "recipient_type": "individual", "to": to, "type": kind}


def location_payload(to, lat, lng, name=None, address=None):
    location = {"latitude": str(lat), "longitude": str(lng)}  # strings when sending
    if name:
        location["name"] = name
    if address:
        location["address"] = address
    return {**base(to, "location"), "location": location}


def location_request_payload(to, text):
    interactive = {
        "type": "location_request_message",
        "body": {"text": text},
        "action": {"name": "send_location"},
    }
    return {**base(to, "interactive"), "interactive": interactive}


def contact_payload(to, formatted_name, phone, wa_id=None):
    entry = {"phone": phone, "type": "Mobile"}
    if wa_id:
        entry["wa_id"] = wa_id  # without it the card shows Invite to WhatsApp
    name = {"formatted_name": formatted_name, "first_name": formatted_name.split()[0]}
    return {**base(to, "contacts"), "contacts": [{"name": name, "phones": [entry]}]}


def parse_event(event):
    found = []
    for entry in event.get("entry", []):
        for change in entry.get("changes", []):
            for msg in change.get("value", {}).get("messages", []):
                sender = msg.get("from") or msg.get("from_user_id")
                if msg.get("type") == "location":
                    loc = msg["location"]
                    found.append({
                        "type": "location",
                        "sender": sender,
                        "lat": float(loc["latitude"]),  # numbers when receiving
                        "lng": float(loc["longitude"]),
                        "name": loc.get("name"),
                        "address": loc.get("address"),
                        "url": loc.get("url"),
                        "in_reply_to": msg.get("context", {}).get("id"),
                    })
                elif msg.get("type") == "contacts":
                    for card in msg.get("contacts", []):
                        found.append({
                            "type": "contact",
                            "sender": sender,
                            "name": card.get("name", {}).get("formatted_name"),
                            "phones": [[p.get("phone"), p.get("wa_id")] for p in card.get("phones", [])],
                            "origin": card.get("origin"),
                            "has_vcard": "vcard" in card,
                        })
    return found


USAGE = (
    "usage: location_contacts.py location TO LAT LNG [NAME] [ADDRESS]"
    " | ask-location TO TEXT | contact TO FORMATTED_NAME PHONE [WA_ID] | parse FILE"
)

if __name__ == "__main__":
    args = sys.argv[1:]
    cmd = args[0] if args else ""
    if cmd == "location" and len(args) >= 4:
        print("accepted:", post_message(location_payload(*args[1:6])))
    elif cmd == "ask-location" and len(args) == 3:
        print("accepted:", post_message(location_request_payload(args[1], args[2])))
    elif cmd == "contact" and len(args) >= 4:
        print("accepted:", post_message(contact_payload(*args[1:5])))
    elif cmd == "parse" and len(args) == 2:
        with open(args[1]) as f:
            for item in parse_event(json.load(f)):
                print(json.dumps(item))
    else:
        sys.exit(USAGE)

Patakbuhin ang mga send nang nasa environment ang token at number ID mo.

pip install requests
export WHATSAPP_TOKEN="ACCESS_TOKEN"
export PHONE_NUMBER_ID="PHONE_NUMBER_ID"
python location_contacts.py location +16505551234 37.44216251868683 -122.16153582049394 "Philz Coffee" "101 Forest Ave, Palo Alto, CA 94301"
python location_contacts.py ask-location +16505551234 "Share your pickup location."
python location_contacts.py contact +16505551234 "Barbara J. Johnson" +19175559999 19175559999

Ang first_name sa contact_payload ay ang unang salita ng formatted name. Palitan ito ng totoong bahagi ng pangalan kung naka-store ang mga iyon sa iyo.

Tumanggap ng location

Nagfi-fire ang location webhook kapag nagpadala ng location ang user, kasama na sa pamamagitan ng Click to WhatsApp ad (location webhook ng Meta, na-access noong 2026-11-04). JSON number ang papasok na latitude at longitude, samantalang string ang ipinapadala mo. Inilalarawan ng Meta ang url bilang “Kadalasan, kasama lang para sa mga business location.” I-save ang halimbawa ng Meta bilang location.json para i-test ang parser.

{
  "object": "whatsapp_business_account",
  "entry": [
    {
      "id": "102290129340398",
      "changes": [
        {
          "value": {
            "messaging_product": "whatsapp",
            "metadata": {
              "display_phone_number": "15550783881",
              "phone_number_id": "106540352242922"
            },
            "contacts": [
              {
                "profile": {
                  "name": "Sheena Nelson"
                },
                "wa_id": "16505551234"
              }
            ],
            "messages": [
              {
                "from": "16505551234",
                "id": "wamid.HBgLMTY1MDM4Nzk0MzkVAgASGBQzQUFERjg0NDEzNDdFODU3MUMxMAA=",
                "timestamp": "1744344496",
                "location": {
                  "address": "101 Forest Ave, Palo Alto, CA 94301",
                  "latitude": 37.44221496582,
                  "longitude": -122.16165924072,
                  "name": "Philz Coffee",
                  "url": "https://philzcoffee.com/"
                },
                "type": "location"
              }
            ]
          },
          "field": "messages"
        }
      ]
    }
  ]
}
python location_contacts.py parse location.json

Kino-convert ng parser ang dalawang coordinate gamit ang float(), kaya tumatanggap ito ng string at number. Lumalabas lang ang referral object sa mga message mula sa Click to WhatsApp ad. Walang sinasabi ang location webhook page ng Meta tungkol sa live location, kaya i-test ang kasong iyon sa totoong device bago ka umasa rito.

Tumanggap ng contact card

Parehong contacts array ang gamit ng papasok na contacts, pero may mga puwang (contacts webhook ng Meta, na-access noong 2026-11-04). Nagbababala ang Meta na “maraming contact property ang maaaring wala” kapag hindi ibinibigay ng user o ng device ang mga ito. Iba-iba ang phone type, gaya ng mga halimbawa ng Meta na “cell, mobile, main, iPhone, home, or work”. Dahil dito, binabasa ng parser ang bawat field gamit ang .get().

May mga field sa business-scoped user IDs page ng Meta na hindi pa ipinapakita ng contacts webhook page (business-scoped user IDs ng Meta, na-access noong 2026-11-04). Idinagdag ng changelog entry nito noong Mayo 4, 2026 ang from_user_id, origin at vcard sa contacts payload. Ang origin ng bawat card ay contact_request kapag pinindot ng user ang REQUEST_CONTACT_INFO button, at other kapag nag-share siya ng contact sa chat.

Nasa vcard ang vCard ng user kapag other lang ang origin. Sinasabi rin ng parehong page na ang from ay “Aalisin kung hindi maisasama ang phone number”, kaya bumabalik ang parser sa from_user_id. Nasa mga username at business-scoped user ID ang buong patakaran.

Para hingin ang sariling detalye ng user, dinodokumento ng Meta sa parehong page ang interactive na request_contact_info message. Pinalitan ang pangalan nito mula sa contact_request noong Mayo 28, 2026.

Mga field limit na hindi inilalathala ng Meta

Walang inilalathalang character limit ang Meta para sa location name at address, o para sa mga contact field. Ang mga dinodokumentong limit ay ang 1024-character na body sa mga location request at ang 257 contact bawat message. I-validate ang haba batay sa kayang i-store ng sarili mong database. Kung ini-store mo ang mga ito katabi ng mga Telegram o Instagram message, tingnan ang iisang message model para sa apat na channel. Nasa Express webhook guide ang isang Node.js receiver.

Ang Z-API Omni team