# Supabase database webhooks سے WhatsApp notifications

> Supabase row بدلنے پر pg_net یا pgmq queue کے ذریعے WhatsApp utility ٹیمپلیٹ بھیجیں، پھر کسٹمر کے بٹن والے جواب کو اسی row میں واپس لکھیں۔

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

Table پر ایک `AFTER UPDATE` trigger لگائیں، اسے `net.http_post` کے ذریعے ایک Edge Function کال کرنے دیں، اور اسی function سے utility ٹیمپلیٹ بھیجیں۔ کسٹمر کا quick-reply ٹیپ ایک دوسرے Edge Function پر واپس آتا ہے، جو Meta کا signature verify کر کے row اپ ڈیٹ کرتا ہے۔ Supabase Database Webhook ایک Postgres trigger ہے جو row کے insert، update یا delete ہونے کے بعد pg_net extension کے ذریعے HTTP request بھیجتا ہے۔

یہاں مثال ایک `orders` table کی ہے۔ جب `status` بدل کر `ready_for_pickup` ہو جائے تو کسٹمر کو تین بٹنوں والا ٹیمپلیٹ ملتا ہے: Today، Tomorrow اور Cancel my order۔ ٹیپ، order میں `pickup_plan` یا منسوخی کی درخواست واپس لکھ دیتا ہے۔

## Row کی تبدیلی سے اپ ڈیٹ شدہ row تک کا چکر

1. کسی row کا update، `status` بدلتا ہے، اور `WHEN` clause والا trigger اس تبدیلی پر ایک بار چلتا ہے۔
2. Transaction کے commit ہونے کے بعد pg_net پرانی اور نئی row، `notify-pickup` Edge Function کو POST کرتا ہے۔
3. Function، row کو claim کرتا ہے، رضامندی چیک کرتا ہے اور WhatsApp Cloud API کے ذریعے `pickup_ready` ٹیمپلیٹ بھیجتا ہے۔
4. کسٹمر بٹن ٹیپ کرتا ہے، اور Meta ایک `type: "button"` پیغام `whatsapp-inbound` function کو POST کرتی ہے۔
5. یہ function، message ID پر dedupe کرتا ہے، order کی حالت چیک کرتا ہے اور جواب row میں لکھ دیتا ہے۔

Supabase کے مطابق Database Webhooks کا مقصد یہ ہے کہ «جب بھی کوئی table event ہو، اپنے database سے real-time data کسی دوسرے سسٹم کو بھیجیں»۔ یہ ان triggers کے گرد ایک wrapper ہیں جو pg_net استعمال کرتے ہیں، اور pg_net «asynchronous ہے، اس لیے لمبی network requests کی وجہ سے آپ کی database تبدیلیوں کو نہیں روکتا» ([Supabase Database Webhooks](https://supabase.com/docs/guides/database/webhooks)، رسائی 2026-11-27)۔

## Tables

`orders` table میں وہ سب ہے جو اس چکر کو چاہیے: E.164 فون، رضامندی کا timestamp، send کا claim، ٹیمپلیٹ کی message ID اور کسٹمر کا جواب۔ `wa_inbound` ہر inbound wamid کو ایک بار محفوظ کرتا ہے، تاکہ دوبارہ آنے والا webhook کسی ٹیپ کو دو بار لاگو نہ کر سکے۔ یہ statements کسی بھی Postgres پر چلتی ہیں، PGlite سمیت۔

```sql
create table public.orders (
  id bigint generated always as identity primary key,
  order_number text not null,
  phone text not null,                -- E.164 digits without the plus sign
  store_name text not null,
  status text not null default 'pending',
  whatsapp_opt_in_at timestamptz,     -- null means no WhatsApp messages
  notified_at timestamptz,            -- set when a send is claimed
  wa_message_id text,                 -- wamid of the template message
  pickup_plan text,                   -- 'today' or 'tomorrow' from the tap
  updated_at timestamptz not null default now()
);

create table public.wa_inbound (
  wamid text primary key,
  received_at timestamptz not null default now()
);
```

فون کو row تک پہنچنے سے پہلے normalize کریں، جیسا کہ [E.164 فون نمبر normalization](/academy/ur/articles/whatsapp-phone-number-format-e164-normalization/) میں دکھایا گیا ہے۔ `whatsapp_opt_in_at` صرف ایسے checkbox سے بھریں جس میں WhatsApp اور مقصد کا نام ہو، جیسا کہ [WhatsApp opt-in کیسے جمع کریں](/academy/ur/articles/whatsapp-opt-in-how-to-collect-consent/) میں بتایا گیا ہے۔

## Trigger اور جو کچھ وہ بھیجتا ہے

Supabase کے dashboard کا form، `supabase_functions.http_request` پر ایک trigger بناتا ہے۔ اس کی مثال پانچ positional arguments دیتی ہے، اور صفحہ آخری دو کا نام نہیں بتاتا۔ Edge Function کال کرنے کا دستاویزی migration pattern زیادہ واضح ہے: یہ Vault سے project URL اور ایک secret key پڑھتا ہے اور named arguments کے ساتھ `net.http_post` کال کرتا ہے۔

Supabase کی مثال `'old_record', null` والا ایک `after insert` trigger ہے۔ نیچے والا version، updates کے لیے ہماری اپنی تبدیلی ہے۔ یہ `to_jsonb(old)` بھیجتا ہے اور `WHEN (old.status is distinct from new.status)` شامل کرتا ہے، تاکہ بعد میں دوسرے columns کے updates اسے نہ چلائیں۔ اس block کے لیے Supabase ضروری ہے، کیونکہ Vault، Supabase کا feature ہے اور pg_net، PGlite کی extensions کی فہرست میں نہیں۔

```sql
-- Run the two vault calls once in the SQL editor, not in a committed migration.
select vault.create_secret('https://<PROJECT_REF>.supabase.co', 'project_url');
select vault.create_secret('<SUPABASE_SECRET_KEY>', 'secret_key');

create or replace function public.notify_pickup_ready()
returns trigger
language plpgsql
security definer
set search_path = ''
as $$
begin
  perform net.http_post(
    url := (select decrypted_secret from vault.decrypted_secrets where name = 'project_url')
           || '/functions/v1/notify-pickup',
    headers := jsonb_build_object(
      'Content-Type', 'application/json',
      'apikey', (select decrypted_secret from vault.decrypted_secrets where name = 'secret_key')
    ),
    body := jsonb_build_object(
      'type', tg_op,
      'table', tg_table_name,
      'schema', tg_table_schema,
      'record', to_jsonb(new),
      'old_record', to_jsonb(old)
    )
  );
  return new;
end;
$$;

create trigger notify_pickup_ready
after update of status on public.orders
for each row
when (old.status is distinct from new.status and new.status = 'ready_for_pickup')
execute function public.notify_pickup_ready();
```

`authenticated` جیسے roles، Vault نہیں پڑھ سکتے، اس لیے `security definer` کے بغیر ان کے updates، permission error کے ساتھ ناکام ہو جاتے ہیں۔ pg_net، commit کا انتظار بھی کرتا ہے: «HTTP requests تب تک شروع نہیں ہوتیں جب تک transaction، commit نہ ہو جائے» ([pg_net](https://supabase.com/docs/guides/database/extensions/pg_net)، رسائی 2026-11-27)۔ Roll back ہونے والا update کچھ نہیں بھیجتا۔

### Payload کی شکل

Supabase، payload کو TypeScript types کے طور پر شائع کرتا ہے، JSON نمونے کے طور پر نہیں۔ Update میں `type: 'UPDATE'`، `table`، `schema`، `record` اور `old_record` ہوتے ہیں۔ نیچے والا نمونہ ہم نے انہی types سے بنایا ہے، `orders` table کی values کے ساتھ۔

```json
{
  "type": "UPDATE",
  "table": "orders",
  "schema": "public",
  "record": {
    "id": 1042,
    "order_number": "A-1042",
    "phone": "16505551234",
    "store_name": "Downtown store",
    "status": "ready_for_pickup",
    "whatsapp_opt_in_at": "2026-11-20T14:02:11+00:00",
    "notified_at": null,
    "wa_message_id": null,
    "pickup_plan": null,
    "updated_at": "2026-11-27T10:15:00+00:00"
  },
  "old_record": {
    "id": 1042,
    "order_number": "A-1042",
    "phone": "16505551234",
    "store_name": "Downtown store",
    "status": "packing",
    "whatsapp_opt_in_at": "2026-11-20T14:02:11+00:00",
    "notified_at": null,
    "wa_message_id": null,
    "pickup_plan": null,
    "updated_at": "2026-11-27T09:40:00+00:00"
  }
}
```

### Request کیسے authenticate ہوتی ہے

Supabase، Database Webhooks پر signature نہیں لگاتا۔ کوئی signature header دستاویزی نہیں، اس لیے اصل ذریعے کا واحد ثبوت وہ header ہے جو آپ خود شامل کرتے ہیں۔ Edge Function کے لیے docs کہتے ہیں: «function میں اسے `auth: 'secret'` اور `verify_jwt = false` کے ساتھ قبول کریں» ([Supabase Database Webhooks](https://supabase.com/docs/guides/database/webhooks)، رسائی 2026-11-27)۔ اوپر والا `apikey` header وہی secret key لے کر جاتا ہے۔

Database سے گزرتے وقت key چھپی نہیں رہتی۔ Supabase کا rendered صفحہ کہتا ہے کہ pg_net «request بھیجنے تک decrypted key کو net.http_request_queue میں لکھتا ہے»، اور request کے انتظار کے دوران login کر سکنے والا کوئی بھی role اسے پڑھ سکتا ہے۔ Dashboard form کے ساتھ key «ہر اس جگہ نظر آتی ہے جہاں trigger کا SQL ہو، جیسے database dump میں»۔ ایک الگ named key، جو `auth: 'secret:<name>'` کے ساتھ قبول ہو، trigger کی key کو آپ کی دوسری services والی key سے الگ رکھتی ہے۔

اگر وصول کرنے والی سروس Supabase سے باہر کی Node سروس ہے تو اپنا `Authorization: Bearer <shared secret>` header شامل کریں اور اس کا constant time میں موازنہ کریں۔ Supabase ایسا کوئی header دستاویز نہیں کرتا، اس لیے یہ ہمارا اپنا ہے۔

## پیغام، اور یہ utility کیوں شمار ہوتا ہے

Meta کا categorization صفحہ کہتا ہے کہ utility ٹیمپلیٹس «عام طور پر صارف کے کسی عمل یا درخواست سے شروع ہوتے ہیں»۔ ان کا غیر تشہیری ہونا لازمی ہے، اور ساتھ ہی یا تو «صارف سے مخصوص یا اس کا مانگا ہوا» یا «ضروری یا اہم» ہونا بھی ([template categorization](https://developers.facebook.com/documentation/business-messaging/whatsapp/templates/template-categorization)، رسائی 2026-11-27)۔ کسٹمر کے اپنے دیے ہوئے order کی pickup اطلاع دونوں شرطیں پوری کرتی ہے۔ Meta کی Order Management والی مثال اس کے قریب ہے: "Your order {{order_number}} is confirmed. We will let you know once your package is on its way."

اس میں کوئی offer نہ ڈالیں۔ Meta ملے جلے مواد والے ٹیمپلیٹس کو، «جیسے promo والی order اپ ڈیٹ»، مارکیٹنگ میں رکھتی ہے۔ ٹیمپلیٹ ایک بار بنائیں۔

```bash
curl "https://graph.facebook.com/v26.0/$WABA_ID/message_templates" \
  -H "Authorization: Bearer $WA_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "pickup_ready",
    "language": "en_US",
    "category": "UTILITY",
    "parameter_format": "NAMED",
    "components": [
      {
        "type": "BODY",
        "text": "Your order {{order_number}} is ready for pickup at {{store_name}}. When will you come by?",
        "example": {
          "body_text_named_params": [
            { "param_name": "order_number", "example": "A-1042" },
            { "param_name": "store_name", "example": "Downtown store" }
          ]
        }
      },
      {
        "type": "BUTTONS",
        "buttons": [
          { "type": "QUICK_REPLY", "text": "Today" },
          { "type": "QUICK_REPLY", "text": "Tomorrow" },
          { "type": "QUICK_REPLY", "text": "Cancel my order" }
        ]
      }
    ]
  }'
```

بھیجتے وقت ہر quick-reply بٹن کو `pk|1042|today` جیسا payload ملتا ہے، تاکہ ٹیپ میں order کا نام آ جائے۔ Order والے پیغامات کے بٹنوں کا ڈیزائن [Confirm اور Cancel بٹنوں والی order confirmation](/academy/ur/articles/whatsapp-order-confirmation-confirm-cancel-buttons/) میں زیادہ تفصیل سے ہے۔

## بھیجنے والا Edge Function

اسے `supabase/functions/notify-pickup/index.ts` کے طور پر محفوظ کریں۔ یہ trigger کا payload قبول کرتا ہے، یا آگے بیان کی گئی queue پر کام کرنے کے لیے `{"drain": true}`۔ Claim ایک مشروط update ہے: صرف وہ row واپس آتی ہے جو ابھی تک `ready_for_pickup` میں ہو، رضامندی رکھتی ہو اور جس کا `notified_at` نہ ہو۔ اسی تبدیلی کے لیے دوسری کال کو کچھ نہیں ملتا اور وہ کچھ نہیں بھیجتی۔

```ts
// supabase/functions/notify-pickup/index.ts
// Body: the Database Webhook payload from pg_net, or {"drain": true} to work the pgmq queue.
import { withSupabase } from 'npm:@supabase/server@1'

const GRAPH_URL = `https://graph.facebook.com/v26.0/${Deno.env.get('PHONE_NUMBER_ID')}/messages`
const WA_TOKEN = Deno.env.get('WA_TOKEN') ?? ''
const TEMPLATE = Deno.env.get('WA_TEMPLATE') ?? 'pickup_ready'
const QUEUE = 'wa_notify'
const MAX_READS = 5

type Order = { id: number; order_number: string; phone: string; store_name: string }

async function sendTemplate(order: Order): Promise<string> {
  const buttons = ['today', 'tomorrow', 'cancel'].map((action, index) => ({
    type: 'button',
    sub_type: 'quick_reply',
    index: String(index),
    parameters: [{ type: 'payload', payload: `pk|${order.id}|${action}` }],
  }))
  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',
      to: order.phone,
      type: 'template',
      template: {
        name: TEMPLATE,
        language: { code: 'en_US' },
        components: [
          {
            type: 'body',
            parameters: [
              { type: 'text', parameter_name: 'order_number', text: order.order_number },
              { type: 'text', parameter_name: 'store_name', text: order.store_name },
            ],
          },
          ...buttons,
        ],
      },
    }),
  })
  const data = await res.json().catch(() => ({}))
  if (!res.ok) throw new Error(`Graph API ${res.status}: ${JSON.stringify(data)}`)
  return data.messages[0].id
}

// deno-lint-ignore no-explicit-any
async function notify(admin: any, orderId: number): Promise<string> {
  const { data: claimed, error } = await admin
    .from('orders')
    .update({ notified_at: new Date().toISOString() })
    .eq('id', orderId)
    .eq('status', 'ready_for_pickup')
    .is('notified_at', null)
    .not('whatsapp_opt_in_at', 'is', null)
    .select('id, order_number, phone, store_name')
  if (error) throw error
  if (!claimed || claimed.length === 0) return 'skipped' // already sent, no consent, or status moved on
  try {
    const wamid = await sendTemplate(claimed[0])
    await admin.from('orders').update({ wa_message_id: wamid }).eq('id', orderId)
    return 'sent'
  } catch (err) {
    await admin.from('orders').update({ notified_at: null }).eq('id', orderId) // release the claim
    throw err
  }
}

// deno-lint-ignore no-explicit-any
async function drain(admin: any): Promise<string[]> {
  const queue = admin.schema('pgmq_public')
  const { data: messages, error } = await queue.rpc('read', { queue_name: QUEUE, sleep_seconds: 60, n: 10 })
  if (error) throw error
  const results: string[] = []
  for (const m of messages ?? []) {
    if (m.read_ct > MAX_READS) {
      await queue.rpc('archive', { queue_name: QUEUE, message_id: m.msg_id })
      results.push(`gave up on ${m.msg_id}`)
      continue
    }
    try {
      results.push(await notify(admin, Number(m.message.order_id)))
      await queue.rpc('archive', { queue_name: QUEUE, message_id: m.msg_id })
    } catch (err) {
      results.push(`retry later ${m.msg_id}: ${String(err)}`) // visible again after the visibility timeout
    }
  }
  return results
}

export default {
  fetch: withSupabase({ auth: 'secret' }, async (req, ctx) => {
    const body = await req.json().catch(() => ({}))
    try {
      if (body.drain === true) return Response.json({ results: await drain(ctx.supabaseAdmin) })
      if (body.type !== 'UPDATE' || body.table !== 'orders' || !body.record?.id) {
        return Response.json({ ignored: true })
      }
      return Response.json({ result: await notify(ctx.supabaseAdmin, Number(body.record.id)) })
    } catch (err) {
      console.error('notify-pickup failed', String(err))
      return Response.json({ error: String(err) }, { status: 502 })
    }
  }),
}
```

`ctx.supabaseAdmin`، row level security کو bypass کرتا ہے، اس لیے اس function کو secret key کے پیچھے رکھیں۔ `WA_TOKEN` اور `PHONE_NUMBER_ID` کو function secrets کے طور پر سیٹ کریں۔ Edge Functions کو 2 سیکنڈ کا CPU time ملتا ہے، اور wall clock کی حد Free پر 150 سیکنڈ اور paid plans پر 400 سیکنڈ ہے ([Edge Function limits](https://supabase.com/docs/guides/functions/limits)، رسائی 2026-11-27)۔ 10 sends والا drain دونوں میں آرام سے سما جاتا ہے۔

اس مضمون کے دونوں functions، gateway کا JWT چیک چھوڑ دیتے ہیں، کیونکہ pg_net اور Meta کوئی user JWT نہیں بھیجتے۔

```toml
[functions.notify-pickup]
verify_jwt = false

[functions.whatsapp-inbound]
verify_jwt = false
```

## آپ کو ملنے والا جواب اور write-back

ٹیمپلیٹ پر quick-reply ٹیپ `"type": "button"` کے ساتھ آتا ہے۔ `button.payload` میں آپ کا سیٹ کیا ہوا payload ہوتا ہے، اور `context.id`، «اس پیغام کی WhatsApp message ID ہے جس میں وہ بٹن تھا جسے WhatsApp صارف نے ٹیپ کیا» ([button webhook reference](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/reference/messages/button)، رسائی 2026-11-27)۔ Meta کا پورا نمونہ [Confirm اور Reschedule والی WhatsApp appointment یاد دہانیاں](/academy/ur/articles/whatsapp-appointment-reminders-confirm-reschedule/) میں ہے۔ اب اس میں `from` کے ساتھ `from_user_id` بھی ہوتا ہے، جس کی وضاحت [BSUID migration guide](/academy/ur/articles/migrate-contact-database-phone-number-to-bsuid/) میں ہے۔

Meta اپنے webhooks پر signature لگاتی ہے، اس لیے یہ function `auth: 'none'` کے ساتھ چلتا ہے، جسے Supabase کا auth صفحہ «کوئی بھی caller، کوئی چیک نہیں (signed webhooks کے لیے)» کہتا ہے۔ Function خود raw body پر `X-Hub-Signature-256` چیک کرتا ہے، جیسا کہ [X-Hub-Signature-256 verification](/academy/ur/articles/whatsapp-webhook-signature-verification-x-hub-signature-256/) میں ہے۔ ہم فرض کرتے ہیں کہ اس mode میں بھی `ctx.supabaseAdmin` موجود ہے، کیونکہ Supabase اسے صرف `secret` والی مثال میں دکھاتا ہے۔ پہلے اسے ٹیسٹ کریں۔

```ts
// supabase/functions/whatsapp-inbound/index.ts
// Meta webhook: verifies X-Hub-Signature-256, dedupes on the wamid, writes the tap to the order.
import { withSupabase } from 'npm:@supabase/server@1'

const APP_SECRET = Deno.env.get('APP_SECRET') ?? ''
const VERIFY_TOKEN = Deno.env.get('VERIFY_TOKEN') ?? ''
const WA_TOKEN = Deno.env.get('WA_TOKEN') ?? ''
const GRAPH_URL = `https://graph.facebook.com/v26.0/${Deno.env.get('PHONE_NUMBER_ID')}/messages`
const LABELS: Record<string, string> = { Today: 'today', Tomorrow: 'tomorrow', 'Cancel my order': 'cancel' }

async function validSignature(raw: Uint8Array, header: string | null): Promise<boolean> {
  if (!header || !header.startsWith('sha256=')) return false
  const key = await crypto.subtle.importKey(
    'raw', new TextEncoder().encode(APP_SECRET), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'],
  )
  const mac = new Uint8Array(await crypto.subtle.sign('HMAC', key, raw))
  const expected = 'sha256=' + Array.from(mac, (b) => b.toString(16).padStart(2, '0')).join('')
  if (expected.length !== header.length) return false
  let diff = 0
  for (let i = 0; i < expected.length; i++) diff |= expected.charCodeAt(i) ^ header.charCodeAt(i)
  return diff === 0
}

async function sendText(to: string, body: string) {
  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', to, type: 'text', text: { body } }),
  })
  if (!res.ok) console.error('reply failed', res.status, await res.text())
}

// deno-lint-ignore no-explicit-any
async function handleMessage(admin: any, msg: any) {
  const { error: seen } = await admin.from('wa_inbound').insert({ wamid: msg.id })
  if (seen && seen.code === '23505') return // Meta retried this webhook
  if (seen) throw seen

  if (msg.type === 'text' && msg.from && /^\s*stop\s*$/i.test(msg.text?.body ?? '')) {
    await admin.from('orders').update({ whatsapp_opt_in_at: null }).eq('phone', msg.from)
    return sendText(msg.from, 'You will not get order updates on WhatsApp anymore.')
  }
  if (msg.type !== 'button') return

  const [prefix, id, fromPayload] = String(msg.button?.payload ?? '').split('|')
  const lookup = admin.from('orders').select('id, order_number, phone, status')
  const { data: rows, error } = prefix === 'pk'
    ? await lookup.eq('id', Number(id))
    : await lookup.eq('wa_message_id', msg.context?.id ?? '') // payload not in our format
  if (error) throw error
  const order = rows?.[0]
  const action = prefix === 'pk' ? fromPayload : LABELS[msg.button?.text ?? '']
  if (!order || !action) return console.warn('unmatched tap', msg.id)
  if (msg.from && msg.from !== order.phone) return console.warn('tap from another number', msg.id)

  const change = action === 'cancel' ? { status: 'cancel_requested' } : { pickup_plan: action }
  const { data: done, error: writeError } = await admin
    .from('orders')
    .update({ ...change, updated_at: new Date().toISOString() })
    .eq('id', order.id)
    .eq('status', 'ready_for_pickup')
    .select('id')
  if (writeError) throw writeError
  if (!done || done.length === 0) {
    return sendText(order.phone, `Order ${order.order_number} can no longer be changed here. Reply with a message and our team will help.`)
  }
  const reply = action === 'cancel'
    ? `We received your request to cancel order ${order.order_number}. Our team will confirm it.`
    : `Thanks. We will have order ${order.order_number} ready for you ${action}.`
  return sendText(order.phone, reply)
}

export default {
  fetch: withSupabase({ auth: 'none' }, async (req, ctx) => {
    const url = new URL(req.url)
    if (req.method === 'GET') {
      const ok = url.searchParams.get('hub.mode') === 'subscribe' && url.searchParams.get('hub.verify_token') === VERIFY_TOKEN
      return ok ? new Response(url.searchParams.get('hub.challenge') ?? '') : new Response('forbidden', { status: 403 })
    }
    const raw = new Uint8Array(await req.arrayBuffer())
    if (!(await validSignature(raw, req.headers.get('x-hub-signature-256')))) {
      return new Response('bad signature', { status: 401 })
    }
    let body
    try {
      body = JSON.parse(new TextDecoder().decode(raw))
    } catch {
      return new Response('bad json', { status: 400 })
    }
    for (const entry of body.entry ?? []) {
      for (const change of entry.changes ?? []) {
        if (change.field !== 'messages') continue
        for (const msg of change.value?.messages ?? []) {
          await handleMessage(ctx.supabaseAdmin, msg).catch((err) => console.error('handler error', msg.id, String(err)))
        }
      }
    }
    return new Response('ok')
  }),
}
```

Write-back، ID کے ساتھ ساتھ `status = 'ready_for_pickup'` پر بھی filter کرتا ہے۔ پرانے پیغام پر ٹیپ، جب staff پہلے ہی order حوالے کر چکا ہو، کچھ نہیں بدلتا اور اس پر ایک مختصر جواب جاتا ہے۔ Cancel والا بٹن `cancelled` کی بجائے `cancel_requested` سیٹ کرتا ہے، تاکہ refund کا فیصلہ کوئی شخص کرے۔ اس تبدیلی پر trigger نہیں چلتا، کیونکہ اس کا `WHEN` clause صرف `ready_for_pickup` سے match کرتا ہے۔

جوابات free-form text ہیں۔ ان کی اجازت ہے کیونکہ ٹیپ نے 24 گھنٹے کی customer service ونڈو کھول دی تھی۔

یہی چکر Telegram کے لیے بھی کام کرتا ہے، فون کی بجائے linked chat ID کے ساتھ، جیسا کہ [order notifications کے لیے Telegram account linking](/academy/ur/articles/telegram-bot-link-account-order-notifications/) میں دکھایا گیا ہے۔

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

### pg_net کوئی request گرا دے

pg_net کوئی retries دستاویز نہیں کرتا۔ ناکامیاں `net._http_response` میں تلاش کریں، جہاں Supabase کا صفحہ `status_code >= 400` یا غیر null `error_msg` کی طرف اشارہ کرتا ہے۔ «Response واپس آنے کے بعد، بطورِ default یہ 6 گھنٹے تک محفوظ رہتا ہے»، اس لیے بار بار چیک کریں یا ناکامیوں کو کہیں اور کاپی کر لیں۔ یہ table، unlogged ہے، اور unlogged tables «crash یا unclean shutdown کے دوران» محفوظ نہیں رہتیں۔ Queue میں پڑی requests بھی اسی طرح ضائع ہو سکتی ہیں۔

```sql
select id, status_code, timed_out, error_msg, created
from net._http_response
where status_code >= 400 or error_msg is not null
order by created desc;
```

وہ claims بھی تلاش کریں جو کبھی مکمل نہیں ہوئے: `notified_at` سیٹ ہو اور چند منٹ بعد بھی `wa_message_id` null ہو۔ وہ row claim ہوئی تھی، پھر function، send سے پہلے یا اس کے دوران بند ہو گیا۔

pg_net والے راستے میں ناکام send، claim چھوڑ دیتا ہے، اور function کو دوبارہ کوئی کال نہیں کرتا۔ `notified_at` null والی `status = 'ready_for_pickup'` rows تلاش کریں، یا نیچے والی queue استعمال کریں۔

### جب کسی اطلاع کا ضائع ہونا اہم ہو تو queue استعمال کریں

اگر ہر اطلاع کا جانا ضروری ہے تو اسے اسی transaction میں queue میں لکھیں اور ایک worker کو بھیجنے دیں۔ Supabase Queues «pgmq database extension پر بنی ہیں»، اور «ایک Message، قابلِ ترتیب visibility window کے اندر کسی consumer کو ٹھیک ایک بار ڈیلیور ہوتا ہے» ([Supabase Queues](https://supabase.com/docs/guides/queues)، رسائی 2026-11-27)۔ یہ trigger، pg_net والے کی جگہ لیتا ہے۔ یہ اوپر والی tables کے بعد، `@electric-sql/pglite-pgmq` extension کے ساتھ PGlite پر چلتا ہے۔

```sql
create extension if not exists pgmq;
select pgmq.create('wa_notify');

create or replace function public.enqueue_pickup_ready()
returns trigger
language plpgsql
security definer
set search_path = ''
as $$
begin
  perform pgmq.send(queue_name => 'wa_notify', msg => jsonb_build_object('order_id', new.id));
  return new;
end;
$$;

create trigger enqueue_pickup_ready
after update of status on public.orders
for each row
when (old.status is distinct from new.status and new.status = 'ready_for_pickup')
execute function public.enqueue_pickup_ready();

-- Try it: the update enqueues one message, the read hides it for 30 seconds.
insert into public.orders (order_number, phone, store_name, whatsapp_opt_in_at)
values ('A-1042', '16505551234', 'Downtown store', now());
update public.orders set status = 'ready_for_pickup' where order_number = 'A-1042';
select msg_id, read_ct, message from pgmq.read(queue_name => 'wa_notify', vt => 30, qty => 10);
```

`notify-pickup` کو ایک schedule پر `{"drain": true}` کے ساتھ کال کریں۔ Drain، `pgmq_public` میں `read` اور `archive` wrappers کال کرتا ہے، جو [Supabase کے Queues API صفحے](https://supabase.com/docs/guides/queues/api) (رسائی 2026-11-27) پر دستاویزی ہیں۔ ان wrappers سے queues نہیں بنائی جا سکتیں، اس لیے `pgmq.create` SQL میں ہی رہتا ہے۔ یہ 60 سیکنڈ کے visibility timeout کے ساتھ پڑھتا ہے، بھیجتا ہے، پھر archive کرتا ہے۔ Archive سے پہلے crash کا مطلب ہے کہ پیغام timeout کے بعد واپس آ جائے گا، اس لیے دوسرا ٹیمپلیٹ روکنے والی چیز `notified_at` کا claim ہے۔ `FOR UPDATE SKIP LOCKED` والی سادہ outbox table بھی اسی طرح کام کرتی ہے، جیسا کہ [workers کے ساتھ webhook queue architecture](/academy/ur/articles/whatsapp-webhook-queue-architecture-workers/) میں دکھایا گیا ہے۔

### کسٹمر خاموش رہے

`pickup_plan` کو null رہنے دیں اور دوسرا ٹیمپلیٹ نہ بھیجیں۔ `status = 'ready_for_pickup' and pickup_plan is null` کے لیے staff کی روزانہ query، خاموشی کو کال کرنے والوں کی فہرست بنا دیتی ہے۔

### Meta کوئی ٹیپ دو بار ڈیلیور کرے

Meta ان webhooks کو retry کرتی ہے جنہیں وہ ناکام سمجھتی ہے، جیسا کہ [جب آپ کا webhook بند ہو تو Meta کیا کرتی ہے](/academy/ur/articles/whatsapp-webhook-retries-endpoint-down/) میں بتایا گیا ہے۔ `wa_inbound` کی primary key دوسری کاپی کو `23505` error کے ساتھ رد کر دیتی ہے، اور status والا filter منسوخی یا حوالگی کے بعد کسی بھی ٹیپ کو روک دیتا ہے۔ Today یا Tomorrow کا دوسرا ٹیپ پہلے کو overwrite کر دیتا ہے، اس لیے کسٹمر اپنا ارادہ بدل سکتا ہے۔ اگر insert کے بعد handler ناکام ہو جائے تو retry نظر انداز ہو جاتا ہے۔ اگر آپ ضائع شدہ ٹیپ کی بجائے کبھی کبھار دوہرا جواب بہتر سمجھتے ہیں تو insert کو write-back کے بعد لے جائیں۔

### کسٹمر STOP کا جواب دے

STOP والا جواب اس نمبر کے ہر order کا `whatsapp_opt_in_at` صاف کر دیتا ہے، اور `notify-pickup` کا claim رضامندی کے بغیر والی rows کو چھوڑ دیتا ہے۔ اسے وہاں ریکارڈ کریں جہاں سے آپ کا checkout رضامندی پڑھتا ہے، تاکہ اگلا order اسے دوبارہ آن نہ کر دے۔

### Local development

Local طور پر Postgres، Docker میں چلتا ہے، اس لیے trigger کو `localhost` نہیں، `host.docker.internal` کال کرنا چاہیے۔

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

Z-API Omni، `sendTemplate` میں Graph API کال کی جگہ لے سکتا ہے۔ ٹیمپلیٹس `content.type` `TEMPLATE` کے ساتھ `POST https://api.omni.z-api.io/v1/channels/{channelId}/messages` سے جاتے ہیں، صرف Meta Cloud API channels پر۔ Quick-reply payloads وہی `button` component استعمال کرتے ہیں، `sub_type` `quick_reply` کے ساتھ۔ جوابات `MESSAGE_RECEIVED` webhooks کے طور پر آتے ہیں: `x-webhook-signature` verify کریں اور `x-webhook-delivery-id` پر dedupe کریں۔ Docs میں ٹیمپلیٹ بٹن ٹیپ کا JSON نہیں دکھایا گیا، اور کوئی Supabase integration دستاویزی نہیں۔

QR connection پر `TEXT` یا `INTERACTIVE_BUTTON` پیغامات کسی بھی وقت جا سکتے ہیں۔ WhatsApp، Messenger، Instagram اور Telegram ایک ہی subscription میں آتے ہیں۔ ہر نمبر کی قیمت 1 سے 10 نمبروں کے لیے US$29 ماہانہ، 11 سے 50 کے لیے US$26، 51 سے 100 کے لیے US$23 اور 100 سے زیادہ پر US$20 ہے۔ آفیشل connection پر Meta کی فیس آگے منتقل ہوتی ہے۔

<!-- TODO:test Omni snippet: order_update_v1 template send copied from the docs; map the tap's MESSAGE_RECEIVED payload before porting whatsapp-inbound -->

```bash
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": "5511999999999" },
    "content": {
      "type": "TEMPLATE",
      "attachments": [
        {
          "template": {
            "name": "order_update_v1",
            "language": { "policy": "deterministic", "code": "en_US" },
            "components": [
              {
                "type": "body",
                "parameters": [
                  { "type": "text", "text": "Ana" },
                  { "type": "text", "text": "ORD-1024" },
                  { "type": "text", "text": "in transit" }
                ]
              }
            ]
          }
        }
      ]
    }
  }'
```

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

*Z-API Omni ٹیم*
