Iscrivi un webhook di Cal.com o Cal.diy a BOOKING_CREATED, BOOKING_RESCHEDULED e BOOKING_CANCELLED, e verifica X-Cal-Signature-256 su ogni richiesta. Tieni una tua copia di ogni prenotazione con chiave uid, poi invia una conferma utility e un promemoria a 24 ore con Confirm, Reschedule e Cancel (Conferma, Riprogramma, Annulla). I tocchi su Cancel e Reschedule tornano indietro tramite la API v2 di Cal.com. Confirm viene salvato nella tua tabella, perché la API v2 di Cal.com non documenta alcun endpoint con cui un partecipante confermi la propria presenza.
Lo schema del promemoria, con TTL, categoria del modello e tracciamento della consegna, è in promemoria degli appuntamenti su WhatsApp con Confirm e Reschedule. Questo articolo copre ciò che aggiunge Cal: il suo payload, la sua firma, i suoi endpoint di scrittura e gli eventi che le tue chiamate ti rimandano indietro. La versione per Calendly è in webhook di Calendly verso WhatsApp, e una lista d’attesa su WhatsApp può riempire di nuovo uno slot quando una prenotazione viene annullata.
Perché Cal.diy self-hosted ha bisogno di un proprio percorso per i promemoria
Cal.diy non ha promemoria integrati da quando si è separato da Cal.com ad aprile 2026. L’articolo di Cal.com del 2026-04-15 descrive Cal.diy come «la piattaforma di pianificazione open source», con licenza passata da AGPL 3.0 a MIT, e dice che «Cal.diy include solo la API v2» (Moving to closed-source: the technical changes, consultato il 2026-11-25). La logica di pianificazione, l’app store, i flussi di prenotazione e la API v2 sono rimasti. Il «motore di workflow automatici (promemoria, follow-up, trigger)» è stato rimosso.
Il README del repository conferma: «Teams, Organizations, Insights, Workflows, SSO/SAML e altre funzioni solo EE sono state rimosse» (calcom/cal.diy, consultato il 2026-11-25). Dice anche: «Non esiste una versione hosted/gestita.»
Due pull request di ottobre e novembre 2026 sono pulizia successiva a quella separazione. La PR #30447 ha rimosso il 2026-10-29 stringhe inutilizzate dei workflow WhatsApp e ha chiuso la issue #30446, che nota che «Workflows non è in Cal.diy». La PR #30442 ha rimosso la pagina di Twilio e le variabili d’ambiente di Twilio inutilizzate, ed è stata unita il 2026-11-03. La PR #30334 è ancora aperta ed è stata segnata come inattiva il 2026-11-08.
Cal.com hosted ha ancora i Workflows, e il suo riferimento API elenca un endpoint /v2/workflows. Il percorso via webhook qui sotto funziona allo stesso modo con Cal.com hosted e con un’installazione self-hosted di Cal.diy.
Prepara il tipo di evento: numero di telefono e consenso
Cal salva il telefono del partecipante in un campo di sistema della prenotazione chiamato attendeePhoneNumber. Nel sorgente di Cal.diy è definito con type: "phone", hidden: true e required: false (getBookingFields.ts, consultato il 2026-11-25). Di base non lo vede nessuno, quindi rendilo visibile nelle domande di prenotazione del tipo di evento.
Accanto, aggiungi una domanda a casella per il consenso WhatsApp. Cal non ne fornisce una, quindi è un consiglio, non una funzione di Cal. Formulala in modo che il partecipante conosca il canale e lo scopo. Un esempio: «Inviami conferme e promemoria delle prenotazioni su WhatsApp.» Il codice legge questa domanda tramite il suo identificativo, impostato in CONSENT_FIELD. Come raccogliere l’opt-in WhatsApp spiega cos’altro registrare.
Il servizio riduce il telefono alle sole cifre per il campo to, quindi un più iniziale o degli spazi non contano. Se altrove i partecipanti scrivono i numeri a mano, normalizzali come mostrato in normalizzazione dei numeri di telefono E.164.
Iscrivi il webhook
Crea l’iscrizione con POST /v2/webhooks (creare un webhook, consultato il 2026-11-25). Il body richiede subscriberUrl, active e triggers[]. Imposta anche secret, perché il servizio rifiuta le richieste non firmate. Il campo facoltativo version accetta 2021-10-20 o 2026-07-27, che aggiunge il contenuto ICS. customHeaders accetta fino a 10 header.
Iscriviti almeno a BOOKING_CREATED, BOOKING_RESCHEDULED e BOOKING_CANCELLED. I tipi di evento che richiedono la conferma dell’host emettono prima BOOKING_REQUESTED. Non abbiamo verificato se per questi parta anche BOOKING_CREATED, quindi il servizio registra BOOKING_REQUESTED e aspetta. Provalo sulla tua installazione prima di fare affidamento su uno dei due.
Il payload che invia Cal
Ogni consegna ha l’involucro {triggerEvent, createdAt, payload} (guida ai webhook di Cal.com, consultato il 2026-11-25). Queste sono le chiavi del payload che il servizio legge:
| Chiave | Cosa contiene |
|---|---|
uid |
L’ID univoco della prenotazione, usato in ogni chiamata alla API v2 |
startTime, endTime |
Orari ISO in UTC |
title, status |
Titolo e stato dell’evento, per esempio ACCEPTED |
attendees[] |
name, email, timeZone, language e altro |
responses.attendeePhoneNumber.value |
Il telefono, una volta reso visibile il campo |
responses.<your question>.value |
La tua casella di consenso |
rescheduleUid |
In caso di spostamento: l’uid della prenotazione precedente |
cancellationReason |
In caso di annullamento |
Ogni voce di responses contiene label, value e isHidden. In uno spostamento, uid è la nuova prenotazione, e rescheduleUid punta a quella vecchia, insieme a rescheduleId, rescheduleStartTime e rescheduleEndTime. attendees[].phoneNumber compare in alcuni payload, ma negli esempi è null, quindi leggi invece responses.
Verifica la firma e considera sconosciuti i nuovi tentativi
Cal firma il body grezzo con HMAC-SHA256 e invia il digest esadecimale in X-Cal-Signature-256. Il sorgente di Cal.diy calcola createHmac("sha256", params.secret).update(`${params.body}`).digest("hex") e lo invia con X-Cal-Webhook-Version (sendPayload.ts, consultato il 2026-11-25). Non viene firmato alcun timestamp, quindi la firma non protegge dai replay. Deduplica dalla tua parte.
Senza un secret, l’header contiene la stringa letterale no-secret-provided, che il servizio rifiuta. Se un payloadTemplate personalizzato non è JSON valido, il content type diventa application/x-www-form-urlencoded. E la richiesta è un solo fetch con redirect: "manual", quindi un 3xx non viene seguito. Dai a Cal l’URL HTTPS definitivo, mai uno che fa redirect.
Quel file non ha nuovi tentativi né timeout. La pagina di guida dice «La consegna può essere ritentata e arrivare più di una volta o fuori ordine», ma solo per gli eventi di registrazione. Cal non documenta alcuna politica di nuovi tentativi per i webhook delle prenotazioni. Il servizio risponde subito 200, deduplica su triggerEvent più uid e fa il lavoro dopo la risposta.
Il lato WhatsApp usa uno schema diverso, X-Hub-Signature-256 con il prefisso sha256= e il tuo app secret. Verificare X-Hub-Signature-256 sui webhook WhatsApp spiega perché entrambi i controlli devono girare sui byte grezzi.
Due modelli e tre pulsanti
Entrambi i messaggi sono modelli utility. Sono legati a una prenotazione fatta dal partecipante e non contengono promozioni, che è il test descritto nell’articolo principale sui promemoria. Creali con la stessa chiamata message_templates mostrata lì.
| Modello | Corpo | Pulsanti | TTL |
|---|---|---|---|
booking_confirmed |
Hi {{customer_name}}, your {{event}} is booked for {{date}} at {{time}}. Reply here if you need to change it. | Nessuno | Default |
booking_reminder_24h |
Hi {{customer_name}}, a reminder that your {{event}} is on {{date}} at {{time}}. Please confirm, reschedule or cancel below. | Risposte rapide Confirm, Reschedule, Cancel | 43.200 secondi |
Per cliniche e altri servizi sanitari, riempi {{event}} con una parola neutra come “appointment”, perché il titolo di un evento Cal può nominare un trattamento.
Per la conferma, il modello di Meta per gli appuntamenti è un’alternativa quando vuoi un pannello “View details” con un link di gestione. Non può portare risposte rapide, quindi non può essere il promemoria. L’articolo principale ne elenca i campi. La chiamata di creazione e i parametri di invio sono trattati per intero in la guida al modello per gli appuntamenti.
Il servizio
Questo file gira così com’è su Node 18 o successivo con Express 4. Tiene lo stato in memoria per poterlo provare. Le due route webhook verificano ciascuna la propria firma, e il job dei promemoria gira ogni minuto.
// cal-whatsapp.js: Cal.com or Cal.diy bookings to WhatsApp confirmation, reminder and replies.
// Node 18+ and Express 4. Run: npm install express && node cal-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 CAL_WEBHOOK_SECRET = env("CAL_WEBHOOK_SECRET");
const CAL_API_KEY = env("CAL_API_KEY"); // cal_live_... or cal_... for test
const CAL_API_BASE = env("CAL_API_BASE", "https://api.cal.com/v2"); // Cal.diy: your own deployment
const CAL_EVENT_TYPE_ID = env("CAL_EVENT_TYPE_ID"); // the event type to offer slots from
const CONSENT_FIELD = env("CONSENT_FIELD", "whatsappConsent"); // your checkbox question
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 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(); // Cal booking uid -> local booking
const ownReschedules = new Set(); // old uids we rescheduled from WhatsApp
const seenCal = new Set(); // triggerEvent:uid already processed
const seenWa = new Set(); // inbound wamids already processed
const digits = (phone) => String(phone || "").replace(/\D/g, "");
function safeEqual(a, b) {
const x = Buffer.from(a);
const y = Buffer.from(b);
return x.length === y.length && crypto.timingSafeEqual(x, y);
}
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 cal(method, path, version, body) {
const res = await fetch(CAL_API_BASE + path, {
method,
headers: {
Authorization: `Bearer ${CAL_API_KEY}`,
"cal-api-version": version,
...(body ? { "Content-Type": "application/json" } : {}),
},
body: body ? JSON.stringify(body) : undefined,
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
const err = new Error(`Cal ${method} ${path} returned ${res.status}: ${JSON.stringify(data)}`);
err.status = res.status;
throw err;
}
return data;
}
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) };
}
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 } });
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", "reschedule", "cancel"].forEach((action, index) => components.push({
type: "button",
sub_type: "quick_reply",
index: String(index),
parameters: [{ type: "payload", payload: `cal|${booking.uid}|${action}` }],
}));
}
return { to: booking.phone, type: "template", template: { name, language: { code: "en_US" }, components } };
}
function fromPayload(p) {
const attendee = (p.attendees || [])[0] || {};
return {
uid: p.uid,
title: p.title || "appointment",
name: attendee.name || p.responses?.name?.value || "there",
phone: digits(p.responses?.attendeePhoneNumber?.value),
consent: p.responses?.[CONSENT_FIELD]?.value === true,
startTime: p.startTime,
timeZone: attendee.timeZone || "UTC",
createdAt: Date.now(),
status: "booked", // booked | confirmed | reschedule_requested | cancelled
reminder: null, // null | "sending" | "skipped" | "failed" | wamid
};
}
function moveBooking(oldUid, newUid, startTime) {
if (bookings.has(newUid)) return bookings.get(newUid); // already moved
const old = bookings.get(oldUid);
if (!old) return null;
bookings.delete(oldUid);
const moved = { ...old, uid: newUid, startTime, status: "booked", reminder: null, createdAt: Date.now() };
bookings.set(newUid, moved);
return moved;
}
const canMessage = (booking) => Boolean(booking.phone && booking.consent);
async function onCalEvent(triggerEvent, p) {
if (triggerEvent === "BOOKING_CREATED") {
const booking = fromPayload(p);
bookings.set(booking.uid, booking);
if (canMessage(booking)) await sendWhatsApp(templateMessage(booking, "booking_confirmed", false));
return;
}
if (triggerEvent === "BOOKING_RESCHEDULED") {
const ours = ownReschedules.has(p.rescheduleUid); // we already confirmed it in the chat
let booking = moveBooking(p.rescheduleUid, p.uid, p.startTime);
if (!booking) {
booking = fromPayload(p);
bookings.set(booking.uid, booking);
}
if (ours) booking.status = "confirmed"; // the attendee picked this time in the chat
else if (canMessage(booking)) await sendWhatsApp(templateMessage(booking, "booking_confirmed", false));
return;
}
if (triggerEvent === "BOOKING_CANCELLED") {
const booking = bookings.get(p.uid);
if (booking) booking.status = "cancelled"; // stops the reminder
return;
}
console.log("not handled", triggerEvent, p.uid); // BOOKING_REQUESTED and others
}
async function runReminders() {
const now = Date.now();
for (const booking of bookings.values()) {
if (booking.reminder || !canMessage(booking) || booking.status === "cancelled") 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";
try {
booking.reminder = await sendWhatsApp(templateMessage(booking, "booking_reminder_24h", true));
} catch (err) {
booking.reminder = "failed";
console.error("reminder failed", booking.uid, err.message);
}
}
}
async function offerSlots(booking) {
const query = new URLSearchParams({
eventTypeId: CAL_EVENT_TYPE_ID,
start: new Date().toISOString(),
end: new Date(Date.now() + 7 * 24 * HOUR).toISOString(),
timeZone: booking.timeZone,
});
const { data = {} } = await cal("GET", `/slots?${query}`, "2024-09-04");
const rows = Object.values(data).flat().slice(0, 10).map((slot) => ({
id: `slot|${booking.uid}|${slot.start}`,
title: formatWhen(slot.start, booking.timeZone).short.slice(0, 24),
}));
if (rows.length === 0) {
booking.status = "booked";
return sendText(booking.phone, "There are no open times in the next 7 days. Reply here and a person will help.");
}
return sendWhatsApp({
to: booking.phone,
type: "interactive",
interactive: {
type: "list",
body: { text: "Pick a new time for your booking:" },
action: { button: "See times", sections: [{ title: "Open times", rows }] },
},
});
}
async function onTap(booking, action) {
if (booking.status === "cancelled") return sendText(booking.phone, "This booking is already cancelled.");
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;
booking.status = "confirmed"; // Cal has no attendee confirm endpoint: this table is the record
return sendText(booking.phone, `Thanks, ${booking.name}. You are confirmed for ${when.date} at ${when.time}.`);
}
if (action === "cancel") {
booking.status = "cancelled"; // set first so a second tap does nothing
try {
await cal("POST", `/bookings/${booking.uid}/cancel`, "2026-02-25", {
cancellationReason: "Cancelled by the attendee on WhatsApp",
});
} catch (err) {
booking.status = "booked";
console.error(err.message);
return sendText(booking.phone, "We could not cancel this booking. A person on our team will follow up.");
}
return sendText(booking.phone, "Your booking is cancelled.");
}
if (action === "reschedule") {
if (booking.status === "reschedule_requested") return;
booking.status = "reschedule_requested";
try {
return await offerSlots(booking);
} catch (err) {
booking.status = "booked";
console.error(err.message);
return sendText(booking.phone, "We could not load open times. A person on our team will follow up.");
}
}
}
async function onSlot(booking, start) {
if (booking.status !== "reschedule_requested" || Number.isNaN(Date.parse(start))) return;
ownReschedules.add(booking.uid);
let result;
try {
result = await cal("POST", `/bookings/${booking.uid}/reschedule`, "2026-02-25", {
start,
reschedulingReason: "Requested by the attendee on WhatsApp",
});
} catch (err) {
ownReschedules.delete(booking.uid);
booking.status = "booked";
console.error(err.message);
return sendText(booking.phone, "We could not move your booking. A person on our team will follow up.");
}
const d = result.data || {};
const newUid = d.rescheduledToUid || (d.rescheduledFromUid ? d.uid : null);
// Without a new uid in the response, the BOOKING_RESCHEDULED webhook moves the booking.
const moved = newUid ? moveBooking(booking.uid, newUid, start) : booking;
moved.status = "confirmed";
const when = formatWhen(start, moved.timeZone);
return sendText(moved.phone, `Done. Your new time is ${when.date} at ${when.time}.`);
}
async function onWhatsAppMessage(msg) {
if (msg.type === "button") {
const [prefix, uid, action] = String(msg.button?.payload || "").split("|");
const fromContext = [...bookings.values()].find((b) => b.reminder === msg.context?.id);
const booking = prefix === "cal" ? bookings.get(uid) : fromContext;
const act = prefix === "cal" ? action : { Confirm: "confirm", Reschedule: "reschedule", Cancel: "cancel" }[msg.button?.text];
if (booking && act) return onTap(booking, act);
return console.warn("unmatched tap", msg.id); // for example a reminder for a time that has since moved
}
if (msg.type === "interactive" && msg.interactive?.type === "list_reply") {
const [prefix, uid, start] = String(msg.interactive.list_reply?.id || "").split("|");
const booking = bookings.get(uid);
if (prefix === "slot" && booking) return onSlot(booking, start);
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.consent = false;
return sendText(msg.from, "You will not get booking messages here anymore.");
}
}
const app = express();
app.post("/cal/webhook", express.raw({ type: "*/*" }), (req, res) => {
const header = req.get("X-Cal-Signature-256") || "";
if (!Buffer.isBuffer(req.body) || header === "no-secret-provided") return res.sendStatus(401);
const expected = crypto.createHmac("sha256", CAL_WEBHOOK_SECRET).update(req.body).digest("hex");
if (!safeEqual(header, expected)) return res.sendStatus(401);
let event;
try {
event = JSON.parse(req.body.toString("utf8"));
} catch {
return res.sendStatus(400);
}
res.sendStatus(200); // answer first, work after
const key = `${event.triggerEvent}:${event.payload?.uid}`;
if (seenCal.has(key)) return;
seenCal.add(key);
onCalEvent(event.triggerEvent, event.payload || {}).catch((err) => console.error("cal 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 Cal senza una prenotazione reale, firma tu stesso un body con lo stesso secret. Il servizio risponde 200, poi prova a inviare booking_confirmed, che richiede il modello approvato e un numero WhatsApp che accetti messaggi di prova.
BODY='{"triggerEvent":"BOOKING_CREATED","createdAt":"2026-11-25T12:00:00.000Z","payload":{"uid":"test-uid-1","title":"Consultation","startTime":"2026-11-28T15:00:00.000Z","endTime":"2026-11-28T15:30:00.000Z","attendees":[{"name":"Marina","timeZone":"America/New_York"}],"responses":{"attendeePhoneNumber":{"label":"Phone","value":"+16505551234","isHidden":false},"whatsappConsent":{"label":"WhatsApp","value":true,"isHidden":false}}}}'
SIG=$(printf '%s' "$BODY" | openssl dgst -sha256 -hmac "$CAL_WEBHOOK_SECRET" | awk '{print $NF}')
curl -i -X POST http://localhost:3000/cal/webhook \
-H "Content-Type: application/json" \
-H "X-Cal-Signature-256: $SIG" \
--data-binary "$BODY"
Riporta la risposta su Cal.com
Ogni endpoint delle prenotazioni avverte che cal-api-version «deve essere impostato su 2026-02-25». Altri valori ripiegano su una versione più vecchia dell’endpoint. L’endpoint degli slot fa eccezione: richiede 2024-09-04. L’autenticazione è Authorization: Bearer con una chiave cal_live_, o una chiave di prova cal_.
| Tocco | Chiamata | cal-api-version |
Body |
|---|---|---|---|
| Cancel | POST /v2/bookings/{bookingUid}/cancel |
2026-02-25 |
cancellationReason |
| Reschedule, passo 1 | GET /v2/slots?eventTypeId=&start=&end=&timeZone= |
2024-09-04 |
Nessuno |
| Reschedule, passo 2 | POST /v2/bookings/{bookingUid}/reschedule |
2026-02-25 |
start (obbligatorio), reschedulingReason |
| Confirm | Nessuna in Cal: salvalo nella tua tabella | n/d | n/d |
Fonti: pagine di riferimento della API v2 di Cal.com per cancel, slots e reschedule, consultate il 2026-11-25.
Cancel restituisce {status: "success", data: {...}}. Reschedule restituisce 201, con rescheduledFromUid e rescheduledToUid che collegano le due prenotazioni. Le prenotazioni cancelled, rejected o awaiting_host restituiscono 400, e una prenotazione pending resta in sospeso dopo lo spostamento. Gli slot tornano come data con chiave la data, ciascuno con oggetti che hanno start, oppure {} quando non c’è nulla di libero. Schema ed esempio di quella pagina non coincidono del tutto, quindi registra una risposta reale prima di fidarti del parser. Il servizio offre al massimo 10 slot, il limite di righe di una lista WhatsApp, elencato con gli altri limiti in pulsanti interattivi e messaggi a lista.
POST /v2/bookings/{uid}/confirm esiste, ma è l’host che accetta una prenotazione in sospeso, non il partecipante che conferma la presenza (confermare una prenotazione, consultato il 2026-11-25). Non abbiamo trovato nemmeno un endpoint per scrivere i metadati della prenotazione. Tieni la conferma del partecipante nella tua tabella. Se in seguito segni le assenze, l’header di versione dell’endpoint mark-absent è documentato come 2024-08-13, mentre una pagina di terze parti dice 2026-02-25, quindi provalo.
Un’alternativa alla lista di slot è POST /v2/bookings/{bookingUid}/request-reschedule. La pagina di Cal dice: «La prenotazione verrà annullata e il partecipante riceverà un’email con un link per riprogrammare.» Così la conversazione si sposta sull’email e la prenotazione viene prima annullata, quindi il servizio non lo usa.
La API consente 120 richieste al minuto per chiave, aumentabili a 200 (introduzione alla API v2, consultato il 2026-11-25). L’URL base https://api.cal.com/v2 viene dagli esempi di Cal. Su Cal.diy, punta CAL_API_BASE alla API v2 della tua installazione.
Quando il ciclo si rompe
Le tue chiamate tornano come webhook
Un annullamento o uno spostamento fatto da WhatsApp rimanda al tuo endpoint BOOKING_CANCELLED o BOOKING_RESCHEDULED. Senza un controllo, il cliente riceve una seconda conferma per una modifica che ha fatto un minuto prima. Il servizio registra il vecchio uid in ownReschedules prima della chiamata e resta in silenzio quando il webhook lo nomina. Un annullamento non invia proprio nulla dal percorso del webhook.
La prenotazione passa a un nuovo uid
In uno spostamento, lo stato del promemoria deve seguire il nuovo uid. moveBooking copia la riga locale sulla nuova chiave, azzera il promemoria e rende la chiamata idempotente. Chi arriva prima, la risposta della API o il webhook, fa lo spostamento, e il secondo lo trova già fatto. Un tocco su un promemoria inviato per il vecchio orario non corrisponde più a nessuna prenotazione, quindi il servizio lo registra invece di agire sull’appuntamento sbagliato.
Eventi duplicati o fuori ordine
Dato che Cal non firma alcun timestamp e non documenta una politica di nuovi tentativi per le prenotazioni, deduplica su triggerEvent più uid. Un BOOKING_CANCELLED che arriva dopo uno spostamento nomina il vecchio uid, che in locale non esiste più, quindi non fa nulla. Prima della produzione sposta gli insiemi in memoria su un indice univoco.
Nessun telefono, nessun consenso, o STOP
Una prenotazione senza telefono o senza la casella di consenso non riceve alcun messaggio WhatsApp. Una risposta STOP cancella il consenso su tutte le prenotazioni di quel numero. I duplicati in entrata su WhatsApp vengono saltati per id del messaggio, come nell’articolo principale sui promemoria.
Cal.com rifiuta la modifica
Un 400 su uno spostamento di solito significa che la prenotazione è annullata, rifiutata o ancora in attesa dell’host. Il servizio ripristina lo stato e dice al cliente che una persona lo ricontatterà. Instrada questi casi verso una casella reale, perché un errore silenzioso qui lascia il partecipante convinto che lo spostamento sia andato a buon fine.
Dove si colloca Z-API Omni
Omni invia gli stessi due modelli su un canale Meta Cloud API e la lista di slot come lista interattiva su WhatsApp. La sua pagina sull’integrazione con n8n elenca le operazioni Send Template e Send Interactive Button e nessun nodo trigger. Se costruisci questo flusso in n8n invece che in Express, usa il nodo Webhook di n8n sia per gli eventi di Cal sia per i messaggi in arrivo. Il JSON in arrivo di un tocco su un pulsante di un modello non è ancora documentato, quindi prova quel ramo prima di dipenderne.
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. I webhook sono inclusi senza limiti, e le tariffe di Meta vengono riaddebitate sulla connessione ufficiale.
Il team di Z-API Omni