# Plantilla de reserva de citas de WhatsApp con enlace de gestión

> La plantilla de reserva de citas de Meta: créala, envía hora, lugar y un enlace de gestión, y descubre cuándo encaja mejor una plantilla con respuestas rápidas.

Published 2026-11-27. Z-API Omni team.

Una plantilla de reserva de citas es un tipo de plantilla de utilidad de Meta que confirma una cita en un solo mensaje. Su botón fijo "View details" (ver detalles) abre una hoja con los detalles de la reserva. La creas con un botón `booking_status` y, al enviarla, mandas `start_datetime`, un lugar o un teléfono y un sufijo `booking_management_url` opcional. Úsala para la confirmación justo después de la reserva. No admite respuestas rápidas, así que un recordatorio que necesita Confirmar o Reprogramar sigue siendo una plantilla personalizada.

El recordatorio personalizado está en [recordatorios de citas por WhatsApp con Confirmar y Reprogramar](/academy/es/articles/whatsapp-appointment-reminders-confirm-reschedule/). Este artículo cubre los campos de la plantilla, los ejemplos de Meta y dónde se contradicen, y un servicio de envío que cierra el ciclo a través de tu página de gestión.

## Qué contiene la plantilla

Todas las reglas de abajo vienen de la página de Meta ([plantillas de reserva de citas](https://developers.facebook.com/documentation/business-messaging/whatsapp/templates/utility-templates/booking-appointment-templates.md), consultado el 2026-11-27).

| Parte | Obligatoria | Límite y regla |
| --- | --- | --- |
| Header | Sí | "Solo se admite el formato de texto", 60 caracteres |
| Cuerpo | Sí | 1.024 caracteres, parámetros con nombre; ejemplos "obligatorios si el texto del cuerpo contiene parámetros con nombre" |
| Footer | No | 60 caracteres |
| Botón | Sí (define el tipo) | Un botón `booking_status`, con la etiqueta "View details", que "no se puede modificar" |
| `booking_url`, `booking_management_url` | No | 2.000 caracteres cada uno; un parámetro, que "tiene que estar al final de la URL" |
| Notas | No | 1.024 caracteres; "pueden contener hasta 3 URL incrustadas" |

Los nombres de parámetro tienen que ser una "cadena única en minúsculas con guiones bajos". "Solo se permite un botón de estado de reserva, y no se puede combinar con otros tipos de botón." El botón "abre una hoja inferior que muestra toda la información de la cita", y las notas "se muestran en la hoja inferior con los detalles de la reserva". Las notas aceptan parámetros con nombre, negrita, cursiva, tachado, código, `\n`, listas con viñetas y enlaces. Un enlace puede llevar "un único sufijo parametrizado al final".

El nombre de la plantilla puede tener hasta 512 caracteres. El token de acceso tiene que ser un "System token" o un "business token". [Los tokens de acceso de la WhatsApp Cloud API](/academy/es/articles/whatsapp-cloud-api-access-tokens-system-user/) explica cómo obtener uno.

Al enviar, `start_datetime` es obligatorio, en ISO 8601 con zona horaria. `end_datetime`, `location`, `phone_number` y `email` son opcionales. `location` es la "dirección física donde se realiza la cita", de hasta 100 caracteres, y `email` admite hasta 254. Una regla se aplica a todos: "Tienes que indicar al menos uno de `location`, `booking_url` o `phone_number` al enviar".

## Crea la plantilla: los ejemplos de Meta

Estos son los bloques de Meta tal como están publicados, en el orden de la página. La página muestra `v27.0` en sus URL. Lo cambiamos a `v26.0`, la versión que usa este blog, y no tocamos nada más. Los comentarios `<!-- -->` son de Meta, y por eso los bloques de sintaxis no funcionan tal cual.

La sintaxis de la solicitud:

```text
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>"
                }
              ]
            }
          }
        }
      ]
    }
  ]
}'
```

La plantilla más simple que muestra Meta:

```bash
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"
        }
      ]
    }
  ]
}'
```

El ejemplo con todas las funciones. Lee la nota sobre el shell en la sección siguiente antes de pegarlo.

```bash
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 respuesta. Una plantilla nueva vuelve como `PENDING`.

```json
{
  "id": "546151681022936",
  "status": "PENDING",
  "category": "UTILITY"
}
```

## Envíala: los ejemplos de Meta

La sintaxis del envío. Los detalles de la reserva viajan en un componente de botón con `sub_type: "booking_status"` y un parámetro `action`.

```text
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>"
                    }
                  ]
                }
              }
            }
          }
        ]
      }
    ]
  }
}'
```

El envío simple. Su fecha ya pasó, como explica la sección siguiente.

```bash
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"
              }
            }
          }
        ]
      }
    ]
  }
}'
```

El envío con todas las funciones:

```bash
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": "info@sdsucculenttours.com",
                "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 respuesta del envío trae el ID del mensaje que vas a asociar con los webhooks de estado y las respuestas:

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

## Dónde se contradicen los ejemplos de Meta

Si copias los bloques de arriba tal cual, te encuentras con varias inconsistencias de la página de Meta.

| Qué | Dónde en la página de Meta | Qué hacer |
| --- | --- | --- |
| Clave de las notas al enviar: `param_name` o `parameter_name` | La sintaxis de envío usa `param_name`; el ejemplo completo de envío usa `parameter_name` | Envía `parameter_name`, como hacen el ejemplo completo y todos los parámetros del cuerpo, y pruébalo. Al crear, `param_name` es consistente |
| `type` en los parámetros de las notas | Los parámetros del cuerpo llevan `"type": "text"`; los de las notas no tienen `type` en ninguno de los dos bloques | Omítelo, como hacen los dos bloques |
| `{{1}}` en las URL | La plantilla es `parameter_format: "named"`, pero las URL usan el posicional `{{1}}` | Mantén `{{1}}` en las URL, como muestra la página |
| Versión de la API | Todos los ejemplos usan `v27.0` | Usa la versión a la que apunta tu app; este blog usa `v26.0` |
| Mayúsculas | `"utility"`, `"named"`, `"header"`, `"buttons"` en minúsculas | La propia respuesta de creación de Meta (`"category": "UTILITY"`) usa mayúsculas; elige una forma y mantenla |
| Formato de `to` | `"+16505551234"` con signo más | Los ejemplos de webhooks de Meta usan solo dígitos; el servicio de abajo guarda dígitos y los envía sin el signo más |
| Fechas | El envío simple usa `2025-07-10` y el completo `2026-03-15` | Las dos ya pasaron; arma siempre `start_datetime` a partir de la reserva real |
| Comillas en el shell | Las notas del ejemplo completo de creación contienen "We're", "San Diego's" y "Can't" dentro de un `-d '...'` entre comillas simples | En un shell POSIX, esos apóstrofos cierran la cadena antes de tiempo, y `bash -n` informa un error de sintaxis. Guarda el JSON en un archivo y envíalo con `-d @template.json` |

El problema del shell es nuestra lectura del bloque, no una nota de la página de Meta. Los bloques de envío no tienen apóstrofos y funcionan cuando reemplazas el token y los IDs.

## Por qué pasa como utilidad

La plantilla está dentro de las plantillas de utilidad de Meta, y su llamada de creación pone `"category": "utility"`. El contenido igual tiene que pasar la prueba de Meta: "tiene que ser no promocional" y "específico del usuario o solicitado por él (claramente relacionado con su pedido, cuenta, servicios o transacciones)" ([categorización de plantillas](https://developers.facebook.com/documentation/business-messaging/whatsapp/templates/template-categorization.md), consultado el 2026-11-27). La confirmación de una reserva que el cliente acaba de hacer cumple las dos. Una línea de descuento en el cuerpo o en las notas la convierte en marketing.

La Template Library no tiene ningún tipo de reserva listo para clonar. Sus industrias son `E_COMMERCE` y `FINANCIAL_SERVICES` ([Template Library](https://developers.facebook.com/documentation/business-messaging/whatsapp/templates/template-library), consultado el 2026-11-25). En las clínicas, limita el header, el cuerpo y las notas a la hora, el lugar y el nombre del profesional. La hoja muestra lo que pongas en las notas, así que tampoco va nada clínico ahí.

## El ciclo sin un webhook del toque

La página de Meta no documenta ningún webhook para un toque en "View details". No puedes saber si el cliente abrió la hoja. Así que el paso de respuesta del ciclo sale de tus propios sistemas.

1. Tu sistema de reservas guarda una reserva y le pide al servicio de envío que la confirme.
2. El servicio envía la plantilla con un sufijo de gestión que apunta a esa reserva.
3. El cliente abre "View details" y sigue `booking_management_url` hasta tu página de gestión.
4. Tu página de gestión cambia la reserva y llama al servicio, que envía la hora nueva.
5. El texto libre que el cliente escribe en el chat llega como un webhook `messages` normal y se convierte en una nota de la reserva.

La página de Meta no describe ninguna forma de editar un mensaje ya enviado. Un cambio sale como un mensaje nuevo, y Meta no documenta qué muestra después una hoja anterior. Si la página de gestión es Calendly, el ID del `reschedule_url` puede servir como sufijo, algo que [webhooks de Calendly a WhatsApp](/academy/es/articles/calendly-webhook-whatsapp-confirmations-reminders/) trata como una deducción que hay que probar.

## Plantilla de reserva o plantilla personalizada

| Necesidad | Plantilla de reserva de citas | Plantilla de utilidad personalizada |
| --- | --- | --- |
| Botones | Un `booking_status`, con la etiqueta fija "View details" | Hasta 10 respuestas rápidas, más botones de URL y de teléfono |
| Una respuesta que tu webhook pueda leer | Ninguna documentada para "View details" | Un mensaje `button` con tu payload |
| Fecha y hora | `start_datetime` y `end_datetime` al enviar | Las formateas tú en el cuerpo |
| Enlace de gestión | `booking_management_url` | Un botón de URL con un sufijo |
| Para qué sirve | La confirmación justo después de reservar | El recordatorio que necesita Confirmar, Cancelar o Reprogramar |

La mayoría de las reservas usan las dos. La plantilla de reserva confirma, y una plantilla personalizada recuerda un día antes, como en [el artículo principal sobre recordatorios](/academy/es/articles/whatsapp-appointment-reminders-confirm-reschedule/) y en [webhooks de Cal.com a recordatorios por WhatsApp](/academy/es/articles/cal-com-webhook-whatsapp-booking-reminders/). Si se libera un turno, [el artículo sobre la lista de espera](/academy/es/articles/whatsapp-waitlist-refill-cancelled-appointment/) se lo ofrece al siguiente cliente.

## Tu propia plantilla y el servicio de envío

Esta plantilla tiene un header de texto, un cuerpo con dos parámetros con nombre, un enlace de gestión y un parámetro en las notas. Reemplaza `example.com` por el host de tu página de gestión. Los parámetros con nombre y sus ejemplos se explican en [las variables de plantillas de WhatsApp](/academy/es/articles/whatsapp-template-variables-named-parameters/).

```bash
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" }
                ]
              }
            }
          }
        ]
      }
    ]
  }'
```

El servicio de envío funciona en Python 3.9 o posterior, solo con la biblioteca estándar. Guarda las reservas en memoria para que puedas probarlo. `NOTES_PARAM_KEY` te permite alternar entre `parameter_name` y `param_name` mientras pruebas la inconsistencia de Meta.

```python
# 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()
```

Confirma una reserva desde tu sistema con una sola llamada. La respuesta devuelve el `manage_token` que tu página de gestión usa para encontrar la reserva.

```bash
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}'
```

El token de gestión es aleatorio, porque cualquiera que tenga el enlace puede abrir tu página de gestión. Haz que esa página compare el token con la reserva, y que lo invalide después de la cita.

## Cuando el ciclo se rompe

### Meta rechaza el envío

Un 4xx de Meta suele significar que no coinciden el nombre, el idioma o un parámetro. El servicio no los reintenta y devuelve 502 con el cuerpo de Meta. Si el error apunta a las notas, cambia `NOTES_PARAM_KEY` a `param_name` y vuelve a enviar. La falta simultánea de `location` y `phone_number` se detecta antes de la llamada, porque Meta exige uno de los dos.

### La fecha es incorrecta o ya pasó

El servicio rechaza un `start` en el pasado y un `end` anterior al inicio. Una hora local sin offset se interpreta en la `time_zone` de la reserva, así que `2026-12-03T09:30` en `America/New_York` sale como `-05:00`.

### El mismo webhook llega dos veces

Meta reintenta los webhooks que cree fallidos. El servicio omite cualquier ID de mensaje entrante que ya vio, así que una respuesta reintentada se convierte en una sola nota. Pasa `seen_inbound` a una tabla con clave única antes de producción.

### El cliente se da de baja o no responde

Una respuesta STOP quita el consentimiento en todas las reservas de ese número, y desde entonces `/bookings/changed` se niega a enviar. Que no haya respuesta no significa nada, porque la plantilla no pide ninguna. La plantilla de recordatorio es donde pides Confirmar.

### Un envío vence por timeout después de que Meta lo aceptó

El servicio reintenta los errores de red, los 429 y los 5xx tres veces con espera progresiva. Un timeout después de la aceptación puede generar una segunda confirmación. Si eso te importa más que una confirmación perdida, baja la cantidad de intentos. El manejo de estados está en [los webhooks de estado de mensajes de WhatsApp](/academy/es/articles/whatsapp-message-status-webhooks-sent-delivered-read-failed/).

## Dónde encaja Z-API Omni

La documentación de Omni no cubre esta plantilla. Sus tipos de botón para crear plantillas son QUICK_REPLY, URL, PHONE_NUMBER, COPY_CODE, OTP, FLOW, CATALOG, MPM, SPM, PAYMENT_REQUEST, ORDER_DETAILS y VOICE_CALL, sin `booking_status`. Su esquema de envío recibe parámetros solo con `type` y `text`, sin `action`. Así que la documentación no muestra ninguna forma de enviar la plantilla de reserva de citas, y este artículo no muestra ninguna solicitud para ella.

Lo que sí cubre la documentación es la plantilla de utilidad personalizada con botones `QUICK_REPLY` y `URL`. La creas con `POST /whatsapp/businesses/{wabaId}/templates`, que acepta `message_send_ttl_seconds`, y un botón de URL admite una variable al final. Las plantillas funcionan en canales de la Meta Cloud API, donde las tarifas de Meta se trasladan.

[Ver la documentación](https://developer.omni.z-api.io/es)

*Equipo de Z-API Omni*
