Booking appointment ٹیمپلیٹ، Meta کی ایک utility ٹیمپلیٹ type ہے جو ایک ہی پیغام میں appointment کی تصدیق کرتی ہے۔ اس کا مقررہ “View details” (تفصیلات دیکھیں) بٹن ایک sheet کھولتا ہے جس میں booking کی تفصیلات ہوتی ہیں۔ آپ اسے booking_status بٹن کے ساتھ بناتے ہیں، اور بھیجتے وقت start_datetime، جگہ یا فون، اور optional booking_management_url suffix دیتے ہیں۔ اسے booking کے فوراً بعد تصدیق کے لیے استعمال کریں۔ اس میں quick replies نہیں آ سکتے، اس لیے جس یاد دہانی کو Confirm یا Reschedule چاہیے وہ custom ٹیمپلیٹ ہی رہتی ہے۔
Custom یاد دہانی Confirm اور Reschedule کے ساتھ WhatsApp پر appointment کی یاد دہانی میں ہے۔ یہ مضمون ٹیمپلیٹ کے fields، Meta کی اپنی مثالیں اور ان کے باہمی تضادات، اور ایک sender کا احاطہ کرتا ہے جو آپ کے manage page کے ذریعے چکر مکمل کرتا ہے۔
ٹیمپلیٹ میں کیا ہوتا ہے
نیچے کا ہر قاعدہ Meta کے صفحے سے ہے (booking appointment templates، رسائی 2026-11-27)۔
| حصہ | لازمی | حد اور قاعدہ |
|---|---|---|
| Header | ہاں | «صرف text format سپورٹ ہے»، 60 حروف |
| Body | ہاں | 1,024 حروف، named parameters؛ examples «اگر body text میں named parameters ہوں تو لازمی» |
| Footer | نہیں | 60 حروف |
| بٹن | ہاں (یہی type طے کرتا ہے) | ایک booking_status بٹن، label “View details”، جسے «بدلا نہیں جا سکتا» |
booking_url، booking_management_url |
نہیں | ہر ایک 2,000 حروف؛ ایک parameter، جو «URL کے آخر میں ہونا لازمی ہے» |
| Notes | نہیں | 1,024 حروف؛ «زیادہ سے زیادہ 3 embedded URLs رکھ سکتے ہیں» |
Parameter کے نام «underscores کے ساتھ منفرد lowercase string» ہونے چاہییں۔ «صرف ایک booking status بٹن کی اجازت ہے، اور اسے دوسری بٹن types کے ساتھ ملایا نہیں جا سکتا۔» بٹن «ایک bottom sheet کھولتا ہے جس میں appointment کی پوری معلومات ہوتی ہیں»، اور notes «booking details والی bottom sheet میں دکھائے جاتے ہیں۔» Notes میں named parameters، bold، italics، strikethrough، code، \n، bulleted lists اور links آ سکتے ہیں۔ کسی link میں «آخر میں ایک parameterized suffix» ہو سکتا ہے۔
ٹیمپلیٹ کا نام 512 حروف تک ہو سکتا ہے۔ Access token کا «System token» یا «business token» ہونا لازمی ہے۔ اسے حاصل کرنے کا طریقہ WhatsApp Cloud API access tokens میں ہے۔
بھیجتے وقت start_datetime لازمی ہے، time zone کے ساتھ ISO 8601 میں۔ end_datetime، location، phone_number اور email optional ہیں۔ location وہ «جسمانی پتہ ہے جہاں appointment ہوتی ہے»، 100 حروف تک، اور email میں 254 تک آتے ہیں۔ ان سب پر ایک قاعدہ لاگو ہوتا ہے: «بھیجتے وقت آپ کو location، booking_url یا phone_number میں سے کم از کم ایک دینا ہو گا۔»
ٹیمپلیٹ بنائیں: Meta کی مثالیں
یہ Meta کے blocks ہیں جیسے شائع ہوئے، صفحے کی ترتیب میں۔ صفحہ اپنے URLs میں v27.0 دکھاتا ہے۔ ہم نے اسے v26.0 کر دیا، جو version یہ blog استعمال کرتا ہے، اور باقی سب ویسا ہی چھوڑ دیا۔ <!-- --> comments، Meta کے ہیں، اسی لیے syntax blocks ویسے کے ویسے paste کرنے پر نہیں چلتے۔
Request کا syntax:
curl 'https://graph.facebook.com/<API_VERSION>/<WHATSAPP_BUSINESS_ACCOUNT_ID>/message_templates' \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer <ACCESS_TOKEN>' \
-d '
{
"name": "<TEMPLATE_NAME>",
"language": "<TEMPLATE_LANGUAGE>",
"category": "utility",
"parameter_format": "named",
"components": [
{
"type": "header",
"format": "text",
"text": "<HEADER_TEXT>"
},
{
"type": "body",
"text": "<BODY_TEXT>",
<!-- Optional. Required if BODY_TEXT contains named parameters. -->
"example": {
"body_text_named_params": [
{
"param_name": "<BODY_PARAM_NAME>",
"example": "<BODY_PARAM_EXAMPLE>"
}
]
}
},
<!-- Optional -->
{
"type": "footer",
"text": "<FOOTER_TEXT>"
},
{
"type": "buttons",
"buttons": [
{
"type": "booking_status",
<!-- Optional -->
"booking_url": {
"url": "<BOOKING_URL>",
"example": [
"<BOOKING_URL_SUFFIX_EXAMPLE>"
]
},
<!-- Optional -->
"booking_management_url": {
"url": "<BOOKING_MANAGEMENT_URL>",
"example": [
"<BOOKING_MANAGEMENT_URL_SUFFIX_EXAMPLE>"
]
},
<!-- Optional -->
"notes": {
"text": "<NOTES_TEXT>",
"example": {
"notes_named_params": [
{
"param_name": "<NOTES_PARAM_NAME>",
"example": "<NOTES_PARAM_EXAMPLE>"
}
]
}
}
}
]
}
]
}'
Meta کا دکھایا گیا سب سے سادہ ٹیمپلیٹ:
curl 'https://graph.facebook.com/v26.0/102290129340398/message_templates' \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer EAAJB...' \
-d '
{
"name": "dentist_appointment",
"language": "en_US",
"category": "utility",
"parameter_format": "named",
"components": [
{
"type": "header",
"format": "text",
"text": "Dentist appointment"
},
{
"type": "body",
"text": "Hello! Thanks for booking your appointment."
},
{
"type": "buttons",
"buttons": [
{
"type": "booking_status"
}
]
}
]
}'
تمام features والی مثال۔ اسے paste کرنے سے پہلے اگلے حصے میں shell والا نوٹ پڑھ لیں۔
curl 'https://graph.facebook.com/v26.0/102290129340398/message_templates' \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer EAAJB...' \
-d '
{
"name": "succulent_walking_tour",
"language": "en_US",
"category": "utility",
"parameter_format": "named",
"components": [
{
"type": "header",
"format": "text",
"text": "Native succulent walking tour"
},
{
"type": "body",
"text": "Hi {{guest_name}}! Your walking tour is confirmed. A deposit of ${{deposit_amount}} has been received. See you in San Diego!",
"example": {
"body_text_named_params": [
{
"param_name": "guest_name",
"example": "Alex"
},
{
"param_name": "deposit_amount",
"example": "35"
}
]
}
},
{
"type": "footer",
"text": "San Diego Succulent Tours"
},
{
"type": "buttons",
"buttons": [
{
"type": "booking_status",
"booking_url": {
"url": "https://zoom.us/j/{{1}}",
"example": [
"98432167055"
]
},
"booking_management_url": {
"url": "https://sdsucculenttours.com/manage/{{1}}",
"example": [
"tour-20260315-0412"
]
},
"notes": {
"text": "Hi {{guest_name}}! We're excited to take you through Torrey Pines and Balboa Park to explore San Diego's native succulents, including Dudleya, coastal agave, and more.\n\n*What to bring:* comfortable walking shoes, sunscreen, and a water bottle.\n\nConfirmation No.: {{confirmation_number}}\nZoom passcode for the virtual option: {{zoom_passcode}}\n\nCan't make it? Please cancel at least 48 hours in advance. [Cancellation policy](https://sdsucculenttours.com/terms/{{terms_suffix}})",
"example": {
"notes_named_params": [
{
"param_name": "guest_name",
"example": "Alex"
},
{
"param_name": "confirmation_number",
"example": "SDT-84302"
},
{
"param_name": "zoom_passcode",
"example": "547291"
},
{
"param_name": "terms_suffix",
"example": "2026-spring"
}
]
}
}
}
]
}
]
}'
جواب۔ نیا ٹیمپلیٹ PENDING کے طور پر واپس آتا ہے۔
{
"id": "546151681022936",
"status": "PENDING",
"category": "UTILITY"
}
اسے بھیجیں: Meta کی مثالیں
بھیجنے کا syntax۔ Booking کی تفصیلات ایک بٹن component میں، sub_type: "booking_status" اور ایک action parameter کے ساتھ جاتی ہیں۔
curl 'https://graph.facebook.com/<API_VERSION>/<WHATSAPP_BUSINESS_PHONE_NUMBER_ID>/messages' \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer <ACCESS_TOKEN>' \
-d '
{
"messaging_product": "whatsapp",
"recipient_type": "individual",
"to": "<WHATSAPP_USER_PHONE_NUMBER>",
"type": "template",
"template": {
"name": "<TEMPLATE_NAME>",
"language": {
"policy": "deterministic",
"code": "<TEMPLATE_LANGUAGE_CODE>"
},
"components": [
{
"type": "header"
},
{
"type": "body",
<!-- Optional. Required if the template body contains named parameters. -->
"parameters": [
{
"type": "text",
"parameter_name": "<BODY_PARAM_NAME>",
"text": "<BODY_PARAM_VALUE>"
}
]
},
{
"type": "button",
"sub_type": "booking_status",
"index": 0,
"parameters": [
{
"type": "action",
"action": {
"booking_status": {
"start_datetime": "<START_DATETIME>",
<!-- Optional -->
"end_datetime": "<END_DATETIME>",
<!-- Optional. At least one of location, booking_url, or phone_number is required. -->
"location": "<LOCATION>",
<!-- Optional. At least one of location, booking_url, or phone_number is required. -->
"phone_number": "<PHONE_NUMBER>",
<!-- Optional -->
"email": "<EMAIL>",
<!-- Optional. Only include if the template was created with a booking URL. -->
"booking_url": "<BOOKING_URL_SUFFIX>",
<!-- Optional. Only include if the template was created with a booking management URL. -->
"booking_management_url": "<BOOKING_MANAGEMENT_URL_SUFFIX>",
<!-- Optional. Only include if the template was created with notes that contain named parameters. -->
"notes": {
"parameters": [
{
"param_name": "<NOTES_PARAM_NAME>",
"text": "<NOTES_PARAM_VALUE>"
}
]
}
}
}
}
]
}
]
}
}'
سادہ send۔ اس کی تاریخ ماضی کی ہے، جیسا کہ اگلا حصہ بتاتا ہے۔
curl 'https://graph.facebook.com/v26.0/106540352242922/messages' \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer EAAJB...' \
-d '
{
"messaging_product": "whatsapp",
"recipient_type": "individual",
"to": "+16505551234",
"type": "template",
"template": {
"name": "dentist_appointment",
"language": {
"policy": "deterministic",
"code": "en_US"
},
"components": [
{
"type": "header"
},
{
"type": "body"
},
{
"type": "button",
"sub_type": "booking_status",
"index": 0,
"parameters": [
{
"type": "action",
"action": {
"booking_status": {
"start_datetime": "2025-07-10T09:30:00-04:00",
"location": "456 Elm Street, Suite 2B",
"phone_number": "+15550198765"
}
}
}
]
}
]
}
}'
تمام features والا send:
curl 'https://graph.facebook.com/v26.0/106540352242922/messages' \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer EAAJB...' \
-d '
{
"messaging_product": "whatsapp",
"recipient_type": "individual",
"to": "+16505551234",
"type": "template",
"template": {
"name": "succulent_walking_tour",
"language": {
"policy": "deterministic",
"code": "en_US"
},
"components": [
{
"type": "header"
},
{
"type": "body",
"parameters": [
{
"type": "text",
"parameter_name": "guest_name",
"text": "Pablo"
},
{
"type": "text",
"parameter_name": "deposit_amount",
"text": "35"
}
]
},
{
"type": "button",
"sub_type": "booking_status",
"index": 0,
"parameters": [
{
"type": "action",
"action": {
"booking_status": {
"start_datetime": "2026-03-15T09:00:00-07:00",
"end_datetime": "2026-03-15T11:30:00-07:00",
"location": "Torrey Pines State Natural Reserve, San Diego, CA",
"phone_number": "+15550051310",
"email": "[email protected]",
"booking_url": "98432167055",
"booking_management_url": "tour-20260315-0412",
"notes": {
"parameters": [
{
"parameter_name": "guest_name",
"text": "Pablo"
},
{
"parameter_name": "confirmation_number",
"text": "SDT-84302"
},
{
"parameter_name": "zoom_passcode",
"text": "547291"
},
{
"parameter_name": "terms_suffix",
"text": "2026-spring"
}
]
}
}
}
}
]
}
]
}
}'
Send کے جواب میں message ID آتی ہے، جسے آپ status webhooks اور جوابات سے ملائیں گے:
{
"messaging_product": "whatsapp",
"contacts": [
{
"input": "+16505551234",
"wa_id": "16505551234"
}
],
"messages": [
{
"id": "wamid.HBgLMTY0NjcwNDM1OTUVAgARGBI1RjQyNUE3NEYxMzAzMzQ5MkEA"
}
]
}
Meta کی مثالیں کہاں ایک دوسرے سے نہیں ملتیں
اوپر والے blocks کو ویسے ہی نقل کرنے پر Meta کے صفحے کے کئی تضادات سامنے آتے ہیں۔
| کیا | Meta کے صفحے پر کہاں | کیا کریں |
|---|---|---|
Send پر notes کی key: param_name یا parameter_name |
Send syntax، param_name استعمال کرتا ہے؛ مکمل send مثال، parameter_name |
parameter_name بھیجیں، جیسا کہ مکمل مثال اور ہر body parameter کرتے ہیں، اور test کریں۔ بناتے وقت param_name ہر جگہ یکساں ہے |
Notes parameters پر type |
Body parameters میں "type": "text" ہوتا ہے؛ notes parameters میں کسی block میں type نہیں |
اسے نکال دیں، جیسا کہ دونوں blocks کرتے ہیں |
URLs میں {{1}} |
ٹیمپلیٹ parameter_format: "named" ہے، لیکن URLs میں positional {{1}} ہے |
URLs میں {{1}} رکھیں، جیسا کہ صفحہ دکھاتا ہے |
| API version | ہر مثال v27.0 استعمال کرتی ہے |
وہ version استعمال کریں جو آپ کی app target کرتی ہے؛ یہ blog، v26.0 استعمال کرتا ہے |
| Casing | Lowercase "utility"، "named"، "header"، "buttons" |
Meta کا اپنا create جواب ("category": "UTILITY") uppercase استعمال کرتا ہے؛ ایک casing چنیں اور اسی پر رہیں |
to کا format |
Plus کے ساتھ "+16505551234" |
Meta کی webhook مثالیں صرف digits استعمال کرتی ہیں؛ نیچے والا sender، digits محفوظ کرتا ہے اور plus کے بغیر بھیجتا ہے |
| تاریخیں | سادہ send میں 2025-07-10، مکمل میں 2026-03-15 |
آج دونوں ماضی کی ہیں؛ start_datetime ہمیشہ اصلی booking سے بنائیں |
| Shell quoting | مکمل creation مثال کے notes میں “We’re”، “San Diego’s” اور “Can’t”، single-quoted -d '...' کے اندر ہیں |
POSIX shell میں یہ apostrophes، string کو وقت سے پہلے ختم کر دیتے ہیں، اور bash -n syntax error بتاتا ہے۔ JSON کو فائل میں محفوظ کریں اور -d @template.json سے بھیجیں |
Shell والا مسئلہ، block کو پڑھ کر ہمارا نتیجہ ہے، Meta کے صفحے کا کوئی نوٹ نہیں۔ Send والے blocks میں کوئی apostrophe نہیں، اور token اور IDs بدلنے کے بعد چلتے ہیں۔
یہ utility کے طور پر کیوں پاس ہوتا ہے
یہ ٹیمپلیٹ، Meta کے utility ٹیمپلیٹس کے تحت آتا ہے، اور اس کی create کال "category": "utility" سیٹ کرتی ہے۔ مواد کو پھر بھی Meta کا ٹیسٹ پاس کرنا ہوتا ہے: «غیر تشہیری ہونا لازمی ہے» اور «صارف سے مخصوص یا اس کا مانگا ہوا (واضح طور پر اس کے آرڈر، اکاؤنٹ، سروسز یا transactions سے متعلق)» (template categorization، رسائی 2026-11-27)۔ کسٹمر کی ابھی کی گئی booking کی تصدیق دونوں شرطیں پوری کرتی ہے۔ Body یا notes میں discount کی ایک لائن اسے مارکیٹنگ بنا دیتی ہے۔
Template Library میں clone کرنے کے لیے booking کی کوئی تیار type نہیں۔ اس کی industries، E_COMMERCE اور FINANCIAL_SERVICES ہیں (Template Library، رسائی 2026-11-25)۔ Clinics کے لیے header، body اور notes میں صرف وقت، جگہ اور professional کا نام رکھیں۔ Sheet وہی دکھاتی ہے جو آپ notes میں ڈالیں، اس لیے وہاں بھی کوئی طبی معلومات نہ جائے۔
ٹیپ webhook کے بغیر چکر
Meta کا صفحہ “View details” ٹیپ کا کوئی webhook دستاویز نہیں کرتا۔ آپ نہیں جان سکتے کہ کسٹمر نے sheet کھولی یا نہیں۔ اس لیے چکر کا جواب والا قدم آپ کے اپنے سسٹمز سے آتا ہے۔
- آپ کا booking سسٹم ایک booking محفوظ کرتا ہے اور sender سے اس کی تصدیق بھیجنے کو کہتا ہے۔
- Sender ٹیمپلیٹ ایک management suffix کے ساتھ بھیجتا ہے جو اسی booking سے جڑا ہوتا ہے۔
- کسٹمر “View details” کھولتا ہے اور
booking_management_urlکے ذریعے آپ کے manage page پر جاتا ہے۔ - آپ کا manage page، booking بدلتا ہے اور sender کو کال کرتا ہے، جو نیا وقت بھیجتا ہے۔
- کسٹمر چیٹ میں جو آزاد text لکھے وہ عام
messageswebhook کے طور پر آتا ہے اور booking پر ایک note بن جاتا ہے۔
Meta کا صفحہ پہلے سے بھیجے گئے پیغام کو edit کرنے کا کوئی طریقہ نہیں بتاتا۔ تبدیلی نئے پیغام کے طور پر جاتی ہے، اور Meta یہ دستاویز نہیں کرتی کہ اس کے بعد پرانی sheet کیا دکھاتی ہے۔ اگر manage page، Calendly ہے تو reschedule_url کی ID شاید suffix کے طور پر فٹ ہو جائے، جسے Calendly webhooks سے WhatsApp ایک test کرنے والا اندازہ مانتا ہے۔
Booking ٹیمپلیٹ یا custom ٹیمپلیٹ
| ضرورت | Booking appointment ٹیمپلیٹ | Custom utility ٹیمپلیٹ |
|---|---|---|
| بٹن | ایک booking_status، مقررہ label “View details” |
10 quick replies تک، ساتھ URL اور فون بٹن |
| ایسا جواب جو آپ کا webhook پڑھ سکے | “View details” کے لیے کوئی دستاویزی نہیں | آپ کے payload والا button پیغام |
| تاریخ اور وقت | Send پر start_datetime اور end_datetime |
آپ خود format کر کے body میں ڈالتے ہیں |
| Manage link | booking_management_url |
ایک suffix والا URL بٹن |
| کس کے لیے موزوں | Booking کے فوراً بعد تصدیق | وہ یاد دہانی جسے Confirm، Cancel یا Reschedule چاہیے |
زیادہ تر bookings دونوں استعمال کرتی ہیں۔ Booking ٹیمپلیٹ تصدیق کرتا ہے، اور ایک custom ٹیمپلیٹ ایک دن پہلے یاد دلاتا ہے، جیسا کہ یاد دہانی والے بنیادی مضمون اور Cal.com webhooks سے WhatsApp یاد دہانیاں میں ہے۔ اگر کوئی slot خالی ہو جائے تو waitlist refill والا مضمون اسے اگلے کسٹمر کو پیش کرتا ہے۔
آپ کا اپنا ٹیمپلیٹ اور sender
اس ٹیمپلیٹ میں ایک text header، دو named parameters والی body، ایک manage link اور ایک notes parameter ہے۔ example.com کو اپنے manage page کے host سے بدلیں۔ Named parameters اور ان کی examples، WhatsApp ٹیمپلیٹ variables میں سمجھائے گئے ہیں۔
curl "https://graph.facebook.com/v26.0/$WABA_ID/message_templates" \
-H "Authorization: Bearer $WA_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"name": "appointment_booked",
"language": "en_US",
"category": "utility",
"parameter_format": "named",
"components": [
{ "type": "header", "format": "text", "text": "Appointment confirmed" },
{
"type": "body",
"text": "Hi {{guest_name}}, your {{service}} is booked. Tap View details for the time, the place and a link to change it.",
"example": {
"body_text_named_params": [
{ "param_name": "guest_name", "example": "Marina" },
{ "param_name": "service", "example": "haircut" }
]
}
},
{
"type": "buttons",
"buttons": [
{
"type": "booking_status",
"booking_management_url": {
"url": "https://example.com/manage/{{1}}",
"example": ["k3J9xQ2pLwV8"]
},
"notes": {
"text": "Confirmation No.: {{confirmation_number}}\nReply to this chat if you have a question.",
"example": {
"notes_named_params": [
{ "param_name": "confirmation_number", "example": "BK-1042" }
]
}
}
}
]
}
]
}'
Sender، Python 3.9 یا اس سے نئے پر صرف standard library کے ساتھ چلتا ہے۔ یہ bookings کو memory میں رکھتا ہے تاکہ آپ اسے آزما سکیں۔ NOTES_PARAM_KEY سے آپ Meta کا تضاد test کرتے وقت parameter_name اور param_name کے درمیان بدل سکتے ہیں۔
# booking_template_service.py: send Meta's booking appointment template and record replies.
# Python 3.9+ standard library only. Run: python3 booking_template_service.py
import hashlib
import hmac
import json
import os
import re
import secrets
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
from datetime import datetime, timezone
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from zoneinfo import ZoneInfo
def env(name, default=None):
value = os.environ.get(name, default)
if not value:
raise SystemExit(f"Missing environment variable {name}")
return value
WA_TOKEN = env("WA_TOKEN")
PHONE_NUMBER_ID = env("PHONE_NUMBER_ID")
APP_SECRET = env("APP_SECRET")
VERIFY_TOKEN = env("VERIFY_TOKEN")
INTERNAL_TOKEN = env("INTERNAL_TOKEN")
TEMPLATE_NAME = env("TEMPLATE_NAME", "appointment_booked")
CHANGED_TEMPLATE = env("CHANGED_TEMPLATE", TEMPLATE_NAME) # a second template if you want other wording
NOTES_PARAM_KEY = env("NOTES_PARAM_KEY", "parameter_name") # Meta's syntax block shows param_name
PORT = int(env("PORT", "3000"))
GRAPH_URL = f"https://graph.facebook.com/v26.0/{PHONE_NUMBER_ID}/messages"
lock = threading.Lock()
bookings = {} # booking id -> booking
by_wamid = {} # confirmation wamid -> booking id
seen_inbound = set() # inbound wamids already handled
def to_datetime(value, tz_name):
dt = datetime.fromisoformat(str(value).replace("Z", "+00:00"))
return dt if dt.tzinfo else dt.replace(tzinfo=ZoneInfo(tz_name))
def check_times(start, end):
if start <= datetime.now(timezone.utc):
raise ValueError("start is in the past")
if end and end <= start:
raise ValueError("end must be after start")
def build_booking(data):
booking_id = str(data.get("booking_id", ""))
phone = re.sub(r"\D", "", str(data.get("phone", "")))
if not re.fullmatch(r"[\w-]{1,64}", booking_id):
raise ValueError("booking_id must be 1-64 letters, digits, _ or -")
if not re.fullmatch(r"[1-9]\d{7,14}", phone):
raise ValueError("phone must be E.164 with the country code")
if data.get("whatsapp_opt_in") is not True:
raise ValueError("no WhatsApp opt-in recorded for this booking")
tz_name = str(data.get("time_zone", "UTC"))
start = to_datetime(data["start"], tz_name)
end = to_datetime(data["end"], tz_name) if data.get("end") else None
check_times(start, end)
location = str(data.get("location") or "")
contact_phone = str(data.get("contact_phone") or "")
if len(location) > 100:
raise ValueError("location is limited to 100 characters")
if not location and not contact_phone:
raise ValueError("Meta needs location, booking_url or phone_number at send time")
return {
"id": booking_id,
"phone": phone,
"guest_name": str(data.get("guest_name") or "there"),
"service": str(data.get("service") or "appointment"),
"start": start,
"end": end,
"time_zone": tz_name,
"location": location,
"contact_phone": contact_phone,
"confirmation_number": str(data.get("confirmation_number") or booking_id),
"manage_token": secrets.token_urlsafe(12), # your manage page maps this token to the booking
"opt_in": True,
"state": "new",
"customer_notes": [],
}
def booking_message(b, template):
status = {"start_datetime": b["start"].isoformat(timespec="seconds")}
if b["end"]:
status["end_datetime"] = b["end"].isoformat(timespec="seconds")
if b["location"]:
status["location"] = b["location"]
if b["contact_phone"]:
status["phone_number"] = b["contact_phone"]
status["booking_management_url"] = b["manage_token"]
status["notes"] = {"parameters": [{NOTES_PARAM_KEY: "confirmation_number", "text": b["confirmation_number"]}]}
return {
"messaging_product": "whatsapp",
"recipient_type": "individual",
"to": b["phone"],
"type": "template",
"template": {
"name": template,
"language": {"policy": "deterministic", "code": "en_US"},
"components": [
{"type": "header"},
{
"type": "body",
"parameters": [
{"type": "text", "parameter_name": "guest_name", "text": b["guest_name"]},
{"type": "text", "parameter_name": "service", "text": b["service"]},
],
},
{
"type": "button",
"sub_type": "booking_status",
"index": 0,
"parameters": [{"type": "action", "action": {"booking_status": status}}],
},
],
},
}
def send_whatsapp(payload, attempts=4):
data = json.dumps(payload).encode("utf-8")
last = ""
for attempt in range(1, attempts + 1):
request = urllib.request.Request(GRAPH_URL, data=data, method="POST", headers={
"Authorization": f"Bearer {WA_TOKEN}",
"Content-Type": "application/json",
})
try:
with urllib.request.urlopen(request, timeout=15) as response:
return json.load(response)["messages"][0]["id"]
except urllib.error.HTTPError as err:
detail = err.read().decode("utf-8", "replace")
if err.code != 429 and err.code < 500:
raise RuntimeError(f"Meta returned {err.code}: {detail}") # template or parameter mismatch
last = f"HTTP {err.code}: {detail}"
except (urllib.error.URLError, OSError) as err:
last = str(err)
if attempt < attempts:
time.sleep(2 ** attempt)
raise RuntimeError(f"send failed after {attempts} attempts: {last}")
def send_text(to, body):
try:
send_whatsapp({"messaging_product": "whatsapp", "to": to, "type": "text", "text": {"body": body}})
except RuntimeError as err:
print("reply failed", to, err)
def write_back(booking, text):
# Replace with a note or comment on the booking in your own system.
booking["customer_notes"].append({"at": datetime.now(timezone.utc).isoformat(), "text": text})
print("note added to booking", booking["id"], repr(text))
def find_booking(msg):
context_id = (msg.get("context") or {}).get("id")
with lock:
if context_id in by_wamid:
return bookings.get(by_wamid[context_id])
mine = [b for b in bookings.values() if b["phone"] == msg.get("from") and b["state"] == "sent"]
return max(mine, key=lambda b: b["start"]) if mine else None
def handle_message(msg):
with lock:
if msg.get("id") in seen_inbound:
return # Meta retried this webhook
seen_inbound.add(msg.get("id"))
sender = msg.get("from")
if msg.get("type") != "text" or not sender:
return
text = (msg.get("text") or {}).get("body", "").strip()
if re.fullmatch(r"(?i)stop", text):
with lock:
for b in bookings.values():
if b["phone"] == sender:
b["opt_in"] = False
send_text(sender, "You will not get booking messages here anymore.")
return
booking = find_booking(msg)
if booking is None:
print("message with no booking", msg.get("id"))
return
write_back(booking, text)
send_text(sender, "Thanks, we added your message to your booking. To change the time, use the link in your confirmation.")
class Handler(BaseHTTPRequestHandler):
def reply(self, code, obj):
body = json.dumps(obj, default=str).encode("utf-8")
self.send_response(code)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_GET(self):
url = urllib.parse.urlparse(self.path)
query = urllib.parse.parse_qs(url.query)
if url.path == "/webhook" and query.get("hub.mode") == ["subscribe"] \
and query.get("hub.verify_token") == [VERIFY_TOKEN]:
challenge = query.get("hub.challenge", [""])[0].encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "text/plain")
self.send_header("Content-Length", str(len(challenge)))
self.end_headers()
self.wfile.write(challenge)
return
self.reply(403, {"error": "verification failed"})
def do_POST(self):
path = urllib.parse.urlparse(self.path).path
raw = self.rfile.read(int(self.headers.get("Content-Length") or 0))
if path == "/webhook":
return self.webhook(raw)
auth = self.headers.get("Authorization", "").encode("utf-8")
if not hmac.compare_digest(auth, f"Bearer {INTERNAL_TOKEN}".encode("utf-8")):
return self.reply(401, {"error": "unauthorized"})
try:
data = json.loads(raw or b"{}")
except ValueError:
return self.reply(400, {"error": "invalid JSON"})
if path == "/bookings":
return self.confirm(data)
if path == "/bookings/changed":
return self.changed(data)
return self.reply(404, {"error": "not found"})
def confirm(self, data):
try:
booking = build_booking(data)
except (KeyError, ValueError, TypeError) as err:
return self.reply(400, {"error": str(err)})
with lock:
existing = bookings.get(booking["id"])
if existing and existing["state"] != "send_failed":
return self.reply(200, {"booking_id": existing["id"], "manage_token": existing["manage_token"]})
bookings[booking["id"]] = booking
return self.send_booking(booking, TEMPLATE_NAME, 201)
def changed(self, data):
# Your manage page calls this after the customer moves the booking.
with lock:
booking = bookings.get(str(data.get("booking_id", "")))
if booking is None:
return self.reply(404, {"error": "unknown booking"})
if not booking["opt_in"]:
return self.reply(409, {"error": "customer opted out of WhatsApp"})
try:
tz_name = str(data.get("time_zone", booking["time_zone"]))
start = to_datetime(data["start"], tz_name)
end = to_datetime(data["end"], tz_name) if data.get("end") else None
check_times(start, end)
except (KeyError, ValueError, TypeError) as err:
return self.reply(400, {"error": str(err)})
with lock:
booking.update(start=start, end=end, time_zone=tz_name)
return self.send_booking(booking, CHANGED_TEMPLATE, 200)
def send_booking(self, booking, template, code):
try:
wamid = send_whatsapp(booking_message(booking, template))
except RuntimeError as err:
booking["state"] = "send_failed"
return self.reply(502, {"error": str(err)})
with lock:
booking["state"] = "sent"
by_wamid[wamid] = booking["id"]
return self.reply(code, {"booking_id": booking["id"], "manage_token": booking["manage_token"], "wamid": wamid})
def webhook(self, raw):
expected = "sha256=" + hmac.new(APP_SECRET.encode("utf-8"), raw, hashlib.sha256).hexdigest()
received = self.headers.get("X-Hub-Signature-256", "").encode("utf-8")
if not hmac.compare_digest(received, expected.encode("utf-8")):
return self.reply(401, {"error": "bad signature"})
self.reply(200, {"ok": True}) # answer first, work after
try:
body = json.loads(raw)
except ValueError:
return
for entry in body.get("entry", []):
for change in entry.get("changes", []):
if change.get("field") != "messages":
continue
value = change.get("value", {})
for status in value.get("statuses", []):
if status.get("status") == "failed":
print("send failed", by_wamid.get(status.get("id")), json.dumps(status.get("errors")))
for msg in value.get("messages", []):
handle_message(msg)
if __name__ == "__main__":
print(f"listening on {PORT}")
ThreadingHTTPServer(("", PORT), Handler).serve_forever()
اپنے سسٹم سے ایک کال کے ذریعے booking کی تصدیق کریں۔ جواب میں manage_token آتا ہے، جس سے آپ کا manage page، booking تلاش کرتا ہے۔
curl -X POST http://localhost:3000/bookings \
-H "Authorization: Bearer $INTERNAL_TOKEN" \
-H "Content-Type: application/json" \
-d '{"booking_id":"bk-1042","phone":"+16505551234","guest_name":"Marina","service":"haircut","start":"2026-12-03T09:30","end":"2026-12-03T10:15","time_zone":"America/New_York","location":"456 Elm Street, Suite 2B","confirmation_number":"BK-1042","whatsapp_opt_in":true}'
Manage token بے ترتیب (random) ہے، کیونکہ جس کے پاس بھی link ہو وہ آپ کا manage page کھول سکتا ہے۔ اس page پر token کو booking سے ملا کر چیک کریں، اور appointment کے بعد اسے expire کر دیں۔
جب چکر ٹوٹ جائے
Meta، send رد کر دیتی ہے
Meta کا 4xx عموماً نام، زبان یا parameter کی عدم مطابقت کا مطلب ہوتا ہے۔ Sender انہیں retry نہیں کرتا اور Meta کی body کے ساتھ 502 واپس کرتا ہے۔ اگر error، notes کی طرف اشارہ کرے تو NOTES_PARAM_KEY کو param_name کریں اور دوبارہ بھیجیں۔ location اور phone_number دونوں کا نہ ہونا کال سے پہلے ہی پکڑا جاتا ہے، کیونکہ Meta ان میں سے ایک مانگتی ہے۔
تاریخ غلط ہے یا ماضی کی ہے
Sender ماضی کا start اور start سے پہلے کا end قبول نہیں کرتا۔ Offset کے بغیر مقامی وقت، booking کے time_zone میں پڑھا جاتا ہے، اس لیے America/New_York میں 2026-12-03T09:30، -05:00 کے ساتھ جاتا ہے۔
ایک ہی webhook دو بار آتا ہے
Meta ان webhooks کو retry کرتی ہے جنہیں وہ ناکام سمجھے۔ Sender ہر وہ inbound message ID چھوڑ دیتا ہے جو پہلے دیکھی ہو، اس لیے retry ہوا جواب ایک ہی note بنتا ہے۔ Production سے پہلے seen_inbound کو unique key والی table میں لے جائیں۔
کسٹمر opt out کرتا ہے یا خاموش رہتا ہے
STOP والا جواب اس نمبر کی ہر booking پر رضامندی ختم کر دیتا ہے، اور پھر /bookings/changed بھیجنے سے انکار کرتا ہے۔ جواب نہ آنے کا کوئی مطلب نہیں، کیونکہ ٹیمپلیٹ کوئی جواب مانگتا ہی نہیں۔ Confirm مانگنے کی جگہ یاد دہانی والا ٹیمپلیٹ ہے۔
Meta کے قبول کرنے کے بعد send کا time out
Sender، network errors، 429 اور 5xx کو backoff کے ساتھ تین بار retry کرتا ہے۔ قبول ہونے کے بعد timeout سے دوسری تصدیق جا سکتی ہے۔ اگر یہ ایک چھوٹ جانے والی تصدیق سے زیادہ اہم ہے تو کوششوں کی تعداد کم کریں۔ Status سنبھالنے کا طریقہ WhatsApp message status webhooks میں ہے۔
Z-API Omni کہاں کام آتا ہے
Omni کے docs اس ٹیمپلیٹ کا احاطہ نہیں کرتے۔ اس کی create-template بٹن types یہ ہیں: QUICK_REPLY، URL، PHONE_NUMBER، COPY_CODE، OTP، FLOW، CATALOG، MPM، SPM، PAYMENT_REQUEST، ORDER_DETAILS اور VOICE_CALL، اور ان میں booking_status نہیں۔ اس کا send schema صرف type اور text والے parameters لیتا ہے، action کے بغیر۔ اس لیے docs، booking appointment ٹیمپلیٹ بھیجنے کا کوئی طریقہ نہیں دکھاتے، اور یہ مضمون بھی اس کی کوئی request نہیں دکھاتا۔
Docs جس چیز کا احاطہ کرتے ہیں وہ QUICK_REPLY اور URL بٹنوں والا custom utility ٹیمپلیٹ ہے۔ آپ اسے POST /whatsapp/businesses/{wabaId}/templates سے بناتے ہیں، جو message_send_ttl_seconds قبول کرتا ہے، اور URL بٹن آخر میں ایک variable لیتا ہے۔ ٹیمپلیٹس، Meta Cloud API channels پر کام کرتے ہیں، جہاں Meta کی فیس آگے منتقل ہوتی ہے۔
Z-API Omni ٹیم