WhatsApp· 9 min read

Calendly webhook to WhatsApp confirmations and reminders


A Calendly webhook subscription tells Calendly to POST a signed JSON event to your URL each time an invitee books or cancels. Subscribe to invitee.created and invitee.canceled with a signing_key, verify Calendly-Webhook-Signature, and send a WhatsApp utility confirmation plus a reminder a day ahead. A Cancel tap goes back through Calendly’s cancellation endpoint. Reschedule can’t, because Calendly has no reschedule endpoint, so that reply carries the invitee’s reschedule_url.

The reminder pattern itself, with TTL, category and delivery tracking, is in WhatsApp appointment reminders with Confirm and Reschedule. The same loop for Cal.com is in Cal.com webhooks to WhatsApp reminders.

The loop from booking to updated event

  1. Calendly posts invitee.created. You verify the signature, store the event and answer 2xx.
  2. If the invitee gave a phone number and WhatsApp consent, you send booking_confirmed.
  3. Your scheduler sends booking_reminder_24h with Confirm, Cancel and Reschedule a day before start_time.
  4. The tap reaches your WhatsApp webhook as a button message.
  5. Confirm is stored in your table, Cancel calls Calendly, and Reschedule answers with the link.

Calendly sends no reminder webhook, so your own job reads scheduled_event.start_time from the stored booking. Zapier’s “Calendly + WhatsApp Notifications” zaps cover the send on new invitees and cancellations (Zapier, accessed 2026-11-27). The listing doesn’t describe writing a reply back into Calendly.

Create the subscription with a signing key

Webhooks don’t need a paid plan. Calendly’s FAQ says “Webhooks are available on all Calendly plans, including the Free plan” (Calendly developer FAQ, accessed 2026-11-27). The help page, updated Nov 4, 2026, also lists “All plans”. Only meeting_recap.* and routing_form_submission.created need a paid account, and they return 403 “Please upgrade to a paid Calendly account.” otherwise.

The token can be a Personal Access Token or OAuth. It needs webhooks:write, plus scheduled_events:read for invitee.* events (create webhook subscription, accessed 2026-11-27). Ask for scheduled_events:write instead of the read scope, because the Cancel tap needs it and a :write scope includes the matching :read. Add users:read for the organization lookup. New PATs “get no API access until scopes are explicitly requested and approved” (scopes, accessed 2026-11-27).

Always send signing_key when you create a subscription with a PAT. Calendly treats it as optional, and without one the requests arrive unsigned. With OAuth, “a webhook signing key will automatically be generated for all webhooks related to your application.” If you lose it, Calendly says to “contact developer support” (webhook signatures, accessed 2026-11-27).

Owners and admins can subscribe at organization or user scope. Other members can use user only. A second subscription with the same URL returns 409 “Hook with this url already exists”, so list before you create.

# 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\"}"

A 201 returns the subscription under resource, including uri, callback_url, state and retry_started_at.

What invitee.created carries

Each delivery has event, created_at, created_by and a payload that describes the invitee. This excerpt is abridged and reformatted from Calendly’s sample, and keeps the fields the service reads (sample webhook data, accessed 2026-11-27).

{
  "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 is the invitee, and its last segment is the service’s booking key. The last segment of scheduled_event.uri is the event UUID that the cancellation endpoint takes. timezone is the “Time zone to use when displaying time to the invitee” (get event invitee, accessed 2026-11-27). invitee.canceled has the same shape, with status: "canceled" and a cancellation object holding canceled_by, canceler_type and reason.

Where the phone number comes from

Calendly has three places that can hold a phone number, and none is guaranteed.

  • text_reminder_number, described as “The phone number to use when sending text (SMS) reminders”. It is set only when the invitee chose SMS reminders.
  • A custom “Phone number” invitee question. It arrives in questions_and_answers[] as {question, answer, position}, and you match it by its exact question text.
  • scheduled_event.location with type: "outbound_call", where location is “the phone number the host will use to call the invitee”.

Calendly doesn’t document the answer format or whether it includes a country code. The service accepts a leading + or 00, and falls back to DEFAULT_COUNTRY_CODE for local numbers. Without either, it skips the message rather than guess. E.164 phone number normalization covers the edge cases.

Calendly has no WhatsApp consent field. text_reminder_number reflects a choice about SMS, so it doesn’t stand in for WhatsApp consent. Add a custom invitee question that names WhatsApp and the purpose, and send only when the answer is yes. The service matches it by its exact text, set in CONSENT_QUESTION. How to collect WhatsApp opt-in covers the wording and the record to keep.

Verify the signature and always answer 2xx

Calendly sends Calendly-Webhook-Signature: t=<unix>,v1=<hex>. The v1 value is an HMAC-SHA256, hex-encoded, over “the timestamp (t), the character ‘.’, and the request body’s JSON payload” (webhook signatures, accessed 2026-11-27). Compute it on the raw body bytes. Calendly’s example rejects webhooks “older than 3 minutes”, so the service uses 180 seconds and makes it configurable.

On any 3xx, 4xx or 5xx, Calendly “will continue to try to deliver for 24 hours” “with an exponential back-off” (webhook errors, accessed 2026-11-27). It also stops “24 hours after the booking of the event passes”. After that, “the webhook is disabled if another message was not delivered successfully”, and “the hook needs to be recreated.”

Returning 400 for a business rejection, such as a booking with no phone, gets that event redelivered for a day and can disable the subscription. The service returns 2xx once the event is verified and stored, and logs the rejection instead.

Calendly allows a 10-second connection timeout and a 15-second read timeout, and asks you to acknowledge “immediately” and process asynchronously (webhook timeouts, accessed 2026-11-27). Calendly documents no delivery or event ID header. The service builds its own dedupe key from event, payload.uri and created_at. That key is our inference, not a Calendly rule.

A reschedule arrives as two events

When an invitee picks a new time, Calendly fires invitee.canceled with rescheduled: true and a new invitee.created (reschedule payloads, accessed 2026-11-27). The invitees reference each other through old_invitee and new_invitee. The order of the two deliveries isn’t documented.

Never send “cancelled” for the first half of a reschedule. The service keys on the rescheduled flag. An invitee.canceled with rescheduled: true marks the old row moved and sends nothing. An invitee.created with an old_invitee marks the old row moved too and sends booking_moved with the new time. Either order ends in the same state.

Your own cancellations come back as well. A cancel through the API fires invitee.canceled with canceler_type: "host". The service sets the row to cancel_requested before the call, so that webhook stays silent instead of sending a second notice.

Four utility templates

All four are utility templates. Each is about a meeting the invitee booked, which meets Meta’s test as explained in the reminder pillar. A promotion added to any of them makes it marketing.

Template Body Buttons TTL
booking_confirmed Hi {{customer_name}}, your {{event}} is booked for {{date}} at {{time}}. Reply here if you have a question. None Default
booking_moved Hi {{customer_name}}, your {{event}} has moved to {{date}} at {{time}}. None Default
booking_cancelled Hi {{customer_name}}, your {{event}} on {{date}} at {{time}} is cancelled. None Default
booking_reminder_24h Hi {{customer_name}}, a reminder that your {{event}} is on {{date}} at {{time}}. Please confirm, cancel or reschedule below. Quick replies Confirm, Cancel, Reschedule 43,200 seconds

Create them with the message_templates call in the reminder pillar, which also explains message_send_ttl_seconds. A Calendly event name can describe a treatment, so clinics should fill {{event}} with a neutral word such as “appointment”.

For the confirmation, Meta’s booking appointment template is an alternative with a “View details” sheet and a manage link. A reschedule_url looks like https://calendly.com/reschedulings/<id>, so a booking_management_url of https://calendly.com/reschedulings/{{1}} with the ID as suffix fits Meta’s one-parameter-at-the-end rule. That fit is our inference, so test it. The booking appointment template post has the fields.

The Calendly-to-WhatsApp service

This file runs as pasted on Node 18 or later with Express 4. It keeps state in memory so you can try it, and the reminder job runs every minute.

// 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}`));

To try the Calendly route without a real booking, sign a body with your own key and the current time. The service answers 200, then tries to send booking_confirmed, which needs the approved template and a number that accepts test messages.

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"

Write the tap back to Calendly

Tap What the service does Calendly call
Confirm Marks the row confirmed in your table None
Cancel Cancels the event POST /scheduled_events/{uuid}/cancellation with scope scheduled_events:write
Cancel, group event Sends the invitee’s cancel_url None
Reschedule Sends the invitee’s reschedule_url as a CTA URL button None: no endpoint exists

The cancellation body is optional, for example {"reason": "Something came up."}. A 201 returns canceled_by, reason, canceler_type and created_at (cancel event, accessed 2026-11-27). Errors share 403 Permission Denied, with the messages “You are not allowed to cancel this event”, “Event in the past” or “Event is already canceled”. So the service branches on the message and treats “already canceled” as success.

The FAQ says the endpoint cancels “an event, including a Group event, but not an individual invitee.” Calling it for one person in a group session would cancel everyone. List your group event type URIs in GROUP_EVENT_TYPES, and the service sends cancel_url for those instead.

For rescheduling, the FAQ is direct: “At this time, there is no API endpoint that supports rescheduling an event or invitee.” The Scheduling API’s POST https://api.calendly.com/invitees can book a new time. Cancel plus create isn’t atomic, and paid event types can’t be booked through it. It allows 5 per user per day on Free and Trial and 100 per day on paid plans below Enterprise (rate limits, accessed 2026-11-27).

The reply to a tap is free-form, because the tap opened a 24-hour window. Those replies are service messages, priced as described in Meta’s service message charges from October 2026.

When the loop breaks

Calendly disables the subscription

A wrong signing key in your environment makes the service reject every real delivery with 401. Calendly keeps retrying for 24 hours, then disables the hook. Check state on the list endpoint from a daily job, and recreate the subscription if it reads disabled. Calendly’s pages don’t describe a replay after you recreate it, so compare your table against the events you expect.

The same event arrives twice

The event, payload.uri and created_at key catches a retry, and the booking map catches a second invitee.created for the same invitee. Move both to a table with a unique key before production, or a restart forgets them.

A booking with no usable number or no yes to the consent question gets no WhatsApp message, and the webhook still returns 200. A reply of STOP clears consent on every booking for that number. Record the opt-out where you read consent, so a later booking doesn’t switch it back on.

The cancellation fails

A network error or an unexpected status leaves the row as it was, and the invitee hears that a person will follow up. Route those logs to someone who can act.

Where Z-API Omni fits

Omni’s custom template docs include an “Appointment reminder” model with Confirm and Reschedule quick replies, and you can add Cancel as a third. You create templates with POST /whatsapp/businesses/{wabaId}/templates, which accepts message_send_ttl_seconds. You send them with POST /v1/channels/{channelId}/messages on Meta Cloud API channels. The docs don’t show the inbound JSON of a template button tap, so test that mapping before you port the handler.

The docs describe no Calendly integration and no scheduler, so the reminder job and the cancellation call stay in your service. Webhooks are signed with x-webhook-signature, as shown in the Node.js quickstart. Each number costs US$29 a month for 1 to 10 numbers, US$26 for 11 to 50, US$23 for 51 to 100 and US$20 above 100. Meta’s fees are passed through on the official connection.

View documentation

Z-API Omni team