# Promemoria degli appuntamenti su WhatsApp con Confirm e Reschedule

> Invia un promemoria WhatsApp 24 ore prima di un appuntamento, scartalo se in ritardo con il TTL e aggiorna la prenotazione sui tocchi Confirm o Reschedule.

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

Invia il promemoria come modello utility personalizzato con due pulsanti di risposta rapida, Confirm (Conferma) e Reschedule (Riprogramma), e metti l'ID della prenotazione nel payload di ogni pulsante. Imposta `message_send_ttl_seconds` sul modello, così Meta scarta un promemoria che non riesce a consegnare in tempo. Un tocco arriva al tuo webhook come messaggio `type: "button"`, e aggiorni la riga della prenotazione in base al suo payload.

Questo è il ciclo generico per qualsiasi tabella di prenotazioni e qualsiasi scheduler. [Dai webhook di Cal.com ai promemoria su WhatsApp](/academy/it/articles/cal-com-webhook-whatsapp-booking-reminders/) lo applica a Cal.com e Cal.diy. [Prenotazioni dai DM di Instagram e Messenger](/academy/it/articles/instagram-messenger-dm-to-booking-utility-reminders/) lo applica alle prenotazioni che nascono in un DM. Il ciclo funziona anche a partire da [Calendly](/academy/it/articles/calendly-webhook-whatsapp-confirmations-reminders/) e dagli [orari delle lezioni](/academy/it/articles/class-session-reminders-attendance-confirmation-lms/), [una lista d'attesa su WhatsApp](/academy/it/articles/whatsapp-waitlist-refill-cancelled-appointment/) può riempire gli slot liberati, e [il modello di Meta per gli appuntamenti](/academy/it/articles/whatsapp-booking-appointment-template-manage-link/) ha una guida a parte.

## Il ciclo dalla prenotazione alla riga aggiornata

La WhatsApp Cloud API non ha uno scheduler, quindi la tempistica sta nel tuo job. Tutto il resto passa dall'endpoint di invio di Meta e da un solo webhook.

1. Salva la prenotazione con un numero di telefono in E.164 e un opt-in WhatsApp raccolto nel modulo di prenotazione.
2. Esegui ogni minuto un job che invia `reminder_24h` un giorno prima e `reminder_2h` due ore prima.
3. Il cliente tocca Confirm o Reschedule, e Meta invia un messaggio `button` al tuo webhook.
4. Abbina il tocco alla prenotazione, aggiornane lo stato e rispondi dentro la finestra di 24 ore aperta dal tocco.
5. Controlla i webhook di stato: nessuno stato `delivered` prima della fine del TTL significa che Meta ha scartato il promemoria.

Raccogli il consenso al momento della prenotazione, con parole che nominano WhatsApp e lo scopo. [Come raccogliere l'opt-in WhatsApp](/academy/it/articles/whatsapp-opt-in-how-to-collect-consent/) tratta la formulazione e il record da conservare.

## Usa un modello utility personalizzato per il promemoria

Meta offre un modello dedicato agli appuntamenti, ma non può portare i pulsanti che servono a questo ciclo. Il suo unico pulsante è `booking_status`, mostrato come "View details" (Vedi dettagli). Un modello ne accetta uno, e «non può essere combinato con altri tipi di pulsante» ([modelli per gli appuntamenti, consultato il 2026-11-25](https://developers.facebook.com/documentation/business-messaging/whatsapp/templates/utility-templates/booking-appointment-templates)).

Un modello personalizzato con pulsanti `QUICK_REPLY` fa il lavoro. «I modelli sono limitati a 10 pulsanti di risposta rapida», e ogni etichetta ha un «massimo di 25 caratteri». Le risposte rapide stanno in un gruppo a parte, separate dai pulsanti URL o telefono ([componenti dei modelli, consultato il 2026-11-25](https://developers.facebook.com/documentation/business-messaging/whatsapp/templates/components)). Due etichette brevi ci stanno con margine.

### Dove il modello per gli appuntamenti serve ancora

Usalo per la conferma subito dopo la prenotazione. Mette data, ora, luogo e link di gestione in un solo messaggio, e "View details" apre un pannello dal basso. Lo crei con `category` utility, `parameter_format` named, un'intestazione di testo fino a 60 caratteri e un corpo fino a 1.024. Al momento dell'invio, un componente pulsante `booking_status` porta `start_datetime`, obbligatorio, più chiavi facoltative come `end_datetime`, `location`, `booking_url` e `booking_management_url`.

Le date e ore sono in ISO 8601 con offset, come `-07:00`. La pagina dice anche: «Devi fornire almeno uno tra `location`, `booking_url` o `phone_number` al momento dell'invio.» In una sezione la pagina chiama il parametro delle note `param_name` e nel suo esempio completo `parameter_name`, quindi copia il JSON di Meta e prova entrambi. La pagina non documenta alcun webhook per un tocco su "View details".

Nemmeno la Template Library ha un promemoria pronto. I suoi settori sono `E_COMMERCE` e `FINANCIAL_SERVICES`, senza un caso d'uso per gli appuntamenti da clonare ([Template Library, consultato il 2026-11-25](https://developers.facebook.com/documentation/business-messaging/whatsapp/templates/template-library)).

## Perché il promemoria passa come utility

La pagina di Meta sulla categorizzazione chiede che un modello utility sia «non promozionale» e «specifico per l'utente o richiesto dall'utente». I suoi esempi sono messaggi «chiaramente legati al loro ordine, account, servizi o transazioni» ([categorizzazione dei modelli, consultato il 2026-11-25](https://developers.facebook.com/documentation/business-messaging/whatsapp/templates/template-categorization)). Un promemoria per un appuntamento prenotato dal cliente supera entrambi i test. La pagina non ha un esempio di appuntamento. Il più vicino è un promemoria di pagamento per un servizio che l'utente ha già.

Una promozione dentro il promemoria lo trasforma in marketing. Basta una riga su un'offerta stagionale sotto l'orario dell'appuntamento. Le penalità di Meta crescono per gradi: un avviso, poi la ricategorizzazione immediata, poi un limite di frequenza sui modelli utility per almeno 7 giorni. Segue una restrizione utility di 7 giorni, o 30 per le violazioni ripetute, durante la quale tutti i tuoi modelli utility partono come marketing. L'ultimo gradino è una restrizione del portfolio di 30 giorni.

Per cliniche e altri servizi sanitari, limita il corpo a orario, luogo e nome del professionista. Lascia fuori i dettagli del trattamento e tutto ciò che è clinico. Le regole sulle categorie sono approfondite in [le categorie dei modelli WhatsApp](/academy/it/articles/whatsapp-template-categories-marketing-utility-authentication/).

## Crea un modello per ogni anticipo

Il TTL appartiene al modello, non al singolo invio. Il campo è `message_send_ttl_seconds`, impostato quando crei o aggiorni il modello. Per i modelli utility l'intervallo va da 30 secondi a 12 ore, il default è 30 giorni, e anche `-1` significa 30 giorni ([time-to-live, consultato il 2026-11-25](https://developers.facebook.com/documentation/business-messaging/whatsapp/templates/time-to-live)). Meta «scarta i messaggi che non possono essere consegnati entro il TTL predefinito o personalizzato». Il TTL utility funziona solo sulla Cloud API.

Siccome il TTL è per modello, un promemoria a 24 ore e uno a 2 ore richiedono due modelli. Scegli un TTL che finisca ben prima dell'appuntamento. Inviato a T-24h con un TTL di 43.200 secondi, il promemoria viene scartato a T-12h se il telefono non si è mai collegato.

```bash
curl "https://graph.facebook.com/v26.0/$WABA_ID/message_templates" \
  -H "Authorization: Bearer $WA_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "reminder_24h",
    "language": "en_US",
    "category": "UTILITY",
    "parameter_format": "NAMED",
    "message_send_ttl_seconds": 43200,
    "components": [
      {
        "type": "BODY",
        "text": "Hi {{customer_name}}, this is a reminder of your appointment on {{date}} at {{time}} with {{professional}}. Please confirm or pick a new time.",
        "example": {
          "body_text_named_params": [
            { "param_name": "customer_name", "example": "Marina" },
            { "param_name": "date", "example": "Friday, November 27" },
            { "param_name": "time", "example": "2:30 PM" },
            { "param_name": "professional", "example": "Jordan Lee" }
          ]
        }
      },
      {
        "type": "BUTTONS",
        "buttons": [
          { "type": "QUICK_REPLY", "text": "Confirm" },
          { "type": "QUICK_REPLY", "text": "Reschedule" }
        ]
      }
    ]
  }'
```

Eseguilo di nuovo con `"name": "reminder_2h"` e `"message_send_ttl_seconds": 3600`. Il corpo inizia con "Hi" perché una variabile non può aprire né chiudere il testo. Se Meta ricategorizza un modello, azzera il TTL personalizzato a null, quindi rileggi `message_send_ttl_seconds` dopo ogni cambio di categoria. La gestione degli stati legata al TTL è in [report di consegna dai webhook di stato](/academy/it/articles/whatsapp-campaign-delivery-report-status-webhooks/).

## Com'è fatto un tocco nel tuo webhook

Un tocco su una risposta rapida di un modello arriva come messaggio in entrata con `type: "button"`. Questo è l'esempio di Meta dal riferimento del webhook button, invariato tranne gli a capo ([riferimento del webhook button, consultato il 2026-11-25](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/reference/messages/button)):

```json
{
  "object": "whatsapp_business_account",
  "entry": [
    {
      "id": "102290129340398",
      "changes": [
        {
          "value": {
            "messaging_product": "whatsapp",
            "metadata": {
              "display_phone_number": "15550783881",
              "phone_number_id": "106540352242922"
            },
            "contacts": [
              {
                "profile": { "name": "Sheena Nelson" },
                "wa_id": "16505551234",
                "user_id": "US.13491208655302741918"
              }
            ],
            "messages": [
              {
                "context": {
                  "from": "15550783881",
                  "id": "wamid.HBgLMTQxMjU1NTA4MjkVAgASGBQzQUNCNjk5RDUwNUZGMUZEM0VBRAA="
                },
                "from": "16505551234",
                "from_user_id": "US.13491208655302741918",
                "id": "wamid.HBgLMTY1MDM4Nzk0MzkVAgASGBQzQUFERjg0NDEzNDdFODU3MUMxMAA=",
                "timestamp": "1750091045",
                "type": "button",
                "button": {
                  "payload": "Unsubscribe",
                  "text": "Unsubscribe"
                }
              }
            ]
          },
          "field": "messages"
        }
      ]
    }
  ]
}
```

`context.id` è il wamid del messaggio modello toccato dal cliente. L'esempio di Meta imposta `payload` e `text` sulla stessa etichetta, e il riferimento li descrive entrambi come l'etichetta. La documentazione dell'SDK Node di Meta descrive `payload` come un «payload definito dallo sviluppatore che viene restituito quando si clicca il pulsante, in aggiunta al testo visualizzato» ([oggetto parametro del pulsante, consultato il 2026-11-25](https://whatsapp.github.io/WhatsApp-Nodejs-SDK/api-reference/types/button_parameter_object)). Quindi interpreta prima `button.payload`. Se non è nel tuo formato, confronta `context.id` con il wamid salvato al momento dell'invio. Non abbinare mai solo per numero di telefono: un cliente può avere due appuntamenti, e il payload `bk|<id>|confirm` ne indica uno solo.

Identifica il cliente con `from_user_id` oltre che con `from`. Meta omette `wa_id` e `from` quando un utente ha uno username e nessun telefono disponibile. [Migrare un database di contatti al BSUID](/academy/it/articles/migrate-contact-database-phone-number-to-bsuid/) tratta il cambiamento.

## Il servizio dei promemoria

Questo file gira così com'è su Node 18 o successivo con Express 4. Tiene le prenotazioni in memoria per poterlo provare, e ogni struttura corrisponde a una tabella di database da mantenere. Verifica `X-Hub-Signature-256`, invia entrambi i promemoria, gestisce tocchi e scelte da lista e segue la consegna rispetto al TTL.

```js
// reminders.js: WhatsApp appointment reminders with Confirm and Reschedule.
// Node 18+ and Express 4. Run: npm install express && node reminders.js
const crypto = require("crypto");
const express = require("express");

for (const name of ["WA_TOKEN", "PHONE_NUMBER_ID", "APP_SECRET", "VERIFY_TOKEN", "INTERNAL_TOKEN"]) {
  if (!process.env[name]) throw new Error(`Missing environment variable ${name}`);
}
const { WA_TOKEN, PHONE_NUMBER_ID, APP_SECRET, VERIFY_TOKEN, INTERNAL_TOKEN } = process.env;
const BOOKING_URL = process.env.BOOKING_URL || "https://example.com/book";
const PORT = Number(process.env.PORT || 3000);

const GRAPH_URL = `https://graph.facebook.com/v26.0/${PHONE_NUMBER_ID}/messages`;
const MINUTE = 60 * 1000;
const HOUR = 60 * MINUTE;
const TTL_BUFFER = 5 * MINUTE;

// One template per lead time, because the TTL lives on the template.
// ttlMs must match message_send_ttl_seconds on the approved template.
const REMINDERS = [
  { template: "reminder_24h", leadMs: 24 * HOUR, ttlMs: 12 * HOUR },
  { template: "reminder_2h", leadMs: 2 * HOUR, ttlMs: 1 * HOUR },
];

// In-memory tables so the file runs as is. Use your database in production.
const bookings = new Map(); // booking id -> booking
const sends = new Map(); // reminder wamid -> { bookingId, template, sentAt, ttlMs, state }
const seenInbound = new Set(); // inbound wamids already handled

function formatWhen(iso, timeZone) {
  const d = new Date(iso);
  return {
    date: d.toLocaleDateString("en-US", { timeZone, weekday: "long", month: "long", day: "numeric" }),
    time: d.toLocaleTimeString("en-US", { timeZone, hour: "numeric", minute: "2-digit" }),
    short: d.toLocaleString("en-US", {
      timeZone, weekday: "short", month: "short", day: "numeric", hour: "numeric", minute: "2-digit",
    }),
  };
}

async function sendWhatsApp(message, attempt = 1) {
  let status = 0;
  let data = {};
  try {
    const res = await fetch(GRAPH_URL, {
      method: "POST",
      headers: { Authorization: `Bearer ${WA_TOKEN}`, "Content-Type": "application/json" },
      body: JSON.stringify({ messaging_product: "whatsapp", recipient_type: "individual", ...message }),
    });
    status = res.status;
    data = await res.json().catch(() => ({}));
    if (res.ok) return data.messages[0].id;
  } catch (err) {
    data = { error: String(err) }; // network error or unexpected body
  }
  const retryable = status === 0 || status === 429 || status >= 500;
  if (retryable && attempt < 4) {
    await new Promise((resolve) => setTimeout(resolve, 2 ** attempt * 1000));
    return sendWhatsApp(message, attempt + 1);
  }
  throw new Error(`Send failed with HTTP ${status}: ${JSON.stringify(data)}`);
}

const sendText = (to, body) => sendWhatsApp({ to, type: "text", text: { body } });

async function sendReminder(booking, reminder) {
  const when = formatWhen(booking.startTime, booking.timeZone);
  const buttons = ["confirm", "reschedule"].map((action, index) => ({
    type: "button",
    sub_type: "quick_reply",
    index: String(index),
    parameters: [{ type: "payload", payload: `bk|${booking.id}|${action}` }],
  }));
  const wamid = await sendWhatsApp({
    to: booking.phone,
    type: "template",
    template: {
      name: reminder.template,
      language: { code: "en_US" },
      components: [
        {
          type: "body",
          parameters: [
            { type: "text", parameter_name: "customer_name", text: booking.name },
            { type: "text", parameter_name: "date", text: when.date },
            { type: "text", parameter_name: "time", text: when.time },
            { type: "text", parameter_name: "professional", text: booking.professional },
          ],
        },
        ...buttons,
      ],
    },
  });
  sends.set(wamid, {
    bookingId: booking.id, template: reminder.template, sentAt: Date.now(), ttlMs: reminder.ttlMs, state: "sent",
  });
  return wamid;
}

async function runReminders() {
  const now = Date.now();
  for (const booking of bookings.values()) {
    if (!booking.optIn || booking.status === "cancelled") continue;
    const start = Date.parse(booking.startTime);
    for (const reminder of REMINDERS) {
      if (booking.reminders[reminder.template]) continue; // sending, sent, skipped or failed
      const due = start - reminder.leadMs;
      if (now < due) continue;
      const tooLate = now >= due + reminder.ttlMs || now >= start; // past the window this lead time was meant for
      const notNeeded = reminder.template === "reminder_2h" && booking.status === "confirmed";
      if (tooLate || notNeeded) {
        booking.reminders[reminder.template] = "skipped";
        continue;
      }
      booking.reminders[reminder.template] = "sending"; // claimed before the await
      try {
        booking.reminders[reminder.template] = await sendReminder(booking, reminder); // stores the wamid
      } catch (err) {
        booking.reminders[reminder.template] = "failed";
        console.error("reminder failed", booking.id, reminder.template, err.message);
      }
    }
  }
  for (const [wamid, send] of sends) {
    if (send.state === "sent" && now > send.sentAt + send.ttlMs + TTL_BUFFER) {
      send.state = "dropped"; // no delivered status before the TTL ended
      const booking = bookings.get(send.bookingId);
      if (booking && booking.reminders[send.template] === wamid) booking.reminders[send.template] = "dropped";
      console.warn("reminder dropped after TTL", send.bookingId, send.template);
    }
  }
}

function writeBack(booking, change) {
  // Replace with an UPDATE on your bookings table or a call to your calendar API.
  Object.assign(booking, change, { updatedAt: new Date().toISOString() });
  console.log("booking updated", booking.id, change);
}

function freeSlots(booking) {
  // Stub: replace with a query on your calendar. Returns ISO start times.
  const start = Date.parse(booking.startTime);
  return [1, 2, 3].map((days) => new Date(start + days * 24 * HOUR).toISOString());
}

async function onTap(booking, action) {
  const when = formatWhen(booking.startTime, booking.timeZone);
  if (Date.parse(booking.startTime) <= Date.now()) {
    return sendText(booking.phone, "This appointment has already passed. Reply here if you would like a new one.");
  }
  if (booking.status === "cancelled") {
    return sendText(booking.phone, "This appointment was cancelled. Reply here if you would like a new one.");
  }
  if (action === "confirm") {
    if (booking.status === "confirmed") return; // a second tap changes nothing
    writeBack(booking, { status: "confirmed" });
    return sendText(booking.phone, `Thanks, ${booking.name}. You are confirmed for ${when.date} at ${when.time}.`);
  }
  if (action === "reschedule") {
    if (booking.status === "reschedule_requested") return;
    writeBack(booking, { status: "reschedule_requested" });
    const rows = freeSlots(booking).slice(0, 10).map((iso) => ({
      id: `slot|${booking.id}|${iso}`,
      title: formatWhen(iso, booking.timeZone).short.slice(0, 24),
    }));
    if (rows.length === 0) {
      return sendWhatsApp({
        to: booking.phone,
        type: "interactive",
        interactive: {
          type: "cta_url",
          body: { text: "No open times fit right now. Pick a new time on our booking page." },
          action: { name: "cta_url", parameters: { display_text: "Choose a time", url: BOOKING_URL } },
        },
      });
    }
    return sendWhatsApp({
      to: booking.phone,
      type: "interactive",
      interactive: {
        type: "list",
        body: { text: "Which of these times works for you?" },
        action: { button: "See times", sections: [{ title: "Open times", rows }] },
      },
    });
  }
}

async function onSlot(booking, iso) {
  if (booking.status !== "reschedule_requested" || Number.isNaN(Date.parse(iso))) return;
  // Check here that the slot is still free in your calendar before you write.
  writeBack(booking, { startTime: iso, status: "confirmed", reminders: {} });
  const when = formatWhen(iso, booking.timeZone);
  return sendText(booking.phone, `Done. Your new time is ${when.date} at ${when.time}.`);
}

async function handleMessage(msg) {
  if (msg.type === "button") {
    const tapped = sends.get(msg.context?.id);
    if (tapped && tapped.state === "sent") tapped.state = "delivered"; // a tap proves delivery
    let [prefix, bookingId, action] = String(msg.button?.payload || "").split("|");
    if (prefix !== "bk") {
      // Payload not in our format: find the reminder this tap belongs to.
      bookingId = sends.get(msg.context?.id)?.bookingId;
      action = { Confirm: "confirm", Reschedule: "reschedule" }[msg.button?.text];
    }
    const booking = bookings.get(bookingId);
    if (booking && action) return onTap(booking, action);
    return console.warn("unmatched button tap", msg.id);
  }
  if (msg.type === "interactive" && msg.interactive?.type === "list_reply") {
    const [prefix, bookingId, iso] = String(msg.interactive.list_reply?.id || "").split("|");
    const booking = bookings.get(bookingId);
    if (prefix === "slot" && booking) return onSlot(booking, iso);
    return;
  }
  if (msg.type === "text" && msg.from && /^\s*stop\s*$/i.test(msg.text?.body || "")) {
    for (const booking of bookings.values()) {
      if (booking.phone === msg.from) booking.optIn = false;
    }
    return sendText(msg.from, "You will not get appointment reminders here anymore.");
  }
}

async function handleWebhook(body) {
  for (const entry of body.entry || []) {
    for (const change of entry.changes || []) {
      if (change.field !== "messages") continue;
      const value = change.value || {};
      for (const status of value.statuses || []) {
        const send = sends.get(status.id);
        if (!send || send.state !== "sent") continue;
        if (status.status === "delivered" || status.status === "read") send.state = "delivered";
        if (status.status === "failed") {
          send.state = "failed";
          console.warn("reminder failed", send.bookingId, JSON.stringify(status.errors));
        }
      }
      for (const msg of value.messages || []) {
        if (seenInbound.has(msg.id)) continue; // Meta retried this webhook
        seenInbound.add(msg.id);
        await handleMessage(msg).catch((err) => console.error("handler error", msg.id, err.message));
      }
    }
  }
}

const app = express();

// Your booking system calls this when a booking is saved.
app.post("/bookings", express.json(), (req, res) => {
  if (req.get("Authorization") !== `Bearer ${INTERNAL_TOKEN}`) return res.sendStatus(401);
  const { id, phone, name, professional, startTime, timeZone = "UTC", optIn } = req.body || {};
  const valid = /^[\w-]{1,64}$/.test(String(id)) && /^[1-9]\d{7,14}$/.test(String(phone))
    && !Number.isNaN(Date.parse(startTime));
  if (!valid) {
    return res.status(400).json({ error: "Need id, phone as E.164 digits without +, and an ISO startTime" });
  }
  const booking = {
    id: String(id), phone: String(phone), name, professional, startTime, timeZone,
    optIn: optIn === true, status: "pending", reminders: {},
  };
  bookings.set(booking.id, booking);
  res.status(201).json(booking);
});

app.get("/webhook", (req, res) => {
  const ok = req.query["hub.mode"] === "subscribe" && req.query["hub.verify_token"] === VERIFY_TOKEN;
  return ok ? res.send(String(req.query["hub.challenge"])) : res.sendStatus(403);
});

app.post("/webhook", express.raw({ type: "application/json" }), (req, res) => {
  if (!Buffer.isBuffer(req.body)) return res.sendStatus(400);
  const received = Buffer.from(req.get("X-Hub-Signature-256") || "");
  const expected = Buffer.from("sha256=" + crypto.createHmac("sha256", APP_SECRET).update(req.body).digest("hex"));
  if (received.length !== expected.length || !crypto.timingSafeEqual(received, expected)) {
    return res.sendStatus(401);
  }
  res.sendStatus(200); // answer first, work after
  let body;
  try {
    body = JSON.parse(req.body.toString("utf8"));
  } catch {
    return;
  }
  handleWebhook(body).catch((err) => console.error("webhook error", err.message));
});

setInterval(() => runReminders().catch((err) => console.error("scheduler error", err.message)), MINUTE);
app.listen(PORT, () => console.log(`listening on ${PORT}`));
```

Crea una prenotazione che inizia tra circa 20 ore, e il tick successivo invia subito `reminder_24h`. Prima di eseguire la richiesta, imposta `startTime` su un orario del genere.

```bash
curl -X POST http://localhost:3000/bookings \
  -H "Authorization: Bearer $INTERNAL_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"id":"bk-1042","phone":"16505551234","name":"Marina","professional":"Jordan Lee","startTime":"2026-11-27T14:30:00-05:00","timeZone":"America/New_York","optIn":true}'
```

Gli stati della prenotazione sono `pending`, `confirmed`, `reschedule_requested` e `cancelled`. Ogni slot di promemoria contiene `sending`, un wamid, `skipped`, `failed` o `dropped`. È questo secondo campo che impedisce allo scheduler di inviare due volte lo stesso promemoria, quindi tienilo nella riga del database, non in memoria.

## Rispondi a Confirm e Reschedule dentro la finestra

Un tocco è un messaggio in entrata, quindi apre una finestra di assistenza clienti di 24 ore. Dentro puoi rispondere senza modello. Per Confirm, il servizio invia una semplice conferma. Per Reschedule, invia una lista interattiva di orari liberi, e l'ID di ogni riga contiene l'ID della prenotazione e lo slot. Se nessuno slot va bene, ripiega su un pulsante CTA URL che apre la tua pagina di prenotazione.

I titoli delle righe sono limitati a 24 caratteri e una lista contiene 10 righe in tutte le sezioni. Il servizio accorcia i titoli per farli stare. [Pulsanti interattivi e messaggi a lista](/academy/it/articles/whatsapp-interactive-buttons-list-messages-limits/) ha la tabella completa dei limiti.

Queste risposte libere contano come messaggi di servizio. Dal 2026-10-01 Meta dà a ogni numero 1.000 messaggi di servizio gratuiti al mese e addebita quelli successivi, come spiegato in [gli addebiti di Meta sui messaggi di servizio da ottobre 2026](/academy/it/articles/meta-whatsapp-service-message-charges-october-2026/).

## Quando il ciclo si rompe

### Il promemoria non è mai stato consegnato

Meta non invia alcun codice di errore quando il TTL scarta un messaggio, quindi l'unico segnale è la mancanza dello stato `delivered`. Il servizio aspetta il TTL più cinque minuti di margine, poi segna il promemoria come `dropped`. È il momento di passare la prenotazione a una persona per una telefonata, o di provare un altro canale accettato dal cliente.

### Il cliente non risponde mai

Un promemoria consegnato senza tocco non dice nulla sulla presenza. Il servizio lascia la prenotazione `pending` e invia comunque il promemoria a 2 ore. Fermati lì. Un terzo modello per lo stesso appuntamento aggiunge costi e dà al cliente un motivo per bloccare il numero.

### Lo stesso tocco arriva due volte

Meta ritenta i webhook che considera falliti, quindi un tocco può arrivarti più di una volta. Il servizio deduplica prima sull'`id` del messaggio in entrata. La macchina a stati intercetta poi un secondo tocco distinto, perché una prenotazione già `confirmed` ignora un altro Confirm. Per una deduplica che sopravviva a un riavvio, salva ogni wamid in entrata in una colonna con indice univoco.

### Promemoria e tocchi in ritardo

Il TTL scarta i promemoria non consegnati, ma un promemoria consegnato in ritardo arriva comunque. Prima di inviare, lo scheduler controlla che l'appuntamento sia ancora nel futuro, e salta un anticipo la cui finestra di TTL è già passata. Un tocco che arriva dopo l'orario di inizio riceve una breve risposta che dice che l'appuntamento è passato.

### Il cliente fa opt-out

Una risposta STOP disattiva i promemoria per tutte le prenotazioni di quel numero. Registra l'opt-out dove il tuo modulo di prenotazione legge il consenso, così la prossima prenotazione non lo riattiva.

### Meta rifiuta l'invio o va in timeout

Il servizio ritenta tre volte con backoff gli errori di rete e le risposte 429 e 5xx, e rinuncia sugli altri errori 4xx. Registra quei body, perché di solito indicano un nome di modello, una lingua o un parametro che non corrispondono. Resta un rischio: un timeout dopo che Meta ha accettato la richiesta può produrre un secondo promemoria al nuovo tentativo. Se questo conta più di un promemoria mancato, abbassa il numero di tentativi.

## Dove si colloca Z-API Omni

La documentazione dei modelli personalizzati di Omni include un modello "Appointment reminder" con le risposte rapide Confirm e Reschedule, come `reminder_24h`. Il suo corpo si apre con una variabile, cosa che secondo la stessa pagina Meta rifiuta, quindi aggiungi prima una parola come "Hi". Lo crei con `POST /whatsapp/businesses/{wabaId}/templates`, che accetta `message_send_ttl_seconds`, e lo invii con `POST /v1/channels/{channelId}/messages`. I modelli funzionano solo sui canali Meta Cloud API. La documentazione non mostra ancora il JSON in arrivo di un tocco su un pulsante di un modello, quindi prova quella corrispondenza prima di portare l'handler.

Lo scheduler resta tuo. Un invio a un canale disconnesso restituisce `422` con `CHANNEL_DISCONNECTED`, e il messaggio «non viene conservato per essere inviato più tardi». Il prezzo è di US$29 per numero al mese da 1 a 10 numeri, US$26 da 11 a 50, US$23 da 51 a 100 e US$20 oltre 100. Le tariffe di Meta vengono riaddebitate sulla connessione ufficiale.

<!-- TODO:test Omni snippet: named-template body parameters without parameter_name, the two quick_reply payloads, and the inbound webhook JSON of the tap -->

```bash
curl -X POST "https://api.omni.z-api.io/v1/channels/$CHANNEL_ID/messages" \
  -H "Authorization: Bearer $OMNI_SECRET_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "recipient": { "identifier": "16505551234" },
    "content": {
      "type": "TEMPLATE",
      "attachments": [
        {
          "template": {
            "name": "appointment_reminder",
            "language": { "policy": "deterministic", "code": "en_US" },
            "components": [
              {
                "type": "body",
                "parameters": [
                  { "type": "text", "text": "Marina" },
                  { "type": "text", "text": "2:30pm" },
                  { "type": "text", "text": "Jordan Lee" }
                ]
              },
              {
                "type": "button",
                "sub_type": "quick_reply",
                "index": 0,
                "parameters": [{ "type": "payload", "payload": "bk|bk-1042|confirm" }]
              },
              {
                "type": "button",
                "sub_type": "quick_reply",
                "index": 1,
                "parameters": [{ "type": "payload", "payload": "bk|bk-1042|reschedule" }]
              }
            ]
          }
        }
      ]
    }
  }'
```

[Vedi la documentazione](https://developer.omni.z-api.io/en)

*Il team di Z-API Omni*
