# Webhook di Calendly per conferme e promemoria su WhatsApp

> Verifica Calendly-Webhook-Signature, invia conferme e promemoria WhatsApp da invitee.created, annulla tramite la API di Calendly e riprogramma con un link.

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

Un'iscrizione webhook di Calendly chiede a Calendly di inviare con un POST un evento JSON firmato al tuo URL ogni volta che un invitato prenota o annulla. Iscriviti a `invitee.created` e `invitee.canceled` con una `signing_key`, verifica `Calendly-Webhook-Signature`, e invia una conferma utility su WhatsApp più un promemoria il giorno prima. Un tocco su Cancel (Annulla) torna indietro tramite l'endpoint di cancellazione di Calendly. Reschedule (Riprogramma) no, perché Calendly non ha un endpoint per riprogrammare, quindi quella risposta porta il `reschedule_url` dell'invitato.

Lo schema del promemoria, con TTL, categoria e tracciamento della consegna, è in [promemoria degli appuntamenti su WhatsApp con Confirm e Reschedule](/academy/it/articles/whatsapp-appointment-reminders-confirm-reschedule/). Lo stesso ciclo per Cal.com è in [dai webhook di Cal.com ai promemoria su WhatsApp](/academy/it/articles/cal-com-webhook-whatsapp-booking-reminders/).

## Il ciclo dalla prenotazione all'evento aggiornato

1. Calendly invia `invitee.created`. Verifichi la firma, salvi l'evento e rispondi con un 2xx.
2. Se l'invitato ha dato un numero di telefono e il consenso WhatsApp, invii `booking_confirmed`.
3. Il tuo scheduler invia `booking_reminder_24h` con Confirm (Conferma), Cancel e Reschedule un giorno prima di `start_time`.
4. Il tocco arriva al tuo webhook WhatsApp come messaggio `button`.
5. Confirm viene salvato nella tua tabella, Cancel chiama Calendly, e Reschedule risponde con il link.

Calendly non invia alcun webhook di promemoria, quindi è il tuo job a leggere `scheduled_event.start_time` dalla prenotazione salvata. Gli zap "Calendly + WhatsApp Notifications" di Zapier coprono l'invio per i nuovi invitati e le cancellazioni ([Zapier](https://zapier.com/apps/calendly/integrations/whatsapp-notifications), consultato il 2026-11-27). La scheda non descrive come riscrivere una risposta dentro Calendly.

## Crea l'iscrizione con una chiave di firma

I webhook non richiedono un piano a pagamento. Le FAQ di Calendly dicono che «I webhook sono disponibili su tutti i piani Calendly, incluso il piano Free» ([FAQ per sviluppatori di Calendly](https://developer.calendly.com/docs/getting-started/frequently-asked-questions.md), consultato il 2026-11-27). Anche la pagina di aiuto, aggiornata il 4 novembre 2026, indica «Tutti i piani». Solo `meeting_recap.*` e `routing_form_submission.created` richiedono un account a pagamento, e altrimenti restituiscono `403` "Please upgrade to a paid Calendly account.".

Il token può essere un Personal Access Token o OAuth. Gli serve `webhooks:write`, più `scheduled_events:read` per gli eventi `invitee.*` ([creare un'iscrizione webhook](https://developer.calendly.com/api-docs/calendly-api/webhooks/create-webhook-subscription.md), consultato il 2026-11-27). Chiedi `scheduled_events:write` al posto dello scope di lettura, perché il tocco su Cancel ne ha bisogno e uno scope `:write` include il `:read` corrispondente. Aggiungi `users:read` per leggere l'organizzazione. I nuovi PAT «non hanno accesso alla API finché gli scope non vengono richiesti e approvati esplicitamente» ([scope](https://developer.calendly.com/docs/authentication/scopes.md), consultato il 2026-11-27).

Invia sempre `signing_key` quando crei un'iscrizione con un PAT. Per Calendly è facoltativa, e senza di essa le richieste arrivano non firmate. Con OAuth, «una chiave di firma dei webhook viene generata automaticamente per tutti i webhook legati alla tua applicazione». Se la perdi, Calendly dice di «contattare il supporto per sviluppatori» ([firme dei webhook](https://developer.calendly.com/api-docs/overview/webhooks/webhook-signatures), consultato il 2026-11-27).

Owner e admin possono iscriversi con scope `organization` o `user`. Gli altri membri possono usare solo `user`. Una seconda iscrizione con lo stesso URL restituisce `409` "Hook with this url already exists", quindi elenca le iscrizioni prima di crearne una.

```bash
# 1. Your organization URI is resource.current_organization (scope users:read).
curl -s https://api.calendly.com/users/me \
  -H "Authorization: Bearer $CALENDLY_TOKEN"

# 2. List existing subscriptions first. Look for your URL and its state (active or disabled).
curl -s --get https://api.calendly.com/webhook_subscriptions \
  --data-urlencode "organization=$ORG_URI" \
  --data-urlencode "scope=organization" \
  -H "Authorization: Bearer $CALENDLY_TOKEN"

# 3. Create it only if it is missing. CALENDLY_SIGNING_KEY is a secret you generate.
curl -s -X POST https://api.calendly.com/webhook_subscriptions \
  -H "Authorization: Bearer $CALENDLY_TOKEN" \
  -H "Content-Type: application/json" \
  -d "{\"url\":\"$WEBHOOK_URL\",\"events\":[\"invitee.created\",\"invitee.canceled\"],\"organization\":\"$ORG_URI\",\"scope\":\"organization\",\"signing_key\":\"$CALENDLY_SIGNING_KEY\"}"
```

Un `201` restituisce l'iscrizione sotto `resource`, con `uri`, `callback_url`, `state` e `retry_started_at`.

## Cosa contiene invitee.created

Ogni consegna ha `event`, `created_at`, `created_by` e un `payload` che descrive l'invitato. Questo estratto è abbreviato e riformattato dall'esempio di Calendly, e tiene i campi che il servizio legge ([dati di esempio dei webhook](https://developer.calendly.com/api-docs/calendly-api/webhooks/get-sample-webhook-data.md), consultato il 2026-11-27).

```json
{
  "event": "invitee.created",
  "created_at": "2020-11-23T17:51:19.000000Z",
  "payload": {
    "cancel_url": "https://calendly.com/cancellations/AAAAAAAAAAAAAAAA",
    "name": "John Doe",
    "new_invitee": null,
    "old_invitee": null,
    "questions_and_answers": [],
    "reschedule_url": "https://calendly.com/reschedulings/AAAAAAAAAAAAAAAA",
    "rescheduled": false,
    "scheduled_event": {
      "event_type": "https://api.calendly.com/event_types/AAAAAAAAAAAAAAAA",
      "location": { "additional_info": "Please check in at the front desk.", "location": "Calendly Office", "type": "physical" },
      "name": "15 Minute Meeting",
      "start_time": "2019-08-24T14:15:22.123456Z",
      "uri": "https://api.calendly.com/scheduled_events/AAAAAAAAAAAAAAAA"
    },
    "status": "active",
    "text_reminder_number": null,
    "timezone": "America/New_York",
    "uri": "https://api.calendly.com/scheduled_events/AAAAAAAAAAAAAAAA/invitees/AAAAAAAAAAAAAAAA"
  }
}
```

`payload.uri` è l'invitato, e il suo ultimo segmento è la chiave della prenotazione nel servizio. L'ultimo segmento di `scheduled_event.uri` è l'UUID dell'evento che l'endpoint di cancellazione si aspetta. `timezone` è il «fuso orario da usare quando si mostra l'ora all'invitato» ([get event invitee](https://developer.calendly.com/api-docs/calendly-api/scheduled-events/get-event-invitee.md), consultato il 2026-11-27). `invitee.canceled` ha la stessa forma, con `status: "canceled"` e un oggetto `cancellation` che contiene `canceled_by`, `canceler_type` e `reason`.

### Da dove arriva il numero di telefono

Calendly ha tre punti che possono contenere un numero di telefono, e nessuno è garantito.

- `text_reminder_number`, descritto come «il numero di telefono da usare per inviare promemoria via testo (SMS)». È presente solo se l'invitato ha scelto i promemoria SMS.
- Una domanda personalizzata "Phone number" (Numero di telefono) per l'invitato. Arriva in `questions_and_answers[]` come `{question, answer, position}`, e la abbini tramite il testo esatto della domanda.
- `scheduled_event.location` con `type: "outbound_call"`, dove `location` è «il numero di telefono che l'host userà per chiamare l'invitato».

Calendly non documenta il formato della risposta né se includa il prefisso internazionale. Il servizio accetta un `+` o un `00` iniziale, e per i numeri locali ricorre a `DEFAULT_COUNTRY_CODE`. Senza nessuno dei due, salta il messaggio invece di tirare a indovinare. [Normalizzazione dei numeri di telefono E.164](/academy/it/articles/whatsapp-phone-number-format-e164-normalization/) tratta i casi limite.

### Il consenso WhatsApp è una domanda tua

Calendly non ha un campo per il consenso WhatsApp. `text_reminder_number` riflette una scelta sugli SMS, quindi non vale come consenso WhatsApp. Aggiungi una domanda personalizzata per l'invitato che nomini WhatsApp e lo scopo, e invia solo se la risposta è sì. Il servizio la abbina tramite il testo esatto, impostato in `CONSENT_QUESTION`. [Come raccogliere l'opt-in WhatsApp](/academy/it/articles/whatsapp-opt-in-how-to-collect-consent/) tratta la formulazione e il record da conservare.

## Verifica la firma e rispondi sempre con un 2xx

Calendly invia `Calendly-Webhook-Signature: t=<unix>,v1=<hex>`. Il valore `v1` è un HMAC-SHA256, codificato in esadecimale, calcolato su «il timestamp (t), il carattere '.' e il payload JSON del body della richiesta» ([firme dei webhook](https://developer.calendly.com/api-docs/overview/webhooks/webhook-signatures), consultato il 2026-11-27). Calcolalo sui byte grezzi del body. L'esempio di Calendly rifiuta i webhook «più vecchi di 3 minuti», quindi il servizio usa 180 secondi e rende il valore configurabile.

Con qualsiasi 3xx, 4xx o 5xx, Calendly «continuerà a tentare la consegna per 24 ore» «con un back-off esponenziale» ([errori dei webhook](https://developer.calendly.com/api-docs/overview/webhooks/webhook-errors.md), consultato il 2026-11-27). Si ferma anche «24 ore dopo che è passata la prenotazione dell'evento». Dopo, «il webhook viene disattivato se un altro messaggio non è stato consegnato correttamente», e «l'hook deve essere ricreato».

Restituire 400 per un rifiuto di logica di business, per esempio una prenotazione senza telefono, fa riconsegnare quell'evento per un giorno e può disattivare l'iscrizione. Il servizio restituisce 2xx appena l'evento è verificato e salvato, e registra il rifiuto nei log.

Calendly concede un timeout di connessione di 10 secondi e un timeout di lettura di 15 secondi, e chiede di confermare la ricezione «immediatamente» ed elaborare in modo asincrono ([timeout dei webhook](https://developer.calendly.com/api-docs/overview/webhooks/webhook-timeouts.md), consultato il 2026-11-27). Calendly non documenta alcun header con un ID di consegna o di evento. Il servizio costruisce la propria chiave di deduplica da `event`, `payload.uri` e `created_at`. Quella chiave è una nostra deduzione, non una regola di Calendly.

## Una riprogrammazione arriva come due eventi

Quando un invitato sceglie un nuovo orario, Calendly emette `invitee.canceled` con `rescheduled: true` e un nuovo `invitee.created` ([payload delle riprogrammazioni](https://developer.calendly.com/docs/api-guides/see-how-webhook-payloads-change-when-invitees-reschedule-events.md), consultato il 2026-11-27). Gli invitati si riferiscono l'uno all'altro tramite `old_invitee` e `new_invitee`. L'ordine delle due consegne non è documentato.

Non inviare mai «annullato» per la prima metà di una riprogrammazione. Il servizio si basa sul flag `rescheduled`. Un `invitee.canceled` con `rescheduled: true` segna la vecchia riga come `moved` e non invia nulla. Un `invitee.created` con un `old_invitee` segna anch'esso la vecchia riga come `moved` e invia `booking_moved` con il nuovo orario. In entrambi gli ordini si arriva allo stesso stato.

Tornano indietro anche le tue cancellazioni. Una cancellazione tramite API emette `invitee.canceled` con `canceler_type: "host"`. Il servizio imposta la riga su `cancel_requested` prima della chiamata, così quel webhook resta muto invece di mandare un secondo avviso.

## Quattro modelli utility

Tutti e quattro sono modelli utility. Ognuno riguarda un incontro che l'invitato ha prenotato, e questo supera il test di Meta come spiegato in [l'articolo pilastro sui promemoria](/academy/it/articles/whatsapp-appointment-reminders-confirm-reschedule/). Una promozione aggiunta a uno qualsiasi di essi lo trasforma in marketing.

| Modello | Corpo | Pulsanti | TTL |
| --- | --- | --- | --- |
| `booking_confirmed` | Hi {{customer_name}}, your {{event}} is booked for {{date}} at {{time}}. Reply here if you have a question. (Ciao {{customer_name}}, il tuo {{event}} è prenotato per {{date}} alle {{time}}. Rispondi qui se hai una domanda.) | Nessuno | Predefinito |
| `booking_moved` | Hi {{customer_name}}, your {{event}} has moved to {{date}} at {{time}}. (Ciao {{customer_name}}, il tuo {{event}} è stato spostato a {{date}} alle {{time}}.) | Nessuno | Predefinito |
| `booking_cancelled` | Hi {{customer_name}}, your {{event}} on {{date}} at {{time}} is cancelled. (Ciao {{customer_name}}, il tuo {{event}} di {{date}} alle {{time}} è annullato.) | Nessuno | Predefinito |
| `booking_reminder_24h` | Hi {{customer_name}}, a reminder that your {{event}} is on {{date}} at {{time}}. Please confirm, cancel or reschedule below. (Ciao {{customer_name}}, ti ricordiamo che il tuo {{event}} è {{date}} alle {{time}}. Conferma, annulla o riprogramma qui sotto.) | Risposte rapide Confirm, Cancel, Reschedule | 43.200 secondi |

Creali con la chiamata `message_templates` dell'[articolo pilastro sui promemoria](/academy/it/articles/whatsapp-appointment-reminders-confirm-reschedule/), che spiega anche `message_send_ttl_seconds`. Il nome di un evento Calendly può descrivere un trattamento, quindi le cliniche dovrebbero riempire `{{event}}` con una parola neutra come "appointment" (appuntamento).

Per la conferma, il modello di Meta per gli appuntamenti è un'alternativa con un pannello "View details" (Vedi dettagli) e un link di gestione. Un `reschedule_url` ha la forma `https://calendly.com/reschedulings/<id>`, quindi un `booking_management_url` uguale a `https://calendly.com/reschedulings/{{1}}`, con l'ID come suffisso, rispetta la regola di Meta di un solo parametro alla fine. Questa compatibilità è una nostra deduzione, quindi provala. [L'articolo sul modello per gli appuntamenti](/academy/it/articles/whatsapp-booking-appointment-template-manage-link/) ha i campi.

## Il servizio da Calendly a WhatsApp

Questo file gira così com'è su Node 18 o successivo con Express 4. Tiene lo stato in memoria per poterlo provare, e il job dei promemoria gira ogni minuto.

```js
// calendly-whatsapp.js: Calendly invitee webhooks to WhatsApp confirmations, reminders and replies.
// Node 18+ and Express 4. Run: npm install express && node calendly-whatsapp.js
const crypto = require("crypto");
const express = require("express");

function env(name, fallback) {
  const value = process.env[name] || fallback;
  if (!value) throw new Error(`Missing environment variable ${name}`);
  return value;
}
const CALENDLY_TOKEN = env("CALENDLY_TOKEN"); // PAT or OAuth token with scheduled_events:write
const CALENDLY_SIGNING_KEY = env("CALENDLY_SIGNING_KEY"); // the signing_key set on the subscription
const SIGNATURE_TOLERANCE_S = Number(env("SIGNATURE_TOLERANCE_S", "180"));
const PHONE_QUESTION = env("PHONE_QUESTION", "Phone number"); // exact text of your invitee question
const CONSENT_QUESTION = env("CONSENT_QUESTION", "May we send booking messages to this number on WhatsApp?");
const DEFAULT_COUNTRY_CODE = process.env.DEFAULT_COUNTRY_CODE || ""; // digits, for answers typed without +
const GROUP_EVENT_TYPES = new Set((process.env.GROUP_EVENT_TYPES || "").split(",").filter(Boolean));
const WA_TOKEN = env("WA_TOKEN");
const PHONE_NUMBER_ID = env("PHONE_NUMBER_ID");
const APP_SECRET = env("APP_SECRET");
const VERIFY_TOKEN = env("VERIFY_TOKEN");
const PORT = Number(env("PORT", "3000"));

const CALENDLY_API = "https://api.calendly.com";
const GRAPH_URL = `https://graph.facebook.com/v26.0/${PHONE_NUMBER_ID}/messages`;
const MINUTE = 60 * 1000;
const HOUR = 60 * MINUTE;
const REMINDER_LEAD = 24 * HOUR;
const REMINDER_TTL = 12 * HOUR; // message_send_ttl_seconds 43200 on booking_reminder_24h

// In-memory state so the file runs as is. Use your database in production.
const bookings = new Map(); // invitee uuid -> booking
const seenCalendly = new Set(); // event|invitee uri|created_at
const seenWa = new Set(); // inbound wamids
const lastSegment = (uri) => String(uri || "").split("/").pop();

function safeEqual(a, b) {
  const x = Buffer.from(String(a));
  const y = Buffer.from(String(b));
  return x.length === y.length && crypto.timingSafeEqual(x, y);
}

function verifyCalendly(header, rawBody) {
  const parts = {};
  for (const item of String(header || "").split(",")) {
    const i = item.indexOf("=");
    if (i > 0) parts[item.slice(0, i).trim()] = item.slice(i + 1).trim();
  }
  const t = Number(parts.t);
  if (!parts.t || !parts.v1 || !Number.isFinite(t)) return false;
  if (Math.abs(Date.now() / 1000 - t) > SIGNATURE_TOLERANCE_S) return false; // too old, or clock skew
  const expected = crypto.createHmac("sha256", CALENDLY_SIGNING_KEY)
    .update(`${parts.t}.`)
    .update(rawBody)
    .digest("hex");
  return safeEqual(parts.v1, expected);
}

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" }),
  };
}

function answer(p, question) {
  const item = (p.questions_and_answers || []).find((qa) => qa.question === question);
  return item ? String(item.answer || "") : "";
}

function toWhatsAppNumber(raw) {
  const text = String(raw || "").trim();
  let digits = text.replace(/\D/g, "");
  if (!digits) return null;
  if (text.startsWith("00")) digits = digits.slice(2);
  else if (!text.startsWith("+")) {
    if (!DEFAULT_COUNTRY_CODE) return null; // no country code and no default: do not guess
    digits = DEFAULT_COUNTRY_CODE + digits.replace(/^0+/, "");
  }
  return /^[1-9]\d{7,14}$/.test(digits) ? digits : null;
}

function phoneFrom(p) {
  const ev = p.scheduled_event || {};
  const candidates = [
    answer(p, PHONE_QUESTION),
    p.text_reminder_number,
    ev.location && ev.location.type === "outbound_call" ? ev.location.location : null,
  ];
  for (const candidate of candidates) {
    const number = toWhatsAppNumber(candidate);
    if (number) return number;
  }
  return null;
}

function fromPayload(p) {
  const ev = p.scheduled_event || {};
  return {
    id: lastSegment(p.uri),
    eventUuid: lastSegment(ev.uri),
    eventType: ev.event_type,
    title: ev.name || "appointment",
    name: p.name || "there",
    phone: phoneFrom(p),
    consent: /^\s*yes\b/i.test(answer(p, CONSENT_QUESTION)),
    startTime: ev.start_time,
    timeZone: p.timezone || "UTC",
    cancelUrl: p.cancel_url,
    rescheduleUrl: p.reschedule_url,
    createdAt: Date.now(),
    status: "booked", // booked | confirmed | cancel_requested | cancelled | moved
    reminder: null, // null | "sending" | "skipped" | "failed" | wamid
  };
}

const canMessage = (booking) => Boolean(booking.phone && booking.consent);

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) };
  }
  // A network error after Meta accepted the send can duplicate it; lower the attempts if that matters.
  if ((status === 0 || status === 429 || status >= 500) && attempt < 4) {
    await new Promise((resolve) => setTimeout(resolve, 2 ** attempt * 1000));
    return sendWhatsApp(message, attempt + 1);
  }
  throw new Error(`WhatsApp send failed with HTTP ${status}: ${JSON.stringify(data)}`);
}

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

const sendLink = (to, text, label, url) => sendWhatsApp({
  to,
  type: "interactive",
  interactive: {
    type: "cta_url",
    body: { text },
    action: { name: "cta_url", parameters: { display_text: label, url } },
  },
});

function templateMessage(booking, name, withButtons) {
  const when = formatWhen(booking.startTime, booking.timeZone);
  const components = [{
    type: "body",
    parameters: [
      { type: "text", parameter_name: "customer_name", text: booking.name },
      { type: "text", parameter_name: "event", text: booking.title },
      { type: "text", parameter_name: "date", text: when.date },
      { type: "text", parameter_name: "time", text: when.time },
    ],
  }];
  if (withButtons) {
    ["confirm", "cancel", "reschedule"].forEach((action, index) => components.push({
      type: "button",
      sub_type: "quick_reply",
      index: String(index),
      parameters: [{ type: "payload", payload: `cal|${booking.id}|${action}` }],
    }));
  }
  return { to: booking.phone, type: "template", template: { name, language: { code: "en_US" }, components } };
}

async function onCalendly(event, p) {
  if (event === "invitee.created") {
    const booking = fromPayload(p);
    if (!booking.id || bookings.has(booking.id)) return;
    const old = p.old_invitee ? bookings.get(lastSegment(p.old_invitee)) : null;
    if (old) {
      old.status = "moved"; // the old time is gone, whichever event arrives first
      if (!booking.phone) booking.phone = old.phone;
      if (!answer(p, CONSENT_QUESTION)) booking.consent = old.consent; // keep the consent you recorded
    }
    bookings.set(booking.id, booking);
    if (!canMessage(booking)) return console.log("no phone or no WhatsApp consent", booking.id);
    await sendWhatsApp(templateMessage(booking, p.old_invitee ? "booking_moved" : "booking_confirmed", false));
    return;
  }
  if (event === "invitee.canceled") {
    const booking = bookings.get(lastSegment(p.uri));
    if (!booking) return;
    if (p.rescheduled) {
      booking.status = "moved"; // the invitee.created for the new time sends the message
      return;
    }
    const ours = booking.status === "cancel_requested" || booking.status === "cancelled";
    booking.status = "cancelled";
    if (ours || !canMessage(booking)) return; // already answered in the chat
    await sendWhatsApp(templateMessage(booking, "booking_cancelled", false));
    return;
  }
  console.log("not handled", event);
}

async function runReminders() {
  const now = Date.now();
  for (const booking of bookings.values()) {
    if (booking.reminder || booking.status !== "booked" || !canMessage(booking)) continue;
    const start = Date.parse(booking.startTime);
    if (now < start - REMINDER_LEAD) continue;
    const bookedLate = booking.createdAt > start - REMINDER_LEAD; // the confirmation was enough
    if (bookedLate || now >= start - REMINDER_LEAD + REMINDER_TTL || now >= start) {
      booking.reminder = "skipped";
      continue;
    }
    booking.reminder = "sending"; // claimed before the await
    try {
      booking.reminder = await sendWhatsApp(templateMessage(booking, "booking_reminder_24h", true));
    } catch (err) {
      booking.reminder = "failed";
      console.error("reminder failed", booking.id, err.message);
    }
  }
}

async function cancelOnCalendly(booking) {
  const res = await fetch(`${CALENDLY_API}/scheduled_events/${booking.eventUuid}/cancellation`, {
    method: "POST",
    headers: { Authorization: `Bearer ${CALENDLY_TOKEN}`, "Content-Type": "application/json" },
    body: JSON.stringify({ reason: "Cancelled by the invitee on WhatsApp" }),
  });
  if (res.status === 201) return "cancelled";
  const text = await res.text();
  if (res.status === 403 && text.includes("already canceled")) return "cancelled"; // idempotent
  if (res.status === 403 && text.includes("Event in the past")) return "past";
  throw new Error(`Calendly cancellation returned ${res.status}: ${text}`);
}

async function onTap(booking, action) {
  if (booking.status === "cancel_requested" || booking.status === "cancelled") {
    return sendText(booking.phone, "This booking is already cancelled.");
  }
  if (booking.status === "moved") {
    return sendText(booking.phone, "This booking was moved to a new time, so this message no longer applies.");
  }
  if (Date.parse(booking.startTime) <= Date.now()) return sendText(booking.phone, "This booking has already passed.");
  const when = formatWhen(booking.startTime, booking.timeZone);
  if (action === "confirm") {
    if (booking.status === "confirmed") return; // a second tap changes nothing
    booking.status = "confirmed"; // kept here: Calendly has no field for it
    return sendText(booking.phone, `Thanks, ${booking.name}. You are confirmed for ${when.date} at ${when.time}.`);
  }
  if (action === "reschedule") {
    return sendLink(booking.phone, "Pick a new time on Calendly. We will send the new time here.", "Pick a new time",
      booking.rescheduleUrl);
  }
  if (action === "cancel") {
    if (GROUP_EVENT_TYPES.has(booking.eventType)) {
      // The API cancels the whole event, not one invitee, so send the invitee's own link.
      return sendLink(booking.phone, "Use this link to cancel your place.", "Cancel my place", booking.cancelUrl);
    }
    const previous = booking.status;
    booking.status = "cancel_requested"; // set before the call so the webhook echo stays silent
    let result;
    try {
      result = await cancelOnCalendly(booking);
    } catch (err) {
      booking.status = previous;
      console.error(err.message);
      return sendText(booking.phone, "We could not cancel this booking. A person on our team will follow up.");
    }
    if (result === "past") {
      booking.status = previous;
      return sendText(booking.phone, "This booking has already passed.");
    }
    booking.status = "cancelled";
    return sendText(booking.phone, "Your booking is cancelled.");
  }
}

async function onWhatsAppMessage(msg) {
  if (msg.type === "button") {
    const [prefix, id, action] = String(msg.button?.payload || "").split("|");
    const fromContext = [...bookings.values()].find((b) => b.reminder === msg.context?.id);
    const booking = prefix === "cal" ? bookings.get(id) : fromContext;
    const act = prefix === "cal"
      ? action
      : { Confirm: "confirm", Cancel: "cancel", Reschedule: "reschedule" }[msg.button?.text];
    if (booking && act) return onTap(booking, act);
    return console.warn("unmatched tap", msg.id);
  }
  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.consent = false;
    return sendText(msg.from, "You will not get booking messages here anymore.");
  }
}

const app = express();

app.post("/calendly/webhook", express.raw({ type: "*/*" }), (req, res) => {
  if (!Buffer.isBuffer(req.body) || !verifyCalendly(req.get("Calendly-Webhook-Signature"), req.body)) {
    console.warn("rejected Calendly request: bad or missing signature");
    return res.sendStatus(401);
  }
  let body;
  try {
    body = JSON.parse(req.body.toString("utf8"));
  } catch {
    console.error("signed body is not JSON; acknowledged so Calendly stops retrying");
    return res.sendStatus(200);
  }
  const key = `${body.event}|${body.payload?.uri}|${body.created_at}`;
  if (seenCalendly.has(key)) return res.sendStatus(200);
  seenCalendly.add(key); // in production, insert into a table with this key as primary key
  res.sendStatus(200); // stored, so acknowledge before doing the work
  onCalendly(body.event, body.payload || {}).catch((err) => console.error("calendly event", key, err.message));
});

app.get("/wa/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("/wa/webhook", express.raw({ type: "application/json" }), (req, res) => {
  if (!Buffer.isBuffer(req.body)) return res.sendStatus(400);
  const expected = "sha256=" + crypto.createHmac("sha256", APP_SECRET).update(req.body).digest("hex");
  if (!safeEqual(req.get("X-Hub-Signature-256") || "", expected)) return res.sendStatus(401);
  res.sendStatus(200);
  let body;
  try {
    body = JSON.parse(req.body.toString("utf8"));
  } catch {
    return;
  }
  for (const entry of body.entry || []) {
    for (const change of entry.changes || []) {
      if (change.field !== "messages") continue;
      for (const status of change.value?.statuses || []) {
        if (status.status === "failed") console.warn("send failed", status.id, JSON.stringify(status.errors));
      }
      for (const msg of change.value?.messages || []) {
        if (seenWa.has(msg.id)) continue;
        seenWa.add(msg.id);
        onWhatsAppMessage(msg).catch((err) => console.error("whatsapp message", msg.id, err.message));
      }
    }
  }
});

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

Per provare la route di Calendly senza una prenotazione vera, firma un body con la tua chiave e l'ora attuale. Il servizio risponde 200, poi prova a inviare `booking_confirmed`, che richiede il modello approvato e un numero che accetti messaggi di prova.

```bash
T=$(date +%s)
BODY='{"event":"invitee.created","created_at":"2026-11-27T12:00:00.000000Z","payload":{"uri":"https://api.calendly.com/scheduled_events/EVT1/invitees/INV1","name":"Marina","timezone":"America/New_York","cancel_url":"https://calendly.com/cancellations/INV1","reschedule_url":"https://calendly.com/reschedulings/INV1","rescheduled":false,"old_invitee":null,"text_reminder_number":null,"questions_and_answers":[{"question":"Phone number","answer":"+1 650 555 1234","position":0},{"question":"May we send booking messages to this number on WhatsApp?","answer":"Yes","position":1}],"scheduled_event":{"uri":"https://api.calendly.com/scheduled_events/EVT1","name":"Consultation","start_time":"2026-11-30T15:00:00.000000Z","event_type":"https://api.calendly.com/event_types/ET1"}}}'
SIG=$(printf '%s.%s' "$T" "$BODY" | openssl dgst -sha256 -hmac "$CALENDLY_SIGNING_KEY" | awk '{print $NF}')
curl -i -X POST http://localhost:3000/calendly/webhook \
  -H "Content-Type: application/json" \
  -H "Calendly-Webhook-Signature: t=$T,v1=$SIG" \
  --data-binary "$BODY"
```

## Riporta il tocco su Calendly

| Tocco | Cosa fa il servizio | Chiamata a Calendly |
| --- | --- | --- |
| Confirm | Segna la riga come `confirmed` nella tua tabella | Nessuna |
| Cancel | Annulla l'evento | `POST /scheduled_events/{uuid}/cancellation` con scope `scheduled_events:write` |
| Cancel, evento di gruppo | Invia il `cancel_url` dell'invitato | Nessuna |
| Reschedule | Invia il `reschedule_url` dell'invitato come pulsante CTA URL | Nessuna: non esiste un endpoint |

Il body della cancellazione è facoltativo, per esempio `{"reason": "Something came up."}`. Un `201` restituisce `canceled_by`, `reason`, `canceler_type` e `created_at` ([annullare un evento](https://developer.calendly.com/api-docs/calendly-api/scheduled-events/create-scheduled-event-cancellation.md), consultato il 2026-11-27). Gli errori condividono `403 Permission Denied`, con i messaggi "You are not allowed to cancel this event", "Event in the past" o "Event is already canceled". Per questo il servizio si dirama in base al messaggio e tratta "already canceled" come un successo.

Le FAQ dicono che l'endpoint annulla «un evento, compreso un evento di gruppo, ma non un singolo invitato». Chiamarlo per una persona in una sessione di gruppo annullerebbe l'evento per tutti. Elenca gli URI dei tuoi tipi di evento di gruppo in `GROUP_EVENT_TYPES`, e per quelli il servizio invia invece `cancel_url`.

Sulla riprogrammazione, le FAQ sono dirette: «Al momento non esiste un endpoint della API che permetta di riprogrammare un evento o un invitato.» La Scheduling API con `POST https://api.calendly.com/invitees` può prenotare un nuovo orario. Annullare e poi creare non è un'operazione atomica, e i tipi di evento a pagamento non si possono prenotare da lì. Consente 5 prenotazioni per utente al giorno sui piani Free e Trial e 100 al giorno sui piani a pagamento sotto Enterprise ([limiti di frequenza](https://developer.calendly.com/api-docs/overview/rate-limits.md), consultato il 2026-11-27).

La risposta a un tocco è testo libero, perché il tocco ha aperto una finestra di 24 ore. Quelle risposte sono messaggi di servizio, con i prezzi descritti 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

### Calendly disattiva l'iscrizione

Una chiave di firma sbagliata nel tuo ambiente fa sì che il servizio rifiuti ogni consegna reale con 401. Calendly continua a ritentare per 24 ore, poi disattiva l'hook. Controlla `state` sull'endpoint di elenco con un job giornaliero, e ricrea l'iscrizione se risulta `disabled`. Le pagine di Calendly non descrivono un nuovo invio degli eventi dopo che l'hai ricreata, quindi confronta la tua tabella con gli eventi che ti aspetti.

### Lo stesso evento arriva due volte

La chiave formata da `event`, `payload.uri` e `created_at` intercetta un nuovo tentativo, e la mappa delle prenotazioni intercetta un secondo `invitee.created` per lo stesso invitato. Sposta entrambe in una tabella con una chiave univoca prima della produzione, altrimenti un riavvio le cancella.

### Niente telefono, niente consenso, o STOP

Una prenotazione senza un numero utilizzabile o senza un sì alla domanda sul consenso non riceve alcun messaggio WhatsApp, e il webhook restituisce comunque 200. Una risposta STOP toglie il consenso su tutte le prenotazioni di quel numero. Registra l'opt-out nel punto in cui leggi il consenso, così una prenotazione successiva non lo riattiva.

### La cancellazione fallisce

Un errore di rete o uno stato inatteso lascia la riga com'era, e l'invitato viene avvisato che una persona lo ricontatterà. Manda quei log a qualcuno che possa intervenire.

## Dove si colloca Z-API Omni

La documentazione dei modelli personalizzati di Omni include un modello "Appointment reminder" (Promemoria appuntamento) con le risposte rapide Confirm e Reschedule, e puoi aggiungere Cancel come terza. Crei i modelli con `POST /whatsapp/businesses/{wabaId}/templates`, che accetta `message_send_ttl_seconds`. Li invii con `POST /v1/channels/{channelId}/messages` sui canali Meta Cloud API. La documentazione non mostra il JSON in arrivo di un tocco su un pulsante del modello, quindi prova quella mappatura prima di portare l'handler.

La documentazione non descrive alcuna integrazione con Calendly né uno scheduler, quindi il job dei promemoria e la chiamata di cancellazione restano nel tuo servizio. I webhook sono firmati con `x-webhook-signature`, come mostra il [quickstart Node.js](/academy/it/articles/z-api-omni-quickstart-nodejs-express/). Ogni numero costa US$29 al mese da 1 a 10 numeri, US$26 da 11 a 50, US$23 da 51 a 100 e US$20 oltre 100. Sulla connessione ufficiale, le tariffe di Meta vengono riaddebitate.

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

*Il team di Z-API Omni*
