# Cal.com webhook سے WhatsApp booking یاد دہانیاں اور جوابات

> X-Cal-Signature-256 verify کریں، Cal.com یا Cal.diy webhooks سے WhatsApp تصدیق اور 24 گھنٹے کی یاد دہانی بھیجیں، پھر API v2 سے cancel یا reschedule کریں۔

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

Cal.com یا Cal.diy کے webhook کو `BOOKING_CREATED`، `BOOKING_RESCHEDULED` اور `BOOKING_CANCELLED` پر subscribe کریں، اور ہر request پر `X-Cal-Signature-256` verify کریں۔ ہر booking کی اپنی نقل `uid` کی key کے ساتھ رکھیں، پھر Confirm، Reschedule اور Cancel کے ساتھ ایک utility تصدیق اور 24 گھنٹے کی یاد دہانی بھیجیں۔ Cancel اور Reschedule کے ٹیپ، Cal.com API v2 کے ذریعے واپس جاتے ہیں۔ Confirm آپ کی اپنی table میں محفوظ ہوتا ہے، کیونکہ Cal.com کی API v2 میں attendee کی حاضری کی تصدیق کا کوئی دستاویزی endpoint نہیں۔

یاد دہانی کا pattern خود، TTL، ٹیمپلیٹ کیٹیگری اور delivery tracking کے ساتھ، [Confirm اور Reschedule کے ساتھ WhatsApp پر appointment کی یاد دہانی](/academy/ur/articles/whatsapp-appointment-reminders-confirm-reschedule/) میں ہے۔ یہ پوسٹ وہ بتاتی ہے جو Cal اضافہ کرتا ہے: اس کا payload، اس کا signature، اس کے write-back endpoints اور وہ events جو آپ کی اپنی calls آپ کو واپس بھیجتی ہیں۔ Calendly والا ورژن [Calendly webhooks سے WhatsApp](/academy/ur/articles/calendly-webhook-whatsapp-confirmations-reminders/) میں ہے، اور booking منسوخ ہونے پر [WhatsApp waitlist](/academy/ur/articles/whatsapp-waitlist-refill-cancelled-appointment/) وہ slot دوبارہ بھر سکتی ہے۔

## Self-hosted Cal.diy کو یاد دہانی کا اپنا راستہ کیوں چاہیے

اپریل 2026 میں Cal.com سے الگ ہونے کے بعد Cal.diy میں کوئی built-in یاد دہانیاں نہیں رہیں۔ Cal.com کی 2026-04-15 کی پوسٹ، Cal.diy کو «open-source scheduling platform» بتاتی ہے، جس کا license، AGPL 3.0 سے MIT کر دیا گیا، اور کہتی ہے کہ «Cal.diy صرف API v2 کے ساتھ آتا ہے» ([Moving to closed-source: the technical changes](https://cal.com/blog/cal-diy-open-source-to-closed-source)، رسائی 2026-11-25)۔ core scheduling logic، app store، booking flows اور API v2 باقی رہے۔ «خودکار workflow engine (یاد دہانیاں، follow-ups، triggers)» ہٹا دیا گیا۔

repository کا README بھی یہی کہتا ہے: «Teams، Organizations، Insights، Workflows، SSO/SAML اور دوسرے صرف EE والے features ہٹا دیے گئے ہیں» ([calcom/cal.diy](https://github.com/calcom/cal.diy)، رسائی 2026-11-25)۔ یہ یہ بھی کہتا ہے: «کوئی hosted/managed ورژن نہیں۔»

اکتوبر اور نومبر 2026 کی دو pull requests اسی علیحدگی کے بعد کی صفائی ہیں۔ PR #30447 نے 2026-10-29 کو WhatsApp workflow کی غیر استعمال شدہ strings ہٹائیں اور [issue #30446](https://github.com/calcom/cal.diy/issues/30446) بند کیا، جس میں لکھا ہے «Workflows، Cal.diy میں نہیں ہے»۔ [PR #30442](https://github.com/calcom/cal.diy/pull/30442) نے Twilio کا صفحہ اور Twilio کے غیر استعمال شدہ environment variables ہٹائے، اور 2026-11-03 کو merge ہوا۔ [PR #30334](https://github.com/calcom/cal.diy/pull/30334) ابھی کھلا ہے اور 2026-11-08 کو stale نشان زد ہوا۔

hosted Cal.com میں Workflows اب بھی ہیں، اور اس کے API reference میں `/v2/workflows` endpoint درج ہے۔ نیچے والا webhook راستہ hosted Cal.com اور self-hosted Cal.diy deployment، دونوں پر ایک ہی طرح چلتا ہے۔

## Event type تیار کریں: فون نمبر اور رضامندی

Cal، attendee کا فون `attendeePhoneNumber` نام کے ایک system booking field میں رکھتا ہے۔ Cal.diy کے source میں اس کی تعریف `type: "phone"`، `hidden: true` اور `required: false` کے ساتھ ہے ([getBookingFields.ts](https://raw.githubusercontent.com/calcom/cal.diy/main/packages/features/bookings/lib/getBookingFields.ts)، رسائی 2026-11-25)۔ شروع میں یہ کسی کو نظر نہیں آتا، اس لیے event type کے booking سوالات میں اسے ظاہر کریں۔

اس کے ساتھ WhatsApp رضامندی کے لیے ایک checkbox سوال شامل کریں۔ Cal ایسا سوال نہیں دیتا، اس لیے یہ ایک سفارش ہے، Cal کا feature نہیں۔ الفاظ ایسے رکھیں کہ attendee کو channel اور مقصد معلوم ہو۔ ایک مثال: «مجھے booking کی تصدیقیں اور یاد دہانیاں WhatsApp پر بھیجیں۔» code اس سوال کو اس کے identifier سے پڑھتا ہے، جو `CONSENT_FIELD` میں سیٹ ہے۔ اور کیا ریکارڈ کرنا ہے، یہ [WhatsApp opt-in کیسے جمع کریں](/academy/ur/articles/whatsapp-opt-in-how-to-collect-consent/) میں ہے۔

سروس `to` field کے لیے فون سے صرف ہندسے رکھتی ہے، اس لیے شروع کا plus یا spaces سے فرق نہیں پڑتا۔ اگر آپ کے attendees کہیں اور ہاتھ سے نمبر لکھتے ہیں تو انہیں [E.164 فون نمبر normalization](/academy/ur/articles/whatsapp-phone-number-format-e164-normalization/) کے مطابق normalize کریں۔

## Webhook کو subscribe کریں

subscription، `POST /v2/webhooks` سے بنائیں ([create a webhook](https://cal.com/docs/api-reference/v2/webhooks/create-a-webhook)، رسائی 2026-11-25)۔ body کو `subscriberUrl`، `active` اور `triggers[]` چاہئیں۔ `secret` بھی سیٹ کریں، کیونکہ سروس unsigned requests رد کرتی ہے۔ optional `version` میں `2021-10-20` یا `2026-07-27` آتا ہے، جو ICS مواد شامل کرتا ہے۔ `customHeaders` میں 10 تک headers آ سکتے ہیں۔

کم از کم `BOOKING_CREATED`، `BOOKING_RESCHEDULED` اور `BOOKING_CANCELLED` پر subscribe کریں۔ جن event types کو host کی تصدیق چاہیے وہ پہلے `BOOKING_REQUESTED` بھیجتے ہیں۔ ہم نے تصدیق نہیں کی کہ ان کے لیے `BOOKING_CREATED` بھی چلتا ہے یا نہیں، اس لیے سروس `BOOKING_REQUESTED` کو log کرتی ہے اور انتظار کرتی ہے۔ دونوں میں سے کسی پر انحصار سے پہلے اپنی deployment پر test کریں۔

## Cal جو payload بھیجتا ہے

ہر delivery کا envelope یہ ہے: `{triggerEvent, createdAt, payload}` ([Cal.com webhooks help](https://cal.com/help/webhooks)، رسائی 2026-11-25)۔ یہ وہ payload keys ہیں جو سروس پڑھتی ہے:

| Key | اس میں کیا ہے |
| --- | --- |
| `uid` | booking کی منفرد ID، جو ہر API v2 call میں استعمال ہوتی ہے |
| `startTime`، `endTime` | UTC میں ISO اوقات |
| `title`، `status` | event کا عنوان اور status، مثلاً `ACCEPTED` |
| `attendees[]` | `name`، `email`، `timeZone`، `language` اور مزید |
| `responses.attendeePhoneNumber.value` | فون، جب field ظاہر ہو |
| `responses.<your question>.value` | آپ کا رضامندی والا checkbox |
| `rescheduleUid` | reschedule پر: پچھلی booking کا `uid` |
| `cancellationReason` | cancel پر |

`responses` کی ہر entry میں `label`، `value` اور `isHidden` ہوتے ہیں۔ reschedule پر `uid` نئی booking ہے، اور `rescheduleUid` پرانی کی طرف اشارہ کرتا ہے، ساتھ `rescheduleId`، `rescheduleStartTime` اور `rescheduleEndTime`۔ `attendees[].phoneNumber` کچھ payloads میں آتا ہے، لیکن نمونوں میں null ہے، اس لیے اس کی بجائے `responses` پڑھیں۔

## Signature verify کریں اور retries کو نامعلوم سمجھیں

Cal، raw body کو HMAC-SHA256 سے sign کرتا ہے اور hex digest کو `X-Cal-Signature-256` میں بھیجتا ہے۔ Cal.diy کا source، ``createHmac("sha256", params.secret).update(`${params.body}`).digest("hex")`` compute کرتا ہے اور اسے `X-Cal-Webhook-Version` کے ساتھ بھیجتا ہے ([sendPayload.ts](https://raw.githubusercontent.com/calcom/cal.diy/main/packages/features/webhooks/lib/sendPayload.ts)، رسائی 2026-11-25)۔ کوئی timestamp signed نہیں ہوتا، اس لیے signature، replay سے تحفظ نہیں دیتا۔ deduplicate اپنی طرف کریں۔

secret کے بغیر header میں لفظی string `no-secret-provided` ہوتی ہے، جسے سروس رد کرتی ہے۔ اگر کوئی custom `payloadTemplate` درست JSON نہ ہو تو content type، `application/x-www-form-urlencoded` ہو جاتا ہے۔ اور request، `redirect: "manual"` والا ایک `fetch` ہے، اس لیے 3xx کو follow نہیں کیا جاتا۔ Cal کو حتمی HTTPS URL دیں، کبھی ایسا نہیں جو redirect کرے۔

اس فائل میں نہ کوئی retry ہے نہ timeout۔ help صفحہ کہتا ہے «Delivery، retry ہو سکتی ہے اور ایک سے زیادہ بار یا بے ترتیب پہنچ سکتی ہے»، لیکن صرف registration events کے لیے۔ Cal، booking webhooks کی کوئی retry پالیسی دستاویز نہیں کرتا۔ سروس فوراً 200 جواب دیتی ہے، `triggerEvent` اور `uid` پر dedupe کرتی ہے، اور کام response کے بعد کرتی ہے۔

WhatsApp کی طرف ایک مختلف طریقہ ہے، `sha256=` prefix اور آپ کے app secret کے ساتھ `X-Hub-Signature-256`۔ دونوں چیک raw bytes پر کیوں چلنے چاہئیں، یہ [WhatsApp webhooks پر X-Hub-Signature-256 verify کریں](/academy/ur/articles/whatsapp-webhook-signature-verification-x-hub-signature-256/) میں ہے۔

## دو ٹیمپلیٹس اور تین بٹن

دونوں پیغامات utility ٹیمپلیٹس ہیں۔ یہ attendee کی بنائی ہوئی booking سے جڑے ہیں اور ان میں کوئی promotion نہیں، اور یہی وہ ٹیسٹ ہے جو [یاد دہانی والا بنیادی مضمون](/academy/ur/articles/whatsapp-appointment-reminders-confirm-reschedule/) سمجھاتا ہے۔ انہیں وہاں دکھائی گئی اسی `message_templates` call سے بنائیں۔

| ٹیمپلیٹ | Body | بٹن | TTL |
| --- | --- | --- | --- |
| `booking_confirmed` | Hi {{customer_name}}, your {{event}} is booked for {{date}} at {{time}}. Reply here if you need to change it. | کوئی نہیں | Default |
| `booking_reminder_24h` | Hi {{customer_name}}, a reminder that your {{event}} is on {{date}} at {{time}}. Please confirm, reschedule or cancel below. | quick replies: Confirm، Reschedule، Cancel | 43,200 سیکنڈ |

clinics اور دوسری صحت کی سروسز کے لیے `{{event}}` میں «appointment» جیسا غیر جانبدار لفظ رکھیں، کیونکہ Cal event کے عنوان میں کسی علاج کا نام ہو سکتا ہے۔

تصدیق کے لیے Meta کا booking appointment ٹیمپلیٹ ایک متبادل ہے، جب آپ manage لنک کے ساتھ "View details" sheet چاہیں۔ اس میں quick replies نہیں ہو سکتے، اس لیے یہ یاد دہانی نہیں بن سکتا۔ بنیادی مضمون اس کے fields درج کرتا ہے۔ اسے بنانے والی call اور بھیجنے کے parameters کی پوری تفصیل [booking appointment ٹیمپلیٹ کی guide](/academy/ur/articles/whatsapp-booking-appointment-template-manage-link/) میں ہے۔

## سروس

یہ فائل Node 18 یا بعد کے ورژن اور Express 4 پر paste کرتے ہی چلتی ہے۔ یہ آزمانے کے لیے state کو memory میں رکھتی ہے۔ دونوں webhook routes اپنے signatures خود verify کرتے ہیں، اور یاد دہانی کی job ہر منٹ چلتی ہے۔

```js
// cal-whatsapp.js: Cal.com or Cal.diy bookings to WhatsApp confirmation, reminder and replies.
// Node 18+ and Express 4. Run: npm install express && node cal-whatsapp.js
const crypto = require("crypto");
const express = require("express");

function env(name, fallback) {
  const value = process.env[name] || fallback;
  if (!value) throw new Error(`Missing environment variable ${name}`);
  return value;
}
const CAL_WEBHOOK_SECRET = env("CAL_WEBHOOK_SECRET");
const CAL_API_KEY = env("CAL_API_KEY"); // cal_live_... or cal_... for test
const CAL_API_BASE = env("CAL_API_BASE", "https://api.cal.com/v2"); // Cal.diy: your own deployment
const CAL_EVENT_TYPE_ID = env("CAL_EVENT_TYPE_ID"); // the event type to offer slots from
const CONSENT_FIELD = env("CONSENT_FIELD", "whatsappConsent"); // your checkbox question
const WA_TOKEN = env("WA_TOKEN");
const PHONE_NUMBER_ID = env("PHONE_NUMBER_ID");
const APP_SECRET = env("APP_SECRET");
const VERIFY_TOKEN = env("VERIFY_TOKEN");
const PORT = Number(env("PORT", "3000"));

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

// In-memory state so the file runs as is. Use your database in production.
const bookings = new Map(); // Cal booking uid -> local booking
const ownReschedules = new Set(); // old uids we rescheduled from WhatsApp
const seenCal = new Set(); // triggerEvent:uid already processed
const seenWa = new Set(); // inbound wamids already processed

const digits = (phone) => String(phone || "").replace(/\D/g, "");
function safeEqual(a, b) {
  const x = Buffer.from(a);
  const y = Buffer.from(b);
  return x.length === y.length && crypto.timingSafeEqual(x, y);
}

function formatWhen(iso, timeZone) {
  const d = new Date(iso);
  return {
    date: d.toLocaleDateString("en-US", { timeZone, weekday: "long", month: "long", day: "numeric" }),
    time: d.toLocaleTimeString("en-US", { timeZone, hour: "numeric", minute: "2-digit" }),
    short: d.toLocaleString("en-US", {
      timeZone, weekday: "short", month: "short", day: "numeric", hour: "numeric", minute: "2-digit",
    }),
  };
}

async function cal(method, path, version, body) {
  const res = await fetch(CAL_API_BASE + path, {
    method,
    headers: {
      Authorization: `Bearer ${CAL_API_KEY}`,
      "cal-api-version": version,
      ...(body ? { "Content-Type": "application/json" } : {}),
    },
    body: body ? JSON.stringify(body) : undefined,
  });
  const data = await res.json().catch(() => ({}));
  if (!res.ok) {
    const err = new Error(`Cal ${method} ${path} returned ${res.status}: ${JSON.stringify(data)}`);
    err.status = res.status;
    throw err;
  }
  return data;
}

async function sendWhatsApp(message, attempt = 1) {
  let status = 0;
  let data = {};
  try {
    const res = await fetch(GRAPH_URL, {
      method: "POST",
      headers: { Authorization: `Bearer ${WA_TOKEN}`, "Content-Type": "application/json" },
      body: JSON.stringify({ messaging_product: "whatsapp", recipient_type: "individual", ...message }),
    });
    status = res.status;
    data = await res.json().catch(() => ({}));
    if (res.ok) return data.messages[0].id;
  } catch (err) {
    data = { error: String(err) };
  }
  if ((status === 0 || status === 429 || status >= 500) && attempt < 4) {
    await new Promise((resolve) => setTimeout(resolve, 2 ** attempt * 1000));
    return sendWhatsApp(message, attempt + 1);
  }
  throw new Error(`WhatsApp send failed with HTTP ${status}: ${JSON.stringify(data)}`);
}

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

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

function fromPayload(p) {
  const attendee = (p.attendees || [])[0] || {};
  return {
    uid: p.uid,
    title: p.title || "appointment",
    name: attendee.name || p.responses?.name?.value || "there",
    phone: digits(p.responses?.attendeePhoneNumber?.value),
    consent: p.responses?.[CONSENT_FIELD]?.value === true,
    startTime: p.startTime,
    timeZone: attendee.timeZone || "UTC",
    createdAt: Date.now(),
    status: "booked", // booked | confirmed | reschedule_requested | cancelled
    reminder: null, // null | "sending" | "skipped" | "failed" | wamid
  };
}

function moveBooking(oldUid, newUid, startTime) {
  if (bookings.has(newUid)) return bookings.get(newUid); // already moved
  const old = bookings.get(oldUid);
  if (!old) return null;
  bookings.delete(oldUid);
  const moved = { ...old, uid: newUid, startTime, status: "booked", reminder: null, createdAt: Date.now() };
  bookings.set(newUid, moved);
  return moved;
}

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

async function onCalEvent(triggerEvent, p) {
  if (triggerEvent === "BOOKING_CREATED") {
    const booking = fromPayload(p);
    bookings.set(booking.uid, booking);
    if (canMessage(booking)) await sendWhatsApp(templateMessage(booking, "booking_confirmed", false));
    return;
  }
  if (triggerEvent === "BOOKING_RESCHEDULED") {
    const ours = ownReschedules.has(p.rescheduleUid); // we already confirmed it in the chat
    let booking = moveBooking(p.rescheduleUid, p.uid, p.startTime);
    if (!booking) {
      booking = fromPayload(p);
      bookings.set(booking.uid, booking);
    }
    if (ours) booking.status = "confirmed"; // the attendee picked this time in the chat
    else if (canMessage(booking)) await sendWhatsApp(templateMessage(booking, "booking_confirmed", false));
    return;
  }
  if (triggerEvent === "BOOKING_CANCELLED") {
    const booking = bookings.get(p.uid);
    if (booking) booking.status = "cancelled"; // stops the reminder
    return;
  }
  console.log("not handled", triggerEvent, p.uid); // BOOKING_REQUESTED and others
}

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

async function offerSlots(booking) {
  const query = new URLSearchParams({
    eventTypeId: CAL_EVENT_TYPE_ID,
    start: new Date().toISOString(),
    end: new Date(Date.now() + 7 * 24 * HOUR).toISOString(),
    timeZone: booking.timeZone,
  });
  const { data = {} } = await cal("GET", `/slots?${query}`, "2024-09-04");
  const rows = Object.values(data).flat().slice(0, 10).map((slot) => ({
    id: `slot|${booking.uid}|${slot.start}`,
    title: formatWhen(slot.start, booking.timeZone).short.slice(0, 24),
  }));
  if (rows.length === 0) {
    booking.status = "booked";
    return sendText(booking.phone, "There are no open times in the next 7 days. Reply here and a person will help.");
  }
  return sendWhatsApp({
    to: booking.phone,
    type: "interactive",
    interactive: {
      type: "list",
      body: { text: "Pick a new time for your booking:" },
      action: { button: "See times", sections: [{ title: "Open times", rows }] },
    },
  });
}

async function onTap(booking, action) {
  if (booking.status === "cancelled") return sendText(booking.phone, "This booking is already cancelled.");
  if (Date.parse(booking.startTime) <= Date.now()) return sendText(booking.phone, "This booking has already passed.");
  const when = formatWhen(booking.startTime, booking.timeZone);
  if (action === "confirm") {
    if (booking.status === "confirmed") return;
    booking.status = "confirmed"; // Cal has no attendee confirm endpoint: this table is the record
    return sendText(booking.phone, `Thanks, ${booking.name}. You are confirmed for ${when.date} at ${when.time}.`);
  }
  if (action === "cancel") {
    booking.status = "cancelled"; // set first so a second tap does nothing
    try {
      await cal("POST", `/bookings/${booking.uid}/cancel`, "2026-02-25", {
        cancellationReason: "Cancelled by the attendee on WhatsApp",
      });
    } catch (err) {
      booking.status = "booked";
      console.error(err.message);
      return sendText(booking.phone, "We could not cancel this booking. A person on our team will follow up.");
    }
    return sendText(booking.phone, "Your booking is cancelled.");
  }
  if (action === "reschedule") {
    if (booking.status === "reschedule_requested") return;
    booking.status = "reschedule_requested";
    try {
      return await offerSlots(booking);
    } catch (err) {
      booking.status = "booked";
      console.error(err.message);
      return sendText(booking.phone, "We could not load open times. A person on our team will follow up.");
    }
  }
}

async function onSlot(booking, start) {
  if (booking.status !== "reschedule_requested" || Number.isNaN(Date.parse(start))) return;
  ownReschedules.add(booking.uid);
  let result;
  try {
    result = await cal("POST", `/bookings/${booking.uid}/reschedule`, "2026-02-25", {
      start,
      reschedulingReason: "Requested by the attendee on WhatsApp",
    });
  } catch (err) {
    ownReschedules.delete(booking.uid);
    booking.status = "booked";
    console.error(err.message);
    return sendText(booking.phone, "We could not move your booking. A person on our team will follow up.");
  }
  const d = result.data || {};
  const newUid = d.rescheduledToUid || (d.rescheduledFromUid ? d.uid : null);
  // Without a new uid in the response, the BOOKING_RESCHEDULED webhook moves the booking.
  const moved = newUid ? moveBooking(booking.uid, newUid, start) : booking;
  moved.status = "confirmed";
  const when = formatWhen(start, moved.timeZone);
  return sendText(moved.phone, `Done. Your new time is ${when.date} at ${when.time}.`);
}

async function onWhatsAppMessage(msg) {
  if (msg.type === "button") {
    const [prefix, uid, action] = String(msg.button?.payload || "").split("|");
    const fromContext = [...bookings.values()].find((b) => b.reminder === msg.context?.id);
    const booking = prefix === "cal" ? bookings.get(uid) : fromContext;
    const act = prefix === "cal" ? action : { Confirm: "confirm", Reschedule: "reschedule", Cancel: "cancel" }[msg.button?.text];
    if (booking && act) return onTap(booking, act);
    return console.warn("unmatched tap", msg.id); // for example a reminder for a time that has since moved
  }
  if (msg.type === "interactive" && msg.interactive?.type === "list_reply") {
    const [prefix, uid, start] = String(msg.interactive.list_reply?.id || "").split("|");
    const booking = bookings.get(uid);
    if (prefix === "slot" && booking) return onSlot(booking, start);
    return;
  }
  if (msg.type === "text" && msg.from && /^\s*stop\s*$/i.test(msg.text?.body || "")) {
    for (const booking of bookings.values()) if (booking.phone === msg.from) booking.consent = false;
    return sendText(msg.from, "You will not get booking messages here anymore.");
  }
}

const app = express();

app.post("/cal/webhook", express.raw({ type: "*/*" }), (req, res) => {
  const header = req.get("X-Cal-Signature-256") || "";
  if (!Buffer.isBuffer(req.body) || header === "no-secret-provided") return res.sendStatus(401);
  const expected = crypto.createHmac("sha256", CAL_WEBHOOK_SECRET).update(req.body).digest("hex");
  if (!safeEqual(header, expected)) return res.sendStatus(401);
  let event;
  try {
    event = JSON.parse(req.body.toString("utf8"));
  } catch {
    return res.sendStatus(400);
  }
  res.sendStatus(200); // answer first, work after
  const key = `${event.triggerEvent}:${event.payload?.uid}`;
  if (seenCal.has(key)) return;
  seenCal.add(key);
  onCalEvent(event.triggerEvent, event.payload || {}).catch((err) => console.error("cal event", key, err.message));
});

app.get("/wa/webhook", (req, res) => {
  const ok = req.query["hub.mode"] === "subscribe" && req.query["hub.verify_token"] === VERIFY_TOKEN;
  return ok ? res.send(String(req.query["hub.challenge"])) : res.sendStatus(403);
});

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

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

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

```bash
BODY='{"triggerEvent":"BOOKING_CREATED","createdAt":"2026-11-25T12:00:00.000Z","payload":{"uid":"test-uid-1","title":"Consultation","startTime":"2026-11-28T15:00:00.000Z","endTime":"2026-11-28T15:30:00.000Z","attendees":[{"name":"Marina","timeZone":"America/New_York"}],"responses":{"attendeePhoneNumber":{"label":"Phone","value":"+16505551234","isHidden":false},"whatsappConsent":{"label":"WhatsApp","value":true,"isHidden":false}}}}'
SIG=$(printf '%s' "$BODY" | openssl dgst -sha256 -hmac "$CAL_WEBHOOK_SECRET" | awk '{print $NF}')
curl -i -X POST http://localhost:3000/cal/webhook \
  -H "Content-Type: application/json" \
  -H "X-Cal-Signature-256: $SIG" \
  --data-binary "$BODY"
```

## جواب Cal.com میں واپس لکھیں

ہر booking endpoint خبردار کرتا ہے کہ `cal-api-version` «لازمی طور پر 2026-02-25 پر سیٹ ہو»۔ دوسری values پر endpoint کا پرانا ورژن چلتا ہے۔ slots endpoint اس سے مستثنیٰ ہے: اسے `2024-09-04` چاہیے۔ authentication، `cal_live_` key یا `cal_` test key کے ساتھ `Authorization: Bearer` ہے۔

| ٹیپ | Call | `cal-api-version` | Body |
| --- | --- | --- | --- |
| Cancel | `POST /v2/bookings/{bookingUid}/cancel` | `2026-02-25` | `cancellationReason` |
| Reschedule، قدم 1 | `GET /v2/slots?eventTypeId=&start=&end=&timeZone=` | `2024-09-04` | کوئی نہیں |
| Reschedule، قدم 2 | `POST /v2/bookings/{bookingUid}/reschedule` | `2026-02-25` | `start` (لازمی)، `reschedulingReason` |
| Confirm | Cal میں کوئی نہیں: اسے اپنی table میں محفوظ کریں | n/a | n/a |

ذرائع: Cal.com API v2 reference کے صفحات [cancel](https://cal.com/docs/api-reference/v2/bookings/cancel-a-booking)، [slots](https://cal.com/docs/api-reference/v2/slots/get-available-time-slots-for-an-event-type) اور [reschedule](https://cal.com/docs/api-reference/v2/bookings/reschedule-a-booking)، رسائی 2026-11-25۔

Cancel، `{status: "success", data: {...}}` واپس کرتا ہے۔ Reschedule، 201 واپس کرتا ہے، جس میں `rescheduledFromUid` اور `rescheduledToUid` دونوں bookings کو جوڑتے ہیں۔ جو bookings، `cancelled`، `rejected` یا `awaiting_host` ہوں وہ 400 واپس کرتی ہیں، اور `pending` booking منتقلی کے بعد بھی pending رہتی ہے۔ Slots، تاریخ کی key والے `data` کے طور پر آتے ہیں، ہر ایک میں `start` والے objects، یا کچھ خالی نہ ہو تو `{}`۔ اس صفحے کا schema اور مثال تھوڑا مختلف ہیں، اس لیے parser پر بھروسا کرنے سے پہلے ایک اصل response log کریں۔ سروس زیادہ سے زیادہ 10 slots دیتی ہے، جو WhatsApp فہرست کی rows کی حد ہے، اور یہ باقی حدوں کے ساتھ [interactive بٹن اور list messages](/academy/ur/articles/whatsapp-interactive-buttons-list-messages-limits/) میں درج ہے۔

`POST /v2/bookings/{uid}/confirm` موجود ہے، لیکن یہ host کا pending booking قبول کرنا ہے، attendee کا حاضری کی تصدیق کرنا نہیں ([confirm a booking](https://cal.com/docs/api-reference/v2/bookings/confirm-a-booking)، رسائی 2026-11-25)۔ ہمیں booking metadata لکھنے کا بھی کوئی endpoint نہیں ملا۔ attendee کی تصدیق اپنی table میں رکھیں۔ اگر آپ بعد میں no-shows نشان زد کریں تو `mark-absent` endpoint کا version header، `2024-08-13` دستاویزی ہے، جبکہ ایک third-party صفحہ `2026-02-25` کہتا ہے، اس لیے test کریں۔

slot فہرست کا ایک متبادل `POST /v2/bookings/{bookingUid}/request-reschedule` ہے۔ Cal کا صفحہ کہتا ہے: «booking منسوخ ہو جائے گی اور attendee کو reschedule کے لنک والی email ملے گی۔» یہ گفتگو کو email پر لے جاتا ہے اور پہلے منسوخ کرتا ہے، اس لیے سروس اسے استعمال نہیں کرتی۔

API ہر key پر فی منٹ 120 requests کی اجازت دیتی ہے، جو 200 تک بڑھ سکتی ہیں ([API v2 introduction](https://cal.com/docs/api-reference/v2/introduction)، رسائی 2026-11-25)۔ base URL `https://api.cal.com/v2` کی مثالوں سے ہے۔ Cal.diy پر `CAL_API_BASE` کو اپنی deployment کی API v2 کی طرف موڑیں۔

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

### آپ کی اپنی calls، webhooks بن کر واپس آتی ہیں

WhatsApp سے کیا گیا cancel یا reschedule، آپ کے endpoint پر `BOOKING_CANCELLED` یا `BOOKING_RESCHEDULED` واپس بھیجتا ہے۔ guard کے بغیر کسٹمر کو اس تبدیلی کی دوسری تصدیق ملتی ہے جو اس نے ایک منٹ پہلے کی۔ سروس call سے پہلے پرانا `uid`، `ownReschedules` میں ریکارڈ کرتی ہے اور جب webhook اس کا نام لے تو خاموش رہتی ہے۔ cancel پر webhook کے راستے سے کچھ بھی نہیں جاتا۔

### Booking نئے uid پر منتقل ہو جاتی ہے

reschedule پر یاد دہانی کی state کو نئے `uid` کے ساتھ جانا چاہیے۔ `moveBooking` مقامی row کو نئی key پر نقل کرتا ہے، یاد دہانی reset کرتا ہے اور call کو idempotent بناتا ہے۔ API response یا webhook، جو بھی پہلے آئے، منتقلی کرتا ہے، اور دوسرا اسے مکمل پاتا ہے۔ پرانے وقت کے لیے بھیجی گئی یاد دہانی پر ٹیپ اب کسی booking سے match نہیں ہوتا، اس لیے سروس غلط appointment پر عمل کی بجائے اسے log کرتی ہے۔

### Duplicate یا بے ترتیب events

چونکہ Cal کوئی timestamp sign نہیں کرتا اور bookings کی کوئی retry پالیسی دستاویز نہیں کرتا، `triggerEvent` اور `uid` پر dedupe کریں۔ reschedule کے بعد آنے والا `BOOKING_CANCELLED` پرانے `uid` کا نام لیتا ہے، جو اب مقامی طور پر موجود نہیں، اس لیے کچھ نہیں ہوتا۔ production سے پہلے in-memory sets کو unique index پر منتقل کریں۔

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

جس booking میں فون یا رضامندی کا box نہ ہو، اسے کوئی WhatsApp پیغام نہیں جاتا۔ STOP کا جواب اس نمبر کی ہر booking پر رضامندی صاف کر دیتا ہے۔ inbound WhatsApp duplicates، message `id` سے چھوڑ دیے جاتے ہیں، جیسا کہ [یاد دہانی والے بنیادی مضمون](/academy/ur/articles/whatsapp-appointment-reminders-confirm-reschedule/) میں ہے۔

### Cal.com تبدیلی سے انکار کرتا ہے

reschedule پر 400 کا مطلب عموماً یہ ہے کہ booking منسوخ ہو چکی، رد ہو چکی یا ابھی host کا انتظار ہے۔ سروس state reset کرتی ہے اور کسٹمر کو بتاتی ہے کہ کوئی شخص رابطہ کرے گا۔ ایسی صورتوں کو کسی اصل inbox تک بھیجیں، کیونکہ یہاں خاموش ناکامی attendee کو یہ سمجھنے دیتی ہے کہ تبدیلی ہو گئی۔

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

Omni یہی دو ٹیمپلیٹس Meta Cloud API channel پر بھیجتا ہے، اور slot فہرست WhatsApp پر interactive list کے طور پر۔ اس کے n8n integration صفحے پر Send Template اور Send Interactive Button operations درج ہیں اور کوئی trigger node نہیں۔ اگر آپ یہ flow، Express کی بجائے n8n میں بناتے ہیں تو Cal events اور inbound پیغامات، دونوں کے لیے n8n کا Webhook node استعمال کریں۔ ٹیمپلیٹ بٹن ٹیپ کا inbound JSON ابھی دستاویزی نہیں، اس لیے اس branch پر انحصار سے پہلے اسے test کریں۔

ہر نمبر کی قیمت 1 سے 10 نمبروں کے لیے US$29 ماہانہ، 11 سے 50 کے لیے US$26، 51 سے 100 کے لیے US$23 اور 100 سے زیادہ پر US$20 ہے۔ Webhooks بغیر حد کے شامل ہیں، اور آفیشل connection پر Meta کی فیس آگے منتقل ہوتی ہے۔

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

*Z-API Omni ٹیم*
