# Calendly webhook'undan WhatsApp onaylarına ve hatırlatmalarına

> Calendly-Webhook-Signature'ı doğrulayın, invitee.created ile WhatsApp onayı ve hatırlatması gönderin, Calendly API'siyle iptal edin, linkle yeniden planlatın.

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

Calendly webhook aboneliği, bir davetli her rezervasyon yaptığında veya iptal ettiğinde Calendly'nin URL'nize imzalı bir JSON olayı POST etmesini sağlar. Bir `signing_key` ile `invitee.created` ve `invitee.canceled` olaylarına abone olun, `Calendly-Webhook-Signature` başlığını doğrulayın, ardından bir WhatsApp utility onayı ve bir gün önceden bir hatırlatma gönderin. Cancel dokunuşu Calendly'nin iptal endpoint'i üzerinden geri gider. Reschedule bunu yapamaz, çünkü Calendly'de yeniden planlama endpoint'i yok; bu yüzden o yanıt davetlinin `reschedule_url` değerini taşır.

TTL, kategori ve teslimat takibiyle birlikte hatırlatma kalıbının kendisi [Confirm ve Reschedule butonlu WhatsApp randevu hatırlatmaları](/academy/tr/articles/whatsapp-appointment-reminders-confirm-reschedule/) yazısında. Aynı döngünün Cal.com için hali [Cal.com webhook'larından WhatsApp hatırlatmalarına](/academy/tr/articles/cal-com-webhook-whatsapp-booking-reminders/) yazısında.

## Rezervasyondan güncellenmiş etkinliğe döngü

1. Calendly `invitee.created` gönderir. İmzayı doğrular, olayı saklar ve 2xx ile yanıt verirsiniz.
2. Davetli bir telefon numarası ve WhatsApp onayı verdiyse `booking_confirmed` gönderirsiniz.
3. Zamanlayıcınız `start_time` değerinden bir gün önce Confirm, Cancel ve Reschedule butonlu `booking_reminder_24h` gönderir.
4. Dokunuş WhatsApp webhook'unuza bir `button` mesajı olarak ulaşır.
5. Confirm tablonuza kaydedilir, Cancel Calendly'yi çağırır, Reschedule ise linkle yanıt verir.

Calendly hatırlatma webhook'u göndermez, bu yüzden kendi işiniz saklanan rezervasyondan `scheduled_event.start_time` değerini okur. Zapier'in "Calendly + WhatsApp Notifications" zap'leri yeni davetlilerde ve iptallerde gönderimi karşılar ([Zapier](https://zapier.com/apps/calendly/integrations/whatsapp-notifications), erişim tarihi 2026-11-27). Listeleme, bir yanıtı Calendly'ye geri yazmayı anlatmıyor.

## Aboneliği bir imzalama anahtarıyla oluşturun

Webhook'lar ücretli plan gerektirmez. Calendly'nin SSS sayfası "Webhook'lar, Free plan dahil tüm Calendly planlarında kullanılabilir" der ([Calendly developer FAQ](https://developer.calendly.com/docs/getting-started/frequently-asked-questions.md), erişim tarihi 2026-11-27). 4 Kasım 2026'da güncellenen yardım sayfası da "All plans" (tüm planlar) yazar. Yalnızca `meeting_recap.*` ve `routing_form_submission.created` ücretli hesap ister; aksi halde `403` "Please upgrade to a paid Calendly account." döner.

Token bir Personal Access Token veya OAuth olabilir. `webhooks:write` ve `invitee.*` olayları için `scheduled_events:read` gerekir ([create webhook subscription](https://developer.calendly.com/api-docs/calendly-api/webhooks/create-webhook-subscription.md), erişim tarihi 2026-11-27). Okuma kapsamı yerine `scheduled_events:write` isteyin, çünkü Cancel dokunuşu buna ihtiyaç duyar ve bir `:write` kapsamı eşleşen `:read` kapsamını içerir. Organizasyon sorgusu için `users:read` ekleyin. Yeni PAT'ler "kapsamlar açıkça istenip onaylanana kadar API erişimi almaz" ([scopes](https://developer.calendly.com/docs/authentication/scopes.md), erişim tarihi 2026-11-27).

PAT ile abonelik oluştururken `signing_key` değerini her zaman gönderin. Calendly bunu isteğe bağlı sayar ve anahtar olmadan istekler imzasız gelir. OAuth ile "uygulamanızla ilgili tüm webhook'lar için otomatik olarak bir webhook imzalama anahtarı oluşturulur." Anahtarı kaybederseniz Calendly "geliştirici desteğiyle iletişime geçin" der ([webhook signatures](https://developer.calendly.com/api-docs/overview/webhooks/webhook-signatures), erişim tarihi 2026-11-27).

Owner ve admin rolleri `organization` veya `user` kapsamında abone olabilir. Diğer üyeler yalnızca `user` kullanabilir. Aynı URL ile ikinci bir abonelik `409` "Hook with this url already exists" döner, bu yüzden oluşturmadan önce listeleyin.

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

Bir `201` yanıtı, aboneliği `resource` altında `uri`, `callback_url`, `state` ve `retry_started_at` ile birlikte döner.

## invitee.created neler taşır

Her teslimatta `event`, `created_at`, `created_by` ve davetliyi anlatan bir `payload` bulunur. Bu alıntı Calendly'nin örneğinden kısaltılıp yeniden biçimlendirildi ve servisin okuduğu alanları korur ([sample webhook data](https://developer.calendly.com/api-docs/calendly-api/webhooks/get-sample-webhook-data.md), erişim tarihi 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` davetlidir ve son parçası servisin rezervasyon anahtarıdır. `scheduled_event.uri` değerinin son parçası, iptal endpoint'inin aldığı etkinlik UUID'sidir. `timezone`, "saati davetliye gösterirken kullanılacak saat dilimi"dir ([get event invitee](https://developer.calendly.com/api-docs/calendly-api/scheduled-events/get-event-invitee.md), erişim tarihi 2026-11-27). `invitee.canceled` aynı biçimdedir; `status: "canceled"` ve `canceled_by`, `canceler_type` ile `reason` içeren bir `cancellation` nesnesi taşır.

### Telefon numarası nereden gelir

Calendly'de telefon numarası tutabilen üç yer var ve hiçbiri garanti değil.

- `text_reminder_number`, "metin (SMS) hatırlatmaları gönderirken kullanılacak telefon numarası" olarak tanımlanır. Yalnızca davetli SMS hatırlatmalarını seçtiyse dolar.
- Özel bir "Phone number" (telefon numarası) davetli sorusu. `questions_and_answers[]` içinde `{question, answer, position}` olarak gelir ve onu tam soru metniyle eşleştirirsiniz.
- `type: "outbound_call"` olan `scheduled_event.location`; burada `location`, "ev sahibinin davetliyi aramak için kullanacağı telefon numarası"dır.

Calendly yanıt biçimini veya ülke kodu içerip içermediğini belgelemiyor. Servis başta `+` veya `00` kabul eder ve yerel numaralar için `DEFAULT_COUNTRY_CODE` değerine döner. İkisi de yoksa tahmin yürütmek yerine mesajı atlar. Uç durumlar [E.164 telefon numarası normalleştirme](/academy/tr/articles/whatsapp-phone-number-format-e164-normalization/) yazısında.

### WhatsApp onayı sizin sorunuzdur

Calendly'de WhatsApp onayı alanı yok. `text_reminder_number` SMS ile ilgili bir seçimi yansıtır, yani WhatsApp onayı yerine geçmez. WhatsApp'ı ve amacı adıyla anan özel bir davetli sorusu ekleyin ve yalnızca yanıt evet olduğunda gönderin. Servis soruyu `CONSENT_QUESTION` içinde ayarlanan tam metniyle eşleştirir. Metin ve saklanacak kayıt [WhatsApp opt-in nasıl toplanır](/academy/tr/articles/whatsapp-opt-in-how-to-collect-consent/) yazısında.

## İmzayı doğrulayın ve her zaman 2xx ile yanıt verin

Calendly `Calendly-Webhook-Signature: t=<unix>,v1=<hex>` gönderir. `v1` değeri, "zaman damgası (t), '.' karakteri ve isteğin gövdesindeki JSON payload" üzerinden hesaplanmış, hex kodlu bir HMAC-SHA256'dır ([webhook signatures](https://developer.calendly.com/api-docs/overview/webhooks/webhook-signatures), erişim tarihi 2026-11-27). Bunu ham gövde baytları üzerinde hesaplayın. Calendly'nin örneği "3 dakikadan eski" webhook'ları reddeder, bu yüzden servis 180 saniye kullanır ve bunu ayarlanabilir yapar.

Herhangi bir 3xx, 4xx veya 5xx yanıtında Calendly "üstel geri çekilmeyle" "24 saat boyunca teslim etmeye çalışmaya devam eder" ([webhook errors](https://developer.calendly.com/api-docs/overview/webhooks/webhook-errors.md), erişim tarihi 2026-11-27). Ayrıca "etkinlik rezervasyonunun üzerinden 24 saat geçtikten sonra" durur. Bundan sonra "başka bir mesaj başarıyla teslim edilmediyse webhook devre dışı bırakılır" ve "hook'un yeniden oluşturulması gerekir."

Telefonsuz bir rezervasyon gibi bir iş kuralı reddi için 400 dönmek, o olayın bir gün boyunca yeniden teslim edilmesine yol açar ve aboneliği devre dışı bırakabilir. Servis olay doğrulanıp saklandıktan sonra 2xx döner ve reddi bunun yerine log'a yazar.

Calendly 10 saniyelik bağlantı ve 15 saniyelik okuma zaman aşımı tanır; teslimatı "hemen" onaylamanızı ve işi asenkron yapmanızı ister ([webhook timeouts](https://developer.calendly.com/api-docs/overview/webhooks/webhook-timeouts.md), erişim tarihi 2026-11-27). Calendly bir teslimat veya olay ID başlığı belgelemiyor. Servis kendi tekilleştirme anahtarını `event`, `payload.uri` ve `created_at` değerlerinden kurar. Bu anahtar bir Calendly kuralı değil, bizim çıkarımımız.

## Yeniden planlama iki olay olarak gelir

Davetli yeni bir saat seçtiğinde Calendly `rescheduled: true` ile bir `invitee.canceled` ve yeni bir `invitee.created` tetikler ([reschedule payloads](https://developer.calendly.com/docs/api-guides/see-how-webhook-payloads-change-when-invitees-reschedule-events.md), erişim tarihi 2026-11-27). Davetliler birbirine `old_invitee` ve `new_invitee` üzerinden başvurur. İki teslimatın sırası belgelenmemiş.

Yeniden planlamanın ilk yarısı için asla "iptal edildi" göndermeyin. Servis `rescheduled` bayrağına bakar. `rescheduled: true` olan bir `invitee.canceled` eski satırı `moved` olarak işaretler ve hiçbir şey göndermez. `old_invitee` içeren bir `invitee.created` da eski satırı `moved` olarak işaretler ve yeni saatle `booking_moved` gönderir. Sıra ne olursa olsun sonuç aynı durumdur.

Kendi iptalleriniz de geri gelir. API üzerinden yapılan bir iptal `canceler_type: "host"` ile `invitee.canceled` tetikler. Servis çağrıdan önce satırı `cancel_requested` yapar; böylece o webhook ikinci bir bildirim göndermek yerine sessiz kalır.

## Dört utility şablonu

Dördü de utility şablonudur. Her biri davetlinin aldığı bir toplantıyla ilgilidir ve bu, [hatırlatma ana yazısında](/academy/tr/articles/whatsapp-appointment-reminders-confirm-reschedule/) anlatıldığı gibi Meta'nın testini geçer. Herhangi birine eklenen bir promosyon onu pazarlama yapar.

| Şablon | Gövde | Butonlar | TTL |
| --- | --- | --- | --- |
| `booking_confirmed` | Hi {{customer_name}}, your {{event}} is booked for {{date}} at {{time}}. Reply here if you have a question. | Yok | Varsayılan |
| `booking_moved` | Hi {{customer_name}}, your {{event}} has moved to {{date}} at {{time}}. | Yok | Varsayılan |
| `booking_cancelled` | Hi {{customer_name}}, your {{event}} on {{date}} at {{time}} is cancelled. | Yok | Varsayılan |
| `booking_reminder_24h` | Hi {{customer_name}}, a reminder that your {{event}} is on {{date}} at {{time}}. Please confirm, cancel or reschedule below. | Confirm, Cancel, Reschedule hızlı yanıtları | 43.200 saniye |

Şablonları, `message_send_ttl_seconds` değerini de açıklayan [hatırlatma ana yazısındaki](/academy/tr/articles/whatsapp-appointment-reminders-confirm-reschedule/) `message_templates` çağrısıyla oluşturun. Bir Calendly etkinlik adı bir tedaviyi tarif edebilir, bu yüzden klinikler `{{event}}` değişkenini "appointment" (randevu) gibi nötr bir kelimeyle doldurmalı.

Onay için Meta'nın randevu rezervasyon şablonu, bir "View details" (Ayrıntıları görüntüle) sayfası ve bir yönetim linki sunan alternatiftir. Bir `reschedule_url` `https://calendly.com/reschedulings/<id>` biçimindedir; bu yüzden ID'nin sonek olduğu `https://calendly.com/reschedulings/{{1}}` şeklinde bir `booking_management_url`, Meta'nın "tek parametre, URL'nin sonunda" kuralına uyar. Bu uyum bizim çıkarımımız, o yüzden test edin. Alanlar [randevu rezervasyon şablonu yazısında](/academy/tr/articles/whatsapp-booking-appointment-template-manage-link/).

## Calendly'den WhatsApp'a servis

Bu dosya Node 18 veya üzeri ve Express 4 ile yapıştırıldığı haliyle çalışır. Deneyebilmeniz için durumu bellekte tutar ve hatırlatma işi her dakika çalışır.

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

Calendly yolunu gerçek bir rezervasyon olmadan denemek için bir gövdeyi kendi anahtarınız ve şu anki zamanla imzalayın. Servis 200 ile yanıt verir, ardından `booking_confirmed` göndermeye çalışır; bunun için onaylanmış şablon ve test mesajı kabul eden bir numara gerekir.

```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"
```

## Dokunuşu Calendly'ye geri yazın

| Dokunuş | Servis ne yapar | Calendly çağrısı |
| --- | --- | --- |
| Confirm | Tablonuzda satırı `confirmed` olarak işaretler | Yok |
| Cancel | Etkinliği iptal eder | `scheduled_events:write` kapsamıyla `POST /scheduled_events/{uuid}/cancellation` |
| Cancel, grup etkinliği | Davetlinin `cancel_url` değerini gönderir | Yok |
| Reschedule | Davetlinin `reschedule_url` değerini bir CTA URL butonu olarak gönderir | Yok: böyle bir endpoint yok |

İptal gövdesi isteğe bağlıdır, örneğin `{"reason": "Something came up."}`. Bir `201` yanıtı `canceled_by`, `reason`, `canceler_type` ve `created_at` döner ([cancel event](https://developer.calendly.com/api-docs/calendly-api/scheduled-events/create-scheduled-event-cancellation.md), erişim tarihi 2026-11-27). Hatalar ortak olarak `403 Permission Denied` döner; mesajlar "You are not allowed to cancel this event", "Event in the past" veya "Event is already canceled" olur. Bu yüzden servis mesaja göre dallanır ve "already canceled" durumunu başarı sayar.

SSS, endpoint'in "Grup etkinliği dahil bir etkinliği iptal ettiğini, ama tek bir davetliyi iptal etmediğini" söyler. Bir grup oturumundaki tek bir kişi için onu çağırmak herkesi iptal eder. Grup etkinlik türü URI'lerinizi `GROUP_EVENT_TYPES` içinde listeleyin; servis bunlar için `cancel_url` gönderir.

Yeniden planlama konusunda SSS açıktır: "Şu anda bir etkinliği veya davetliyi yeniden planlamayı destekleyen bir API endpoint'i yoktur." Scheduling API'nin `POST https://api.calendly.com/invitees` çağrısı yeni bir saat rezerve edebilir. İptal artı oluşturma atomik değildir ve ücretli etkinlik türleri bu yolla rezerve edilemez. Free ve Trial planlarında kullanıcı başına günde 5, Enterprise altındaki ücretli planlarda günde 100 çağrıya izin verir ([rate limits](https://developer.calendly.com/api-docs/overview/rate-limits.md), erişim tarihi 2026-11-27).

Bir dokunuşa verilen yanıt serbest metindir, çünkü dokunuş 24 saatlik pencereyi açmıştır. Bu yanıtlar servis mesajıdır ve [Meta'nın Ekim 2026'dan itibaren servis mesajı ücretleri](/academy/tr/articles/meta-whatsapp-service-message-charges-october-2026/) yazısında anlatıldığı gibi fiyatlandırılır.

## Döngü bozulduğunda

### Calendly aboneliği devre dışı bırakır

Ortamınızdaki yanlış bir imzalama anahtarı, servisin her gerçek teslimatı 401 ile reddetmesine yol açar. Calendly 24 saat boyunca yeniden dener, sonra hook'u devre dışı bırakır. Günlük bir işle liste endpoint'indeki `state` değerini kontrol edin ve `disabled` görünüyorsa aboneliği yeniden oluşturun. Calendly'nin sayfaları yeniden oluşturduktan sonra bir tekrar gönderimden bahsetmiyor, bu yüzden tablonuzu beklediğiniz olaylarla karşılaştırın.

### Aynı olay iki kez gelir

`event`, `payload.uri` ve `created_at` anahtarı bir yeniden denemeyi yakalar; rezervasyon haritası da aynı davetli için ikinci bir `invitee.created` olayını yakalar. Üretimden önce ikisini de benzersiz anahtarlı bir tabloya taşıyın, yoksa yeniden başlatma onları unutur.

### Telefon yok, onay yok veya STOP

Kullanılabilir numarası olmayan ya da onay sorusuna evet demeyen bir rezervasyon WhatsApp mesajı almaz ve webhook yine de 200 döner. STOP yanıtı o numaraya ait her rezervasyonda onayı kaldırır. Opt-out'u onayı okuduğunuz yere kaydedin ki sonraki bir rezervasyon onu yeniden açmasın.

### İptal başarısız olur

Bir ağ hatası veya beklenmeyen bir durum kodu satırı olduğu gibi bırakır ve davetliye ekipten bir kişinin dönüş yapacağı söylenir. Bu log'ları harekete geçebilecek birine yönlendirin.

## Z-API Omni'nin yeri

Omni'nin özel şablon dokümanlarında Confirm ve Reschedule hızlı yanıtlı bir "Appointment reminder" (randevu hatırlatması) modeli var; üçüncü buton olarak Cancel ekleyebilirsiniz. Şablonları `message_send_ttl_seconds` kabul eden `POST /whatsapp/businesses/{wabaId}/templates` ile oluşturursunuz. Meta Cloud API kanallarında onları `POST /v1/channels/{channelId}/messages` ile gönderirsiniz. Dokümanlar bir şablon buton dokunuşunun gelen JSON'unu göstermiyor, bu yüzden handler'ı taşımadan önce bu eşlemeyi test edin.

Dokümanlar bir Calendly entegrasyonu veya zamanlayıcı anlatmıyor, bu yüzden hatırlatma işi ve iptal çağrısı servisinizde kalır. Webhook'lar, [Node.js hızlı başlangıç](/academy/tr/articles/z-api-omni-quickstart-nodejs-express/) yazısında gösterildiği gibi `x-webhook-signature` ile imzalanır. Her numara 1 ila 10 numara için ayda US$29, 11 ila 50 için US$26, 51 ila 100 için US$23 ve 100'ün üzerinde US$20'dir. Resmi bağlantıda Meta'nın ücretleri olduğu gibi yansıtılır.

[Dokümantasyonu görüntüleyin](https://developer.omni.z-api.io/en)

*Z-API Omni ekibi*
