WhatsApp· 10 منٹ کا مطالعہ

Confirm اور Reschedule کے ساتھ WhatsApp پر appointment کی یاد دہانی


یاد دہانی کو دو quick reply بٹنوں، Confirm (تصدیق کریں) اور Reschedule (نیا وقت چنیں)، والے custom utility ٹیمپلیٹ کے طور پر بھیجیں، اور ہر بٹن کے payload میں booking ID رکھیں۔ ٹیمپلیٹ پر message_send_ttl_seconds سیٹ کریں تاکہ جو یاد دہانی Meta وقت پر ڈیلیور نہ کر سکے، اسے drop کر دے۔ ٹیپ آپ کے webhook پر type: "button" پیغام کے طور پر پہنچتا ہے، اور آپ اس کے payload سے booking row اپ ڈیٹ کرتے ہیں۔

یہ کسی بھی bookings table اور scheduler کے لیے عمومی چکر ہے۔ Cal.com webhooks سے WhatsApp یاد دہانیاں اسے Cal.com اور Cal.diy پر لاگو کرتا ہے۔ Instagram اور Messenger DM bookings اسے ان bookings پر لاگو کرتا ہے جو کسی DM سے شروع ہوتی ہیں۔ یہ چکر Calendly اور class timetables سے بھی چلتا ہے، WhatsApp waitlist خالی ہونے والے slots بھر سکتی ہے، اور Meta کے booking appointment ٹیمپلیٹ کی اپنی guide ہے۔

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

WhatsApp Cloud API میں کوئی scheduler نہیں، اس لیے timing آپ کی اپنی job میں ہوتی ہے۔ باقی سب Meta کے send endpoint اور ایک webhook سے چلتا ہے۔

  1. booking کو E.164 فون نمبر اور booking فارم پر لیے گئے WhatsApp opt-in کے ساتھ محفوظ کریں۔
  2. ہر منٹ ایک job چلائیں جو ایک دن پہلے reminder_24h اور دو گھنٹے پہلے reminder_2h بھیجے۔
  3. کسٹمر Confirm یا Reschedule ٹیپ کرتا ہے، اور Meta آپ کے webhook پر button پیغام بھیجتا ہے۔
  4. ٹیپ کو booking سے ملائیں، اس کا status اپ ڈیٹ کریں اور اس 24 گھنٹے کی ونڈو کے اندر جواب دیں جو ٹیپ نے کھولی۔
  5. status webhooks پر نظر رکھیں: TTL ختم ہونے سے پہلے delivered status نہ آئے تو مطلب ہے Meta نے یاد دہانی drop کر دی۔

booking کے وقت ایسے الفاظ میں رضامندی لیں جن میں WhatsApp اور مقصد کا نام ہو۔ الفاظ اور رکھے جانے والے ریکارڈ کی تفصیل WhatsApp opt-in کیسے جمع کریں میں ہے۔

یاد دہانی کے لیے custom utility ٹیمپلیٹ استعمال کریں

Meta، booking appointment کا ایک خاص ٹیمپلیٹ دیتا ہے، لیکن اس میں وہ بٹن نہیں آ سکتے جو اس چکر کو چاہئیں۔ اس کا واحد بٹن booking_status ہے، جو “View details” (تفصیلات دیکھیں) کے طور پر نظر آتا ہے۔ ایک ٹیمپلیٹ میں ایک ہی ہوتا ہے، اور یہ «دوسری بٹن types کے ساتھ ملایا نہیں جا سکتا» (booking appointment templates، رسائی 2026-11-25)۔

QUICK_REPLY بٹنوں والا custom ٹیمپلیٹ یہ کام کرتا ہے۔ «ٹیمپلیٹس 10 quick reply بٹنوں تک محدود ہیں»، اور ہر label کی حد «زیادہ سے زیادہ 25 حروف» ہے۔ quick replies اپنے الگ گروپ میں ہوتے ہیں، URL یا فون بٹنوں سے الگ (template components، رسائی 2026-11-25)۔ دو مختصر labels آسانی سے آ جاتے ہیں۔

Booking appointment ٹیمپلیٹ پھر کہاں کام آتا ہے

اسے booking کے فوراً بعد تصدیق کے لیے استعمال کریں۔ یہ تاریخ، وقت، جگہ اور management links ایک پیغام میں رکھتا ہے، اور “View details” ایک bottom sheet کھولتا ہے۔ آپ اسے category utility، parameter_format named، 60 حروف تک کے text header اور 1,024 تک کی body کے ساتھ بناتے ہیں۔ بھیجتے وقت booking_status بٹن component میں start_datetime ہوتا ہے، جو لازمی ہے، اور end_datetime، location، booking_url اور booking_management_url جیسی optional keys۔

Datetimes، offset کے ساتھ ISO 8601 میں ہوتے ہیں، جیسے -07:00۔ صفحہ یہ بھی کہتا ہے: «بھیجتے وقت آپ کو location، booking_url یا phone_number میں سے کم از کم ایک دینا ہو گا۔» صفحہ notes parameter کو ایک حصے میں param_name اور اپنی مکمل مثال میں parameter_name کہتا ہے، اس لیے Meta کا JSON نقل کریں اور دونوں test کریں۔ صفحہ “View details” ٹیپ کا کوئی webhook دستاویز نہیں کرتا۔

Template Library میں بھی کوئی تیار یاد دہانی نہیں۔ اس کی industries، E_COMMERCE اور FINANCIAL_SERVICES ہیں، اور clone کرنے کے لیے appointment کا کوئی use case نہیں (Template Library، رسائی 2026-11-25)۔

یاد دہانی utility کے طور پر کیوں پاس ہوتی ہے

Meta کا categorization صفحہ چاہتا ہے کہ utility ٹیمپلیٹ «غیر تشہیری» اور «صارف سے متعلق یا اس کی درخواست پر» ہو۔ اس کی مثالیں ایسے پیغامات ہیں جو «واضح طور پر ان کے آرڈر، اکاؤنٹ، سروسز یا transactions سے متعلق ہوں» (template categorization، رسائی 2026-11-25)۔ کسٹمر کی بک کی ہوئی appointment کی یاد دہانی دونوں ٹیسٹ پاس کرتی ہے۔ صفحے پر appointment کی کوئی مثال نہیں۔ سب سے قریبی مثال اس سروس کی ادائیگی کی یاد دہانی ہے جو صارف کے پاس پہلے سے ہے۔

یاد دہانی کے اندر کوئی promotion اسے مارکیٹنگ بنا دیتی ہے۔ appointment کے وقت کے نیچے کسی موسمی offer کی ایک سطر کافی ہے۔ Meta کی سزائیں بڑھتی جاتی ہیں: ایک تنبیہ، پھر فوری recategorization، پھر کم از کم 7 دن کی utility rate limiting۔ اس کے بعد 7 دن کی utility پابندی، یا بار بار خلاف ورزی پر 30 دن، جس کے دوران آپ کے تمام utility ٹیمپلیٹس مارکیٹنگ کے طور پر جاتے ہیں۔ آخری قدم 30 دن کی portfolio پابندی ہے۔

clinics اور دوسری صحت کی سروسز کے لیے body کو وقت، جگہ اور ماہر کے نام تک رکھیں۔ علاج کی تفصیلات اور ہر طبی بات باہر رکھیں۔ کیٹیگری کے قواعد کی گہری تفصیل WhatsApp ٹیمپلیٹ کیٹیگریز میں ہے۔

ہر lead time کے لیے ایک ٹیمپلیٹ بنائیں

TTL، ٹیمپلیٹ کا ہوتا ہے، ہر send کا نہیں۔ field، message_send_ttl_seconds ہے، جو ٹیمپلیٹ بناتے یا اپ ڈیٹ کرتے وقت سیٹ ہوتا ہے۔ utility ٹیمپلیٹس کے لیے حد 30 سیکنڈ سے 12 گھنٹے ہے، default 30 دن ہے، اور -1 کا مطلب بھی 30 دن ہے (time-to-live، رسائی 2026-11-25)۔ Meta «ان پیغامات کو drop کر دیتا ہے جو default یا customized TTL کے اندر ڈیلیور نہ ہو سکیں۔» Utility TTL صرف Cloud API پر کام کرتا ہے۔

چونکہ TTL ہر ٹیمپلیٹ کا ہے، 24 گھنٹے اور 2 گھنٹے والی یاد دہانیوں کو دو ٹیمپلیٹس چاہئیں۔ ایسا TTL چنیں جو appointment سے کافی پہلے ختم ہو۔ T-24h پر 43,200 سیکنڈ کے TTL کے ساتھ بھیجی گئی یاد دہانی، فون کبھی online نہ ہو تو T-12h پر drop ہو جاتی ہے۔

curl "https://graph.facebook.com/v26.0/$WABA_ID/message_templates" \
  -H "Authorization: Bearer $WA_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "reminder_24h",
    "language": "en_US",
    "category": "UTILITY",
    "parameter_format": "NAMED",
    "message_send_ttl_seconds": 43200,
    "components": [
      {
        "type": "BODY",
        "text": "Hi {{customer_name}}, this is a reminder of your appointment on {{date}} at {{time}} with {{professional}}. Please confirm or pick a new time.",
        "example": {
          "body_text_named_params": [
            { "param_name": "customer_name", "example": "Marina" },
            { "param_name": "date", "example": "Friday, November 27" },
            { "param_name": "time", "example": "2:30 PM" },
            { "param_name": "professional", "example": "Jordan Lee" }
          ]
        }
      },
      {
        "type": "BUTTONS",
        "buttons": [
          { "type": "QUICK_REPLY", "text": "Confirm" },
          { "type": "QUICK_REPLY", "text": "Reschedule" }
        ]
      }
    ]
  }'

اسے "name": "reminder_2h" اور "message_send_ttl_seconds": 3600 کے ساتھ دوبارہ چلائیں۔ body “Hi” سے شروع ہوتی ہے کیونکہ variable، text کو شروع یا ختم نہیں کر سکتا۔ اگر Meta کسی ٹیمپلیٹ کی کیٹیگری بدلے تو custom TTL کو null کر دیتا ہے، اس لیے کیٹیگری کی ہر تبدیلی کے بعد message_send_ttl_seconds واپس پڑھیں۔ TTL سے متعلق status کی handling status webhooks سے delivery رپورٹس میں ہے۔

آپ کے webhook میں ٹیپ کیسا دکھتا ہے

ٹیمپلیٹ پر quick reply ٹیپ، type: "button" والے inbound پیغام کے طور پر آتا ہے۔ یہ button webhook reference سے Meta کا نمونہ ہے، line breaks کے سوا بغیر تبدیلی کے (button webhook reference، رسائی 2026-11-25):

{
  "object": "whatsapp_business_account",
  "entry": [
    {
      "id": "102290129340398",
      "changes": [
        {
          "value": {
            "messaging_product": "whatsapp",
            "metadata": {
              "display_phone_number": "15550783881",
              "phone_number_id": "106540352242922"
            },
            "contacts": [
              {
                "profile": { "name": "Sheena Nelson" },
                "wa_id": "16505551234",
                "user_id": "US.13491208655302741918"
              }
            ],
            "messages": [
              {
                "context": {
                  "from": "15550783881",
                  "id": "wamid.HBgLMTQxMjU1NTA4MjkVAgASGBQzQUNCNjk5RDUwNUZGMUZEM0VBRAA="
                },
                "from": "16505551234",
                "from_user_id": "US.13491208655302741918",
                "id": "wamid.HBgLMTY1MDM4Nzk0MzkVAgASGBQzQUFERjg0NDEzNDdFODU3MUMxMAA=",
                "timestamp": "1750091045",
                "type": "button",
                "button": {
                  "payload": "Unsubscribe",
                  "text": "Unsubscribe"
                }
              }
            ]
          },
          "field": "messages"
        }
      ]
    }
  ]
}

context.id اس ٹیمپلیٹ پیغام کا wamid ہے جس پر کسٹمر نے ٹیپ کیا۔ Meta کا نمونہ payload اور text کو ایک ہی label پر سیٹ کرتا ہے، اور reference دونوں کو label بتاتا ہے۔ Meta کے Node SDK docs، payload کو «developer کا طے کردہ payload جو بٹن کلک ہونے پر display text کے علاوہ واپس آتا ہے» کہتے ہیں (button parameter object، رسائی 2026-11-25)۔ اس لیے پہلے button.payload parse کریں۔ اگر یہ آپ کے format میں نہ ہو تو context.id کو اس wamid سے ملائیں جو آپ نے send کے وقت محفوظ کیا۔ صرف فون نمبر سے کبھی match نہ کریں: کسٹمر کی دو appointments ہو سکتی ہیں، اور payload bk|<id>|confirm ایک booking کا نام لیتا ہے۔

کسٹمر کو from کے ساتھ from_user_id سے بھی پہچانیں۔ جب صارف کا username ہو اور کوئی فون دستیاب نہ ہو تو Meta، wa_id اور from چھوڑ دیتا ہے۔ یہ تبدیلی contact database کو BSUID پر منتقل کرنا میں ہے۔

یاد دہانی کی سروس

یہ فائل Node 18 یا بعد کے ورژن اور Express 4 پر paste کرتے ہی چلتی ہے۔ یہ آزمانے کے لیے bookings کو memory میں رکھتی ہے، اور ہر table اس database table کی جگہ ہے جو آپ رکھیں گے۔ یہ X-Hub-Signature-256 verify کرتی ہے، دونوں یاد دہانیاں بھیجتی ہے، ٹیپس اور فہرست کے انتخاب سنبھالتی ہے، اور TTL کے مقابلے میں delivery پر نظر رکھتی ہے۔

// reminders.js: WhatsApp appointment reminders with Confirm and Reschedule.
// Node 18+ and Express 4. Run: npm install express && node reminders.js
const crypto = require("crypto");
const express = require("express");

for (const name of ["WA_TOKEN", "PHONE_NUMBER_ID", "APP_SECRET", "VERIFY_TOKEN", "INTERNAL_TOKEN"]) {
  if (!process.env[name]) throw new Error(`Missing environment variable ${name}`);
}
const { WA_TOKEN, PHONE_NUMBER_ID, APP_SECRET, VERIFY_TOKEN, INTERNAL_TOKEN } = process.env;
const BOOKING_URL = process.env.BOOKING_URL || "https://example.com/book";
const PORT = Number(process.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 TTL_BUFFER = 5 * MINUTE;

// One template per lead time, because the TTL lives on the template.
// ttlMs must match message_send_ttl_seconds on the approved template.
const REMINDERS = [
  { template: "reminder_24h", leadMs: 24 * HOUR, ttlMs: 12 * HOUR },
  { template: "reminder_2h", leadMs: 2 * HOUR, ttlMs: 1 * HOUR },
];

// In-memory tables so the file runs as is. Use your database in production.
const bookings = new Map(); // booking id -> booking
const sends = new Map(); // reminder wamid -> { bookingId, template, sentAt, ttlMs, state }
const seenInbound = new Set(); // inbound wamids already handled

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 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) }; // network error or unexpected body
  }
  const retryable = status === 0 || status === 429 || status >= 500;
  if (retryable && attempt < 4) {
    await new Promise((resolve) => setTimeout(resolve, 2 ** attempt * 1000));
    return sendWhatsApp(message, attempt + 1);
  }
  throw new Error(`Send failed with HTTP ${status}: ${JSON.stringify(data)}`);
}

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

async function sendReminder(booking, reminder) {
  const when = formatWhen(booking.startTime, booking.timeZone);
  const buttons = ["confirm", "reschedule"].map((action, index) => ({
    type: "button",
    sub_type: "quick_reply",
    index: String(index),
    parameters: [{ type: "payload", payload: `bk|${booking.id}|${action}` }],
  }));
  const wamid = await sendWhatsApp({
    to: booking.phone,
    type: "template",
    template: {
      name: reminder.template,
      language: { code: "en_US" },
      components: [
        {
          type: "body",
          parameters: [
            { type: "text", parameter_name: "customer_name", text: booking.name },
            { type: "text", parameter_name: "date", text: when.date },
            { type: "text", parameter_name: "time", text: when.time },
            { type: "text", parameter_name: "professional", text: booking.professional },
          ],
        },
        ...buttons,
      ],
    },
  });
  sends.set(wamid, {
    bookingId: booking.id, template: reminder.template, sentAt: Date.now(), ttlMs: reminder.ttlMs, state: "sent",
  });
  return wamid;
}

async function runReminders() {
  const now = Date.now();
  for (const booking of bookings.values()) {
    if (!booking.optIn || booking.status === "cancelled") continue;
    const start = Date.parse(booking.startTime);
    for (const reminder of REMINDERS) {
      if (booking.reminders[reminder.template]) continue; // sending, sent, skipped or failed
      const due = start - reminder.leadMs;
      if (now < due) continue;
      const tooLate = now >= due + reminder.ttlMs || now >= start; // past the window this lead time was meant for
      const notNeeded = reminder.template === "reminder_2h" && booking.status === "confirmed";
      if (tooLate || notNeeded) {
        booking.reminders[reminder.template] = "skipped";
        continue;
      }
      booking.reminders[reminder.template] = "sending"; // claimed before the await
      try {
        booking.reminders[reminder.template] = await sendReminder(booking, reminder); // stores the wamid
      } catch (err) {
        booking.reminders[reminder.template] = "failed";
        console.error("reminder failed", booking.id, reminder.template, err.message);
      }
    }
  }
  for (const [wamid, send] of sends) {
    if (send.state === "sent" && now > send.sentAt + send.ttlMs + TTL_BUFFER) {
      send.state = "dropped"; // no delivered status before the TTL ended
      const booking = bookings.get(send.bookingId);
      if (booking && booking.reminders[send.template] === wamid) booking.reminders[send.template] = "dropped";
      console.warn("reminder dropped after TTL", send.bookingId, send.template);
    }
  }
}

function writeBack(booking, change) {
  // Replace with an UPDATE on your bookings table or a call to your calendar API.
  Object.assign(booking, change, { updatedAt: new Date().toISOString() });
  console.log("booking updated", booking.id, change);
}

function freeSlots(booking) {
  // Stub: replace with a query on your calendar. Returns ISO start times.
  const start = Date.parse(booking.startTime);
  return [1, 2, 3].map((days) => new Date(start + days * 24 * HOUR).toISOString());
}

async function onTap(booking, action) {
  const when = formatWhen(booking.startTime, booking.timeZone);
  if (Date.parse(booking.startTime) <= Date.now()) {
    return sendText(booking.phone, "This appointment has already passed. Reply here if you would like a new one.");
  }
  if (booking.status === "cancelled") {
    return sendText(booking.phone, "This appointment was cancelled. Reply here if you would like a new one.");
  }
  if (action === "confirm") {
    if (booking.status === "confirmed") return; // a second tap changes nothing
    writeBack(booking, { status: "confirmed" });
    return sendText(booking.phone, `Thanks, ${booking.name}. You are confirmed for ${when.date} at ${when.time}.`);
  }
  if (action === "reschedule") {
    if (booking.status === "reschedule_requested") return;
    writeBack(booking, { status: "reschedule_requested" });
    const rows = freeSlots(booking).slice(0, 10).map((iso) => ({
      id: `slot|${booking.id}|${iso}`,
      title: formatWhen(iso, booking.timeZone).short.slice(0, 24),
    }));
    if (rows.length === 0) {
      return sendWhatsApp({
        to: booking.phone,
        type: "interactive",
        interactive: {
          type: "cta_url",
          body: { text: "No open times fit right now. Pick a new time on our booking page." },
          action: { name: "cta_url", parameters: { display_text: "Choose a time", url: BOOKING_URL } },
        },
      });
    }
    return sendWhatsApp({
      to: booking.phone,
      type: "interactive",
      interactive: {
        type: "list",
        body: { text: "Which of these times works for you?" },
        action: { button: "See times", sections: [{ title: "Open times", rows }] },
      },
    });
  }
}

async function onSlot(booking, iso) {
  if (booking.status !== "reschedule_requested" || Number.isNaN(Date.parse(iso))) return;
  // Check here that the slot is still free in your calendar before you write.
  writeBack(booking, { startTime: iso, status: "confirmed", reminders: {} });
  const when = formatWhen(iso, booking.timeZone);
  return sendText(booking.phone, `Done. Your new time is ${when.date} at ${when.time}.`);
}

async function handleMessage(msg) {
  if (msg.type === "button") {
    const tapped = sends.get(msg.context?.id);
    if (tapped && tapped.state === "sent") tapped.state = "delivered"; // a tap proves delivery
    let [prefix, bookingId, action] = String(msg.button?.payload || "").split("|");
    if (prefix !== "bk") {
      // Payload not in our format: find the reminder this tap belongs to.
      bookingId = sends.get(msg.context?.id)?.bookingId;
      action = { Confirm: "confirm", Reschedule: "reschedule" }[msg.button?.text];
    }
    const booking = bookings.get(bookingId);
    if (booking && action) return onTap(booking, action);
    return console.warn("unmatched button tap", msg.id);
  }
  if (msg.type === "interactive" && msg.interactive?.type === "list_reply") {
    const [prefix, bookingId, iso] = String(msg.interactive.list_reply?.id || "").split("|");
    const booking = bookings.get(bookingId);
    if (prefix === "slot" && booking) return onSlot(booking, iso);
    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.optIn = false;
    }
    return sendText(msg.from, "You will not get appointment reminders here anymore.");
  }
}

async function handleWebhook(body) {
  for (const entry of body.entry || []) {
    for (const change of entry.changes || []) {
      if (change.field !== "messages") continue;
      const value = change.value || {};
      for (const status of value.statuses || []) {
        const send = sends.get(status.id);
        if (!send || send.state !== "sent") continue;
        if (status.status === "delivered" || status.status === "read") send.state = "delivered";
        if (status.status === "failed") {
          send.state = "failed";
          console.warn("reminder failed", send.bookingId, JSON.stringify(status.errors));
        }
      }
      for (const msg of value.messages || []) {
        if (seenInbound.has(msg.id)) continue; // Meta retried this webhook
        seenInbound.add(msg.id);
        await handleMessage(msg).catch((err) => console.error("handler error", msg.id, err.message));
      }
    }
  }
}

const app = express();

// Your booking system calls this when a booking is saved.
app.post("/bookings", express.json(), (req, res) => {
  if (req.get("Authorization") !== `Bearer ${INTERNAL_TOKEN}`) return res.sendStatus(401);
  const { id, phone, name, professional, startTime, timeZone = "UTC", optIn } = req.body || {};
  const valid = /^[\w-]{1,64}$/.test(String(id)) && /^[1-9]\d{7,14}$/.test(String(phone))
    && !Number.isNaN(Date.parse(startTime));
  if (!valid) {
    return res.status(400).json({ error: "Need id, phone as E.164 digits without +, and an ISO startTime" });
  }
  const booking = {
    id: String(id), phone: String(phone), name, professional, startTime, timeZone,
    optIn: optIn === true, status: "pending", reminders: {},
  };
  bookings.set(booking.id, booking);
  res.status(201).json(booking);
});

app.get("/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("/webhook", express.raw({ type: "application/json" }), (req, res) => {
  if (!Buffer.isBuffer(req.body)) return res.sendStatus(400);
  const received = Buffer.from(req.get("X-Hub-Signature-256") || "");
  const expected = Buffer.from("sha256=" + crypto.createHmac("sha256", APP_SECRET).update(req.body).digest("hex"));
  if (received.length !== expected.length || !crypto.timingSafeEqual(received, expected)) {
    return res.sendStatus(401);
  }
  res.sendStatus(200); // answer first, work after
  let body;
  try {
    body = JSON.parse(req.body.toString("utf8"));
  } catch {
    return;
  }
  handleWebhook(body).catch((err) => console.error("webhook error", err.message));
});

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

ایسی booking بنائیں جو اب سے تقریباً 20 گھنٹے بعد شروع ہو، اور اگلا tick فوراً reminder_24h بھیج دے گا۔ چلانے سے پہلے اس request میں startTime کو ایسے ہی وقت پر سیٹ کریں۔

curl -X POST http://localhost:3000/bookings \
  -H "Authorization: Bearer $INTERNAL_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"id":"bk-1042","phone":"16505551234","name":"Marina","professional":"Jordan Lee","startTime":"2026-11-27T14:30:00-05:00","timeZone":"America/New_York","optIn":true}'

booking کی حالتیں pending، confirmed، reschedule_requested اور cancelled ہیں۔ ہر یاد دہانی کے slot میں sending، ایک wamid، skipped، failed یا dropped ہوتا ہے۔ یہی دوسرا field scheduler کو ایک ہی یاد دہانی دو بار بھیجنے سے روکتا ہے، اس لیے اسے memory میں نہیں، database row میں رکھیں۔

ونڈو کے اندر Confirm اور Reschedule کا جواب دیں

ٹیپ ایک inbound پیغام ہے، اس لیے یہ 24 گھنٹے کی کسٹمر سروس ونڈو کھولتا ہے۔ اس کے اندر آپ ٹیمپلیٹ کے بغیر جواب دے سکتے ہیں۔ Confirm پر سروس ایک سادہ تصدیق بھیجتی ہے۔ Reschedule پر یہ دستیاب اوقات کی interactive فہرست بھیجتی ہے، جس کی ہر row ID میں booking ID اور slot ہوتا ہے۔ اگر کوئی slot فٹ نہ ہو تو یہ CTA URL بٹن پر جاتی ہے جو آپ کا booking صفحہ کھولتا ہے۔

row کے عنوان 24 حروف تک محدود ہیں اور ایک فہرست میں تمام sections ملا کر 10 rows ہوتی ہیں۔ سروس عنوانات کو فٹ ہونے کے لیے کاٹ دیتی ہے۔ حدوں کی مکمل table interactive بٹن اور list messages میں ہے۔

یہ free-form جوابات سروس پیغامات شمار ہوتے ہیں۔ 2026-10-01 سے Meta ہر نمبر کو ہر ماہ 1,000 مفت سروس پیغامات دیتا ہے اور اس کے بعد فیس لیتا ہے، جیسا کہ اکتوبر 2026 سے Meta کے سروس پیغامات کی فیس میں بیان ہے۔

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

یاد دہانی کبھی ڈیلیور نہیں ہوئی

جب TTL کسی پیغام کو drop کرے تو Meta کوئی error code نہیں بھیجتا، اس لیے delivered status کا نہ آنا ہی واحد اشارہ ہے۔ سروس TTL اور پانچ منٹ کا وقفہ انتظار کرتی ہے، پھر یاد دہانی کو dropped نشان زد کرتی ہے۔ یہی وہ موقع ہے جب booking کسی شخص کو فون کال کے لیے دی جائے، یا کوئی اور channel آزمایا جائے جس پر کسٹمر نے رضامندی دی ہو۔

کسٹمر کبھی جواب نہیں دیتا

ڈیلیور شدہ یاد دہانی پر ٹیپ نہ ہونا آپ کو حاضری کے بارے میں کچھ نہیں بتاتا۔ سروس booking کو pending رہنے دیتی ہے اور 2 گھنٹے والی یاد دہانی پھر بھی بھیجتی ہے۔ وہیں رک جائیں۔ اسی appointment کے لیے تیسرا ٹیمپلیٹ لاگت بڑھاتا ہے اور کسٹمر کو نمبر block کرنے کی وجہ دیتا ہے۔

ایک ہی ٹیپ دو بار آتا ہے

Meta ان webhooks کو retry کرتا ہے جنہیں وہ ناکام سمجھے، اس لیے ٹیپ آپ تک ایک سے زیادہ بار پہنچ سکتا ہے۔ سروس پہلے inbound message id پر dedupe کرتی ہے۔ پھر state machine دوسرا، الگ ٹیپ پکڑ لیتی ہے، کیونکہ جو booking پہلے سے confirmed ہو وہ دوسرے Confirm کو نظر انداز کرتی ہے۔ restart کے بعد بھی باقی رہنے والے dedupe کے لیے ہر inbound wamid کو unique index والے column میں محفوظ کریں۔

دیر سے یاد دہانیاں اور دیر سے ٹیپ

TTL، ڈیلیور نہ ہونے والی یاد دہانیوں کو drop کرتا ہے، لیکن دیر سے ڈیلیور ہونے والی یاد دہانی پھر بھی پہنچ جاتی ہے۔ scheduler بھیجنے سے پہلے چیک کرتا ہے کہ appointment ابھی مستقبل میں ہے، اور ایسے lead time کو چھوڑ دیتا ہے جس کی TTL ونڈو گزر چکی ہو۔ شروع ہونے کے وقت کے بعد آنے والے ٹیپ کو ایک مختصر جواب ملتا ہے کہ appointment گزر چکی ہے۔

کسٹمر opt out کرتا ہے

STOP کا جواب اس نمبر کی ہر booking کے لیے یاد دہانیاں بند کر دیتا ہے۔ opt-out وہاں ریکارڈ کریں جہاں سے آپ کا booking فارم رضامندی پڑھتا ہے، تاکہ اگلی booking اسے دوبارہ آن نہ کر دے۔

Meta، send کو رد کرتا ہے یا timeout ہو جاتا ہے

سروس network errors، 429 اور 5xx responses کو backoff کے ساتھ تین بار retry کرتی ہے، اور باقی 4xx errors پر رک جاتی ہے۔ ان کی bodies کو log کریں، کیونکہ ان کا مطلب عموماً ٹیمپلیٹ کے نام، زبان یا parameter کی غلطی ہوتی ہے۔ ایک خطرہ باقی رہتا ہے: Meta کے request قبول کرنے کے بعد timeout، retry پر دوسری یاد دہانی بھیج سکتا ہے۔ اگر یہ چھوٹ جانے والی یاد دہانی سے زیادہ اہم ہے تو کوششوں کی تعداد کم کریں۔

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

Omni کے custom ٹیمپلیٹ docs میں Confirm اور Reschedule quick replies والا “Appointment reminder” (appointment کی یاد دہانی) model ہے، reminder_24h جیسا۔ اس کی body ایک variable سے شروع ہوتی ہے، جسے اسی صفحے کے مطابق Meta رد کرتا ہے، اس لیے پہلے “Hi” جیسا کوئی لفظ لگائیں۔ آپ اسے POST /whatsapp/businesses/{wabaId}/templates سے بناتے ہیں، جو message_send_ttl_seconds قبول کرتا ہے، اور POST /v1/channels/{channelId}/messages سے بھیجتے ہیں۔ ٹیمپلیٹس صرف Meta Cloud API channels پر کام کرتے ہیں۔ docs ابھی ٹیمپلیٹ بٹن ٹیپ کا inbound JSON نہیں دکھاتے، اس لیے handler منتقل کرنے سے پہلے یہ mapping test کریں۔

scheduler آپ کا ہی رہتا ہے۔ منقطع channel پر send، CHANNEL_DISCONNECTED کے ساتھ 422 واپس کرتا ہے، اور پیغام «بعد میں بھیجنے کے لیے نہیں رکھا جاتا»۔ قیمت 1 سے 10 نمبروں کے لیے US$29 فی نمبر ماہانہ، 11 سے 50 کے لیے US$26، 51 سے 100 کے لیے US$23 اور 100 سے زیادہ پر US$20 ہے۔ آفیشل connection پر Meta کی فیس آگے منتقل ہوتی ہے۔

curl -X POST "https://api.omni.z-api.io/v1/channels/$CHANNEL_ID/messages" \
  -H "Authorization: Bearer $OMNI_SECRET_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "recipient": { "identifier": "16505551234" },
    "content": {
      "type": "TEMPLATE",
      "attachments": [
        {
          "template": {
            "name": "appointment_reminder",
            "language": { "policy": "deterministic", "code": "en_US" },
            "components": [
              {
                "type": "body",
                "parameters": [
                  { "type": "text", "text": "Marina" },
                  { "type": "text", "text": "2:30pm" },
                  { "type": "text", "text": "Jordan Lee" }
                ]
              },
              {
                "type": "button",
                "sub_type": "quick_reply",
                "index": 0,
                "parameters": [{ "type": "payload", "payload": "bk|bk-1042|confirm" }]
              },
              {
                "type": "button",
                "sub_type": "quick_reply",
                "index": 1,
                "parameters": [{ "type": "payload", "payload": "bk|bk-1042|reschedule" }]
              }
            ]
          }
        }
      ]
    }
  }'

دستاویزات دیکھیں

Z-API Omni ٹیم