Il modello per gli appuntamenti (booking appointment template) è un tipo di modello utility di Meta che conferma un appuntamento in un solo messaggio. Il suo pulsante fisso “View details” (Vedi dettagli) apre un pannello con i dettagli della prenotazione. Lo crei con un pulsante booking_status e, al momento dell’invio, passi start_datetime, un luogo o un telefono, e un suffisso facoltativo per booking_management_url. Usalo per la conferma subito dopo la prenotazione. Non può portare risposte rapide, quindi un promemoria che richiede Confirm (Conferma) o Reschedule (Riprogramma) resta un modello personalizzato.
Il promemoria personalizzato è in promemoria degli appuntamenti su WhatsApp con Confirm e Reschedule. Questo articolo copre i campi del modello, gli esempi di Meta e i punti in cui si contraddicono, e un servizio di invio che chiude il ciclo tramite la tua pagina di gestione.
Cosa contiene il modello
Ogni regola qui sotto viene dalla pagina di Meta (modelli per gli appuntamenti, consultato il 2026-11-27).
| Parte | Obbligatoria | Limite e regola |
|---|---|---|
| Intestazione | Sì | «È supportato solo il formato testo», 60 caratteri |
| Corpo | Sì | 1.024 caratteri, parametri con nome; esempi «obbligatori se il testo del corpo contiene parametri con nome» |
| Piè di pagina | No | 60 caratteri |
| Pulsante | Sì (definisce il tipo) | Un pulsante booking_status, con etichetta “View details”, che «non può essere modificato» |
booking_url, booking_management_url |
No | 2.000 caratteri ciascuno; un parametro, che «deve trovarsi alla fine dell’URL» |
| Note | No | 1.024 caratteri; «possono contenere fino a 3 URL incorporati» |
I nomi dei parametri devono essere una «stringa univoca in minuscolo con trattini bassi». «È consentito un solo pulsante di stato della prenotazione, e non può essere combinato con altri tipi di pulsante.» Il pulsante «apre un pannello dal basso che mostra tutte le informazioni sull’appuntamento», e le note sono «mostrate nel pannello dei dettagli della prenotazione». Le note accettano parametri con nome, grassetto, corsivo, barrato, codice, \n, elenchi puntati e link. Un link può portare «un solo suffisso parametrizzato alla fine».
Il nome del modello può arrivare a 512 caratteri. Il token di accesso deve essere un «token di sistema» o un «token business». Token di accesso della WhatsApp Cloud API spiega come ottenerne uno.
Al momento dell’invio, start_datetime è obbligatorio, in ISO 8601 con fuso orario. end_datetime, location, phone_number e email sono facoltativi. location è l’«indirizzo fisico in cui si svolge l’appuntamento», fino a 100 caratteri, e email arriva a 254. Una regola vale per tutti: «Devi fornire almeno uno tra location, booking_url o phone_number al momento dell’invio.»
Crea il modello: gli esempi di Meta
Questi sono i blocchi di Meta così come pubblicati, nell’ordine della pagina. La pagina usa v27.0 nei suoi URL. Lo abbiamo cambiato in v26.0, la versione che usa questo blog, e non abbiamo toccato nient’altro. I commenti <!-- --> sono di Meta, ed è per questo che i blocchi di sintassi non girano se incollati così.
La sintassi della richiesta:
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>"
}
]
}
}
}
]
}
]
}'
Il modello più semplice che mostra 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"
}
]
}
]
}'
L’esempio con tutte le funzioni. Leggi la nota sulla shell nella sezione successiva prima di incollarlo.
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"
}
]
}
}
}
]
}
]
}'
La risposta. Un modello nuovo torna come PENDING.
{
"id": "546151681022936",
"status": "PENDING",
"category": "UTILITY"
}
Invialo: gli esempi di Meta
La sintassi dell’invio. I dettagli della prenotazione viaggiano in un componente pulsante con sub_type: "booking_status" e un parametro action.
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>"
}
]
}
}
}
}
]
}
]
}
}'
L’invio semplice. La sua data è nel passato, come spiega la sezione successiva.
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"
}
}
}
]
}
]
}
}'
L’invio con tutte le funzioni:
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"
}
]
}
}
}
}
]
}
]
}
}'
La risposta all’invio contiene l’ID del messaggio che abbinerai ai webhook di stato e alle risposte:
{
"messaging_product": "whatsapp",
"contacts": [
{
"input": "+16505551234",
"wa_id": "16505551234"
}
],
"messages": [
{
"id": "wamid.HBgLMTY0NjcwNDM1OTUVAgARGBI1RjQyNUE3NEYxMzAzMzQ5MkEA"
}
]
}
Dove gli esempi di Meta si contraddicono
Copiare i blocchi qui sopra così come sono porta a diverse incoerenze presenti sulla pagina di Meta.
| Cosa | Dove sulla pagina di Meta | Cosa fare |
|---|---|---|
Chiave delle note all’invio: param_name o parameter_name |
La sintassi dell’invio usa param_name; l’esempio di invio completo usa parameter_name |
Invia parameter_name, come fanno l’esempio completo e tutti i parametri del corpo, e prova. Alla creazione, param_name è coerente |
type sui parametri delle note |
I parametri del corpo hanno "type": "text"; i parametri delle note non hanno type in nessuno dei due blocchi |
Lascialo fuori, come fanno entrambi i blocchi |
{{1}} negli URL |
Il modello è parameter_format: "named", ma gli URL usano il posizionale {{1}} |
Tieni {{1}} negli URL, come mostra la pagina |
| Versione della API | Tutti gli esempi usano v27.0 |
Usa la versione su cui punta la tua app; questo blog usa v26.0 |
| Maiuscole e minuscole | "utility", "named", "header", "buttons" in minuscolo |
La risposta di creazione di Meta ("category": "UTILITY") usa il maiuscolo; scegline una e mantienila |
Formato di to |
"+16505551234" con il più |
Gli esempi di webhook di Meta usano solo cifre; il servizio qui sotto salva le cifre e le invia senza il più |
| Date | L’invio semplice usa 2025-07-10, quello completo 2026-03-15 |
Oggi sono entrambe nel passato; costruisci sempre start_datetime dalla prenotazione reale |
| Apici nella shell | Le note dell’esempio di creazione completo contengono “We’re”, “San Diego’s” e “Can’t” dentro un -d '...' tra apici singoli |
In una shell POSIX quegli apostrofi chiudono la stringa in anticipo, e bash -n segnala un errore di sintassi. Salva il JSON in un file e invialo con -d @template.json |
Il problema della shell è una nostra lettura del blocco, non una nota della pagina di Meta. I blocchi di invio non hanno apostrofi e girano appena sostituisci il token e gli ID.
Perché passa come utility
Il modello sta tra i modelli utility di Meta, e la sua chiamata di creazione imposta "category": "utility". Il contenuto deve comunque superare il test di Meta: «deve essere non promozionale» e «specifico per l’utente o da lui richiesto (chiaramente legato al suo ordine, account, servizi o transazioni)» (categorizzazione dei modelli, consultato il 2026-11-27). La conferma di una prenotazione appena fatta dal cliente li soddisfa entrambi. Una riga con uno sconto nel corpo o nelle note la trasforma in marketing.
La Template Library non ha un tipo pronto per le prenotazioni da clonare. I suoi settori sono E_COMMERCE e FINANCIAL_SERVICES (Template Library, consultato il 2026-11-25). Per le cliniche, limita intestazione, corpo e note a orario, luogo e nome del professionista. Il pannello mostra tutto ciò che metti nelle note, quindi nemmeno lì va niente di clinico.
Il ciclo senza un webhook del tocco
La pagina di Meta non documenta alcun webhook per un tocco su “View details”. Non puoi sapere se il cliente ha aperto il pannello. Quindi il passo di risposta del ciclo viene dai tuoi sistemi.
- Il tuo sistema di prenotazione salva una prenotazione e chiede al servizio di invio di confermarla.
- Il servizio invia il modello con un suffisso di gestione che corrisponde a quella prenotazione.
- Il cliente apre “View details” e segue
booking_management_urlfino alla tua pagina di gestione. - La tua pagina di gestione modifica la prenotazione e chiama il servizio di invio, che manda il nuovo orario.
- Il testo libero che il cliente scrive in chat arriva come normale webhook
messagese diventa una nota sulla prenotazione.
La pagina di Meta non descrive alcun modo per modificare un messaggio già inviato. Una modifica parte come nuovo messaggio, e Meta non documenta cosa mostri poi un pannello precedente. Se la pagina di gestione è Calendly, l’ID di reschedule_url potrebbe funzionare come suffisso, cosa che webhook di Calendly verso WhatsApp tratta come una deduzione da provare.
Modello per gli appuntamenti o modello personalizzato
| Esigenza | Modello per gli appuntamenti | Modello utility personalizzato |
|---|---|---|
| Pulsanti | Un booking_status, etichetta fissa “View details” |
Fino a 10 risposte rapide, più pulsanti URL e telefono |
| Una risposta che il tuo webhook può leggere | Nessuna documentata per “View details” | Un messaggio button con il tuo payload |
| Data e ora | start_datetime e end_datetime all’invio |
Formattate da te nel corpo |
| Link di gestione | booking_management_url |
Un pulsante URL con un suffisso |
| Adatto a | La conferma subito dopo la prenotazione | Il promemoria che richiede Confirm, Cancel o Reschedule |
La maggior parte delle prenotazioni usa entrambi. Il modello per gli appuntamenti conferma, e un modello personalizzato ricorda l’appuntamento il giorno prima, come nell’articolo pilastro sui promemoria e in dai webhook di Cal.com ai promemoria su WhatsApp. Se uno slot si libera, l’articolo sulla lista d’attesa lo offre al cliente successivo.
Il tuo modello e il servizio di invio
Questo modello ha un’intestazione di testo, un corpo con due parametri con nome, un link di gestione e un parametro nelle note. Sostituisci example.com con l’host della tua pagina di gestione. I parametri con nome e i loro esempi sono spiegati in variabili dei modelli WhatsApp.
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" }
]
}
}
}
]
}
]
}'
Il servizio di invio gira su Python 3.9 o successivo con la sola libreria standard. Tiene le prenotazioni in memoria per poterlo provare. NOTES_PARAM_KEY ti fa passare da parameter_name a param_name mentre provi l’incoerenza di Meta.
# 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()
Conferma una prenotazione dal tuo sistema con una sola chiamata. La risposta restituisce il manage_token che la tua pagina di gestione usa per trovare la prenotazione.
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}'
Il token di gestione è casuale, perché chiunque abbia il link può aprire la tua pagina di gestione. Fai in modo che la pagina verifichi il token rispetto alla prenotazione, e fallo scadere dopo l’appuntamento.
Quando il ciclo si rompe
Meta rifiuta l’invio
Un 4xx da Meta di solito indica un nome, una lingua o un parametro che non corrispondono. Il servizio non ritenta questi errori e restituisce 502 con il body di Meta. Se l’errore riguarda le note, imposta NOTES_PARAM_KEY su param_name e invia di nuovo. La mancanza contemporanea di location e phone_number viene intercettata prima della chiamata, perché Meta ne richiede almeno uno.
La data è sbagliata o nel passato
Il servizio rifiuta uno start nel passato e un end precedente all’inizio. Un orario locale senza offset viene letto nel time_zone della prenotazione, quindi 2026-12-03T09:30 in America/New_York parte come -05:00.
Lo stesso webhook arriva due volte
Meta ritenta i webhook che ritiene falliti. Il servizio salta ogni ID di messaggio in arrivo già visto, quindi una risposta ritentata diventa una sola nota. Sposta seen_inbound in una tabella con una chiave univoca prima della produzione.
Il cliente fa opt-out o non risponde
Una risposta STOP toglie il consenso su tutte le prenotazioni di quel numero, e /bookings/changed a quel punto rifiuta di inviare. Nessuna risposta non significa nulla, perché il modello non ne chiede. È il modello del promemoria quello in cui chiedi Confirm.
Un invio va in timeout dopo che Meta lo ha accettato
Il servizio ritenta tre volte, con backoff, gli errori di rete, i 429 e i 5xx. Un timeout dopo l’accettazione può produrre una seconda conferma. Se per te è più grave di una conferma persa, riduci il numero di tentativi. La gestione degli stati è in webhook di stato dei messaggi WhatsApp.
Dove si colloca Z-API Omni
La documentazione di Omni non copre questo modello. I tipi di pulsante per la creazione dei modelli sono QUICK_REPLY, URL, PHONE_NUMBER, COPY_CODE, OTP, FLOW, CATALOG, MPM, SPM, PAYMENT_REQUEST, ORDER_DETAILS e VOICE_CALL, senza booking_status. Il suo schema di invio accetta parametri con i soli type e text, senza action. Quindi la documentazione non mostra alcun modo per inviare il modello per gli appuntamenti, e questo articolo non mostra una richiesta per farlo.
Ciò che la documentazione copre è il modello utility personalizzato con pulsanti QUICK_REPLY e URL. Lo crei con POST /whatsapp/businesses/{wabaId}/templates, che accetta message_send_ttl_seconds, e un pulsante URL accetta una variabile alla fine. I modelli funzionano sui canali Meta Cloud API, dove le tariffe di Meta vengono riaddebitate.
Il team di Z-API Omni