# Calendly webhook سے WhatsApp پر تصدیق اور یاد دہانیاں

> Calendly-Webhook-Signature verify کریں، invitee.created سے WhatsApp تصدیق اور یاد دہانی بھیجیں، Calendly کی API سے cancel کریں اور link سے نیا وقت دیں۔

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

Calendly webhook subscription، Calendly کو کہتی ہے کہ جب بھی کوئی invitee booking کرے یا اسے cancel کرے تو وہ آپ کے URL پر ایک signed JSON event، POST کرے۔ `signing_key` کے ساتھ `invitee.created` اور `invitee.canceled` پر subscribe کریں، `Calendly-Webhook-Signature` verify کریں، اور WhatsApp پر ایک utility تصدیق اور ایک دن پہلے یاد دہانی بھیجیں۔ Cancel ٹیپ، Calendly کے cancellation endpoint سے واپس جاتا ہے۔ Reschedule ایسا نہیں کر سکتا، کیونکہ Calendly میں reschedule کا کوئی endpoint نہیں، اس لیے اس جواب میں invitee کا `reschedule_url` جاتا ہے۔

یاد دہانی کا بنیادی pattern، TTL، category اور delivery tracking سمیت، [Confirm اور Reschedule کے ساتھ WhatsApp پر appointment کی یاد دہانی](/academy/ur/articles/whatsapp-appointment-reminders-confirm-reschedule/) میں ہے۔ Cal.com کے لیے یہی چکر [Cal.com webhooks سے WhatsApp یاد دہانیاں](/academy/ur/articles/cal-com-webhook-whatsapp-booking-reminders/) میں ہے۔

## Booking سے اپ ڈیٹ شدہ event تک کا چکر

1. Calendly، `invitee.created` بھیجتا ہے۔ آپ signature verify کرتے ہیں، event محفوظ کرتے ہیں اور 2xx سے جواب دیتے ہیں۔
2. اگر invitee نے فون نمبر اور WhatsApp کی رضامندی دی ہے تو آپ `booking_confirmed` بھیجتے ہیں۔
3. آپ کا scheduler، `start_time` سے ایک دن پہلے Confirm (تصدیق کریں)، Cancel (منسوخ کریں) اور Reschedule (نیا وقت چنیں) کے ساتھ `booking_reminder_24h` بھیجتا ہے۔
4. ٹیپ آپ کے WhatsApp webhook پر `button` پیغام کے طور پر پہنچتا ہے۔
5. Confirm آپ کی table میں محفوظ ہوتا ہے، Cancel، Calendly کو کال کرتا ہے، اور Reschedule کا جواب link کے ساتھ جاتا ہے۔

Calendly یاد دہانی کا کوئی webhook نہیں بھیجتا، اس لیے آپ کی اپنی job محفوظ booking سے `scheduled_event.start_time` پڑھتی ہے۔ Zapier کے "Calendly + WhatsApp Notifications" zaps نئے invitees اور cancellations پر send سنبھالتے ہیں ([Zapier](https://zapier.com/apps/calendly/integrations/whatsapp-notifications)، رسائی 2026-11-27)۔ اس listing میں Calendly میں جواب واپس لکھنے کا کوئی ذکر نہیں۔

## Signing key کے ساتھ subscription بنائیں

Webhooks کے لیے paid plan ضروری نہیں۔ Calendly کا FAQ کہتا ہے: «Webhooks، Free plan سمیت Calendly کے تمام plans پر دستیاب ہیں» ([Calendly developer FAQ](https://developer.calendly.com/docs/getting-started/frequently-asked-questions.md)، رسائی 2026-11-27)۔ Help page بھی، جو 4 نومبر 2026 کو اپ ڈیٹ ہوا، «All plans» درج کرتا ہے۔ صرف `meeting_recap.*` اور `routing_form_submission.created` کو paid account چاہیے، ورنہ وہ `403` "Please upgrade to a paid Calendly account." واپس کرتے ہیں۔

Token، Personal Access Token یا OAuth ہو سکتا ہے۔ اسے `webhooks:write` چاہیے، اور `invitee.*` events کے لیے ساتھ `scheduled_events:read` بھی ([create webhook subscription](https://developer.calendly.com/api-docs/calendly-api/webhooks/create-webhook-subscription.md)، رسائی 2026-11-27)۔ Read scope کی بجائے `scheduled_events:write` مانگیں، کیونکہ Cancel ٹیپ کو اس کی ضرورت ہے اور `:write` scope میں متعلقہ `:read` شامل ہوتا ہے۔ Organization معلوم کرنے کے لیے `users:read` بھی شامل کریں۔ نئے PATs کو «تب تک کوئی API رسائی نہیں ملتی جب تک scopes واضح طور پر مانگے اور منظور نہ کیے جائیں» ([scopes](https://developer.calendly.com/docs/authentication/scopes.md)، رسائی 2026-11-27)۔

PAT کے ساتھ subscription بناتے وقت ہمیشہ `signing_key` بھیجیں۔ Calendly اسے optional مانتا ہے، اور اس کے بغیر requests بغیر signature کے آتی ہیں۔ OAuth کے ساتھ «آپ کی application سے متعلق تمام webhooks کے لیے signing key خود بخود بن جاتی ہے۔» اگر یہ کھو جائے تو Calendly کہتا ہے کہ «developer support سے رابطہ کریں» ([webhook signatures](https://developer.calendly.com/api-docs/overview/webhooks/webhook-signatures)، رسائی 2026-11-27)۔

Owners اور admins، `organization` یا `user` scope پر subscribe کر سکتے ہیں۔ باقی members صرف `user` استعمال کر سکتے ہیں۔ اسی URL کے ساتھ دوسری subscription، `409` "Hook with this url already exists" واپس کرتی ہے، اس لیے بنانے سے پہلے فہرست دیکھ لیں۔

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

`201` جواب میں subscription، `resource` کے تحت آتی ہے، جس میں `uri`، `callback_url`، `state` اور `retry_started_at` شامل ہیں۔

## invitee.created میں کیا ہوتا ہے

ہر delivery میں `event`، `created_at`، `created_by` اور ایک `payload` ہوتا ہے جو invitee کو بیان کرتا ہے۔ یہ اقتباس Calendly کے نمونے سے مختصر کر کے نئے format میں رکھا گیا ہے، اور اس میں وہ fields ہیں جو سروس پڑھتی ہے ([sample webhook data](https://developer.calendly.com/api-docs/calendly-api/webhooks/get-sample-webhook-data.md)، رسائی 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` خود invitee ہے، اور اس کا آخری حصہ سروس کی booking key ہے۔ `scheduled_event.uri` کا آخری حصہ event UUID ہے، جو cancellation endpoint لیتا ہے۔ `timezone` وہ «time zone ہے جس میں invitee کو وقت دکھانا ہے» ([get event invitee](https://developer.calendly.com/api-docs/calendly-api/scheduled-events/get-event-invitee.md)، رسائی 2026-11-27)۔ `invitee.canceled` کی شکل بھی یہی ہے، بس `status: "canceled"` کے ساتھ اور ایک `cancellation` object جس میں `canceled_by`، `canceler_type` اور `reason` ہوتے ہیں۔

### فون نمبر کہاں سے آتا ہے

Calendly میں تین جگہیں ہیں جہاں فون نمبر ہو سکتا ہے، اور کسی کی بھی ضمانت نہیں۔

- `text_reminder_number`، جس کی تعریف ہے «وہ فون نمبر جس پر text (SMS) یاد دہانیاں بھیجنی ہیں»۔ یہ صرف تب بھرا ہوتا ہے جب invitee نے SMS یاد دہانیاں چنی ہوں۔
- invitee سے پوچھا گیا ایک custom سوال "Phone number"۔ یہ `questions_and_answers[]` میں `{question, answer, position}` کی شکل میں آتا ہے، اور آپ اسے سوال کے بالکل اسی text سے ملاتے ہیں۔
- `type: "outbound_call"` والی `scheduled_event.location`، جہاں `location` «وہ فون نمبر ہے جس سے host، invitee کو کال کرے گا»۔

Calendly یہ نہیں بتاتا کہ جواب کس format میں ہوتا ہے یا اس میں country code ہوتا ہے یا نہیں۔ سروس شروع میں `+` یا `00` قبول کرتی ہے، اور مقامی نمبروں کے لیے `DEFAULT_COUNTRY_CODE` استعمال کرتی ہے۔ دونوں نہ ہوں تو وہ اندازہ لگانے کی بجائے پیغام چھوڑ دیتی ہے۔ مشکل صورتیں [E.164 فون نمبر normalization](/academy/ur/articles/whatsapp-phone-number-format-e164-normalization/) میں ہیں۔

### WhatsApp کی رضامندی آپ کا اپنا سوال ہے

Calendly میں WhatsApp کی رضامندی کا کوئی field نہیں۔ `text_reminder_number`، SMS سے متعلق ایک انتخاب ہے، اس لیے یہ WhatsApp کی رضامندی کا متبادل نہیں۔ invitee کے لیے ایک custom سوال شامل کریں جس میں WhatsApp اور مقصد کا نام ہو، اور صرف تب بھیجیں جب جواب ہاں ہو۔ سروس اسے بالکل اسی text سے ملاتی ہے جو `CONSENT_QUESTION` میں سیٹ ہے۔ الفاظ اور رکھنے والا ریکارڈ [WhatsApp opt-in کیسے جمع کریں](/academy/ur/articles/whatsapp-opt-in-how-to-collect-consent/) میں ہیں۔

## Signature verify کریں اور ہمیشہ 2xx سے جواب دیں

Calendly، `Calendly-Webhook-Signature: t=<unix>,v1=<hex>` بھیجتا ہے۔ `v1` کی value ایک HMAC-SHA256 ہے، hex میں، جو «timestamp (t)، حرف '.' اور request body کے JSON payload» پر بنتا ہے ([webhook signatures](https://developer.calendly.com/api-docs/overview/webhooks/webhook-signatures)، رسائی 2026-11-27)۔ اسے body کے raw bytes پر حساب کریں۔ Calendly کی مثال «3 منٹ سے پرانے» webhooks رد کرتی ہے، اس لیے سروس 180 سیکنڈ استعمال کرتی ہے اور اسے configurable رکھتی ہے۔

کسی بھی 3xx، 4xx یا 5xx پر Calendly «24 گھنٹے تک ڈیلیور کرنے کی کوشش جاری رکھے گا»، «exponential back-off کے ساتھ» ([webhook errors](https://developer.calendly.com/api-docs/overview/webhooks/webhook-errors.md)، رسائی 2026-11-27)۔ یہ «event کی booking کا وقت گزرنے کے 24 گھنٹے بعد» بھی رک جاتا ہے۔ اس کے بعد «اگر کوئی اور پیغام کامیابی سے ڈیلیور نہ ہوا ہو تو webhook غیر فعال ہو جاتا ہے»، اور «hook کو دوبارہ بنانا پڑتا ہے۔»

کاروباری وجہ سے انکار پر 400 واپس کرنا، جیسے بغیر فون والی booking، اس event کو ایک دن تک دوبارہ بھجواتا ہے اور subscription کو غیر فعال کر سکتا ہے۔ سروس، event کے verify اور محفوظ ہوتے ہی 2xx واپس کرتی ہے، اور انکار کو log کر دیتی ہے۔

Calendly، connection کے لیے 10 سیکنڈ اور read کے لیے 15 سیکنڈ کا timeout دیتا ہے، اور کہتا ہے کہ «فوراً» acknowledge کریں اور کام asynchronous طریقے سے کریں ([webhook timeouts](https://developer.calendly.com/api-docs/overview/webhooks/webhook-timeouts.md)، رسائی 2026-11-27)۔ Calendly کسی delivery یا event ID header کا ذکر نہیں کرتا۔ سروس `event`، `payload.uri` اور `created_at` سے اپنی dedupe key بناتی ہے۔ یہ key ہمارا اخذ کردہ نتیجہ ہے، Calendly کا قاعدہ نہیں۔

## Reschedule دو events کی شکل میں آتا ہے

جب invitee نیا وقت چنتا ہے تو Calendly، `rescheduled: true` کے ساتھ `invitee.canceled` اور ایک نیا `invitee.created` بھیجتا ہے ([reschedule payloads](https://developer.calendly.com/docs/api-guides/see-how-webhook-payloads-change-when-invitees-reschedule-events.md)، رسائی 2026-11-27)۔ دونوں invitees، `old_invitee` اور `new_invitee` کے ذریعے ایک دوسرے کا حوالہ دیتے ہیں۔ دونوں deliveries کی ترتیب دستاویز میں نہیں۔

Reschedule کے پہلے حصے پر کبھی "cancelled" نہ بھیجیں۔ سروس `rescheduled` flag پر فیصلہ کرتی ہے۔ `rescheduled: true` والا `invitee.canceled` پرانی row کو `moved` کر دیتا ہے اور کچھ نہیں بھیجتا۔ `old_invitee` والا `invitee.created` بھی پرانی row کو `moved` کرتا ہے اور نئے وقت کے ساتھ `booking_moved` بھیجتا ہے۔ ترتیب جو بھی ہو، نتیجہ ایک ہی state ہوتی ہے۔

آپ کی اپنی cancellations بھی واپس آتی ہیں۔ API سے کیا گیا cancel، `canceler_type: "host"` کے ساتھ `invitee.canceled` بھیجتا ہے۔ سروس کال سے پہلے row کو `cancel_requested` کر دیتی ہے، اس لیے وہ webhook دوسرا نوٹس بھیجنے کی بجائے خاموش رہتا ہے۔

## چار utility ٹیمپلیٹس

چاروں utility ٹیمپلیٹس ہیں۔ ہر ایک اس meeting کے بارے میں ہے جو invitee نے بک کی، جو Meta کا ٹیسٹ پاس کرتی ہے، جیسا کہ [یاد دہانی والے بنیادی مضمون](/academy/ur/articles/whatsapp-appointment-reminders-confirm-reschedule/) میں بیان ہے۔ ان میں سے کسی میں بھی promotion ڈالیں تو وہ مارکیٹنگ بن جاتا ہے۔

| ٹیمپلیٹ | Body | بٹن | TTL |
| --- | --- | --- | --- |
| `booking_confirmed` | Hi {{customer_name}}, your {{event}} is booked for {{date}} at {{time}}. Reply here if you have a question. | کوئی نہیں | Default |
| `booking_moved` | Hi {{customer_name}}, your {{event}} has moved to {{date}} at {{time}}. | کوئی نہیں | Default |
| `booking_cancelled` | Hi {{customer_name}}, your {{event}} on {{date}} at {{time}} is cancelled. | کوئی نہیں | 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 سیکنڈ |

انہیں [یاد دہانی والے بنیادی مضمون](/academy/ur/articles/whatsapp-appointment-reminders-confirm-reschedule/) والی `message_templates` کال سے بنائیں، جو `message_send_ttl_seconds` بھی سمجھاتا ہے۔ Calendly میں event کا نام کسی علاج کو بیان کر سکتا ہے، اس لیے clinics کو `{{event}}` میں "appointment" جیسا غیر جانبدار لفظ ڈالنا چاہیے۔

تصدیق کے لیے Meta کا booking appointment ٹیمپلیٹ ایک متبادل ہے، جس میں "View details" (تفصیلات دیکھیں) sheet اور manage link ہوتا ہے۔ `reschedule_url` کی شکل `https://calendly.com/reschedulings/<id>` ہوتی ہے، اس لیے `https://calendly.com/reschedulings/{{1}}` والا `booking_management_url`، ID کو suffix کے طور پر لے کر، Meta کے «آخر میں ایک parameter» والے قاعدے پر پورا اترتا ہے۔ یہ مطابقت ہمارا اخذ کردہ نتیجہ ہے، اس لیے اسے test کریں۔ Fields [booking appointment ٹیمپلیٹ والے مضمون](/academy/ur/articles/whatsapp-booking-appointment-template-manage-link/) میں ہیں۔

## Calendly سے WhatsApp والی سروس

یہ فائل Node 18 یا اس سے نئے اور Express 4 پر ویسے ہی چلتی ہے جیسے paste کی گئی۔ یہ state کو memory میں رکھتی ہے تاکہ آپ اسے آزما سکیں، اور یاد دہانی کی job ہر منٹ چلتی ہے۔

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

اصلی booking کے بغیر Calendly والا راستہ آزمانے کے لیے، ایک body کو اپنی key اور موجودہ وقت کے ساتھ sign کریں۔ سروس 200 سے جواب دیتی ہے، پھر `booking_confirmed` بھیجنے کی کوشش کرتی ہے، جس کے لیے منظور شدہ ٹیمپلیٹ اور ایسا نمبر چاہیے جو test پیغامات قبول کرے۔

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

## ٹیپ کو Calendly میں واپس لکھیں

| ٹیپ | سروس کیا کرتی ہے | Calendly کال |
| --- | --- | --- |
| Confirm | آپ کی table میں row کو `confirmed` کرتی ہے | کوئی نہیں |
| Cancel | Event کو cancel کرتی ہے | `POST /scheduled_events/{uuid}/cancellation`، scope `scheduled_events:write` کے ساتھ |
| Cancel، group event | invitee کا `cancel_url` بھیجتی ہے | کوئی نہیں |
| Reschedule | invitee کا `reschedule_url`، CTA URL بٹن کے طور پر بھیجتی ہے | کوئی نہیں: ایسا کوئی endpoint موجود نہیں |

Cancellation کی body optional ہے، مثلاً `{"reason": "Something came up."}`۔ `201` جواب میں `canceled_by`، `reason`، `canceler_type` اور `created_at` آتے ہیں ([cancel event](https://developer.calendly.com/api-docs/calendly-api/scheduled-events/create-scheduled-event-cancellation.md)، رسائی 2026-11-27)۔ تمام errors ایک ہی `403 Permission Denied` دیتے ہیں، ان پیغامات کے ساتھ: "You are not allowed to cancel this event"، "Event in the past" یا "Event is already canceled"۔ اس لیے سروس پیغام کی بنیاد پر فیصلہ کرتی ہے اور "already canceled" کو کامیابی مانتی ہے۔

FAQ کہتا ہے کہ یہ endpoint «ایک event کو cancel کرتا ہے، Group event سمیت، لیکن کسی اکیلے invitee کو نہیں۔» group session میں ایک شخص کے لیے اسے کال کرنا سب کو cancel کر دے گا۔ اپنے group event types کے URIs، `GROUP_EVENT_TYPES` میں درج کریں، اور سروس ان کے لیے `cancel_url` بھیجے گی۔

Rescheduling پر FAQ صاف کہتا ہے: «اس وقت کوئی ایسا API endpoint نہیں جو کسی event یا invitee کو reschedule کر سکے۔» Scheduling API کا `POST https://api.calendly.com/invitees` نیا وقت بک کر سکتا ہے۔ Cancel اور پھر create، atomic نہیں، اور paid event types اس سے بک نہیں ہو سکتے۔ یہ Free اور Trial پر فی صارف روزانہ 5، اور Enterprise سے نیچے کے paid plans پر روزانہ 100 کی اجازت دیتا ہے ([rate limits](https://developer.calendly.com/api-docs/overview/rate-limits.md)، رسائی 2026-11-27)۔

ٹیپ کا جواب free-form ہوتا ہے، کیونکہ ٹیپ نے 24 گھنٹے کی ونڈو کھول دی۔ یہ جوابات service messages ہیں، جن کی قیمت [اکتوبر 2026 سے Meta کے service message charges](/academy/ur/articles/meta-whatsapp-service-message-charges-october-2026/) میں بیان ہے۔

## جب چکر ٹوٹ جائے

### Calendly، subscription غیر فعال کر دیتا ہے

آپ کے environment میں غلط signing key ہو تو سروس ہر اصلی delivery کو 401 سے رد کرتی ہے۔ Calendly، 24 گھنٹے retry کرتا رہتا ہے اور پھر hook غیر فعال کر دیتا ہے۔ روزانہ کی ایک job سے list endpoint پر `state` چیک کریں، اور اگر وہ `disabled` ہو تو subscription دوبارہ بنائیں۔ Calendly کے صفحات یہ نہیں بتاتے کہ دوبارہ بنانے کے بعد پرانے events دوبارہ آتے ہیں یا نہیں، اس لیے اپنی table کا متوقع events سے موازنہ کریں۔

### ایک ہی event دو بار آتا ہے

`event`، `payload.uri` اور `created_at` والی key، retry کو پکڑ لیتی ہے، اور bookings map اسی invitee کے دوسرے `invitee.created` کو۔ Production سے پہلے دونوں کو unique key والی table میں لے جائیں، ورنہ restart پر وہ بھول جائیں گے۔

### فون نہیں، رضامندی نہیں، یا STOP

جس booking میں قابلِ استعمال نمبر نہ ہو یا رضامندی والے سوال کا جواب ہاں نہ ہو، اسے کوئی WhatsApp پیغام نہیں جاتا، اور webhook پھر بھی 200 واپس کرتا ہے۔ STOP والا جواب اس نمبر کی ہر booking پر رضامندی ختم کر دیتا ہے۔ Opt-out وہیں ریکارڈ کریں جہاں سے آپ رضامندی پڑھتے ہیں، تاکہ بعد کی کوئی booking اسے دوبارہ فعال نہ کر دے۔

### Cancellation ناکام ہو جاتی ہے

Network error یا غیر متوقع status، row کو ویسے ہی چھوڑ دیتا ہے، اور invitee کو بتایا جاتا ہے کہ ٹیم کا کوئی شخص رابطہ کرے گا۔ یہ logs کسی ایسے شخص تک پہنچائیں جو کارروائی کر سکے۔

## Z-API Omni کہاں کام آتا ہے

Omni کے custom template docs میں Confirm اور Reschedule quick replies والا "Appointment reminder" ماڈل ہے، اور آپ تیسرے کے طور پر Cancel شامل کر سکتے ہیں۔ ٹیمپلیٹس `POST /whatsapp/businesses/{wabaId}/templates` سے بنتے ہیں، جو `message_send_ttl_seconds` قبول کرتا ہے۔ انہیں Meta Cloud API channels پر `POST /v1/channels/{channelId}/messages` سے بھیجا جاتا ہے۔ Docs ٹیمپلیٹ بٹن ٹیپ کا inbound JSON نہیں دکھاتے، اس لیے handler منتقل کرنے سے پہلے یہ mapping test کریں۔

Docs میں نہ کوئی Calendly integration ہے اور نہ scheduler، اس لیے یاد دہانی کی job اور cancellation کال آپ کی سروس میں رہتی ہیں۔ Webhooks پر `x-webhook-signature` سے signature ہوتا ہے، جیسا کہ [Node.js quickstart](/academy/ur/articles/z-api-omni-quickstart-nodejs-express/) میں دکھایا گیا ہے۔ ہر نمبر کی قیمت 1 سے 10 نمبروں کے لیے US$29 ماہانہ، 11 سے 50 کے لیے US$26، 51 سے 100 کے لیے US$23 اور 100 سے زیادہ پر US$20 ہے۔ آفیشل connection پر Meta کی فیس آگے منتقل ہوتی ہے۔

[دستاویزات دیکھیں](https://developer.omni.z-api.io/en)

*Z-API Omni ٹیم*
