# Database Webhook di Supabase verso notifiche WhatsApp

> Invia un modello utility WhatsApp quando cambia una riga Supabase, con pg_net o una coda pgmq, poi riscrivi sulla stessa riga la risposta del cliente al pulsante.

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

Metti un trigger `AFTER UPDATE` sulla tabella, fagli chiamare una Edge Function tramite `net.http_post` e invia un modello utility da quella funzione. Il tocco del cliente su una risposta rapida torna a una seconda Edge Function, che verifica la firma di Meta e aggiorna la riga. Un Database Webhook di Supabase è un trigger Postgres che invia una richiesta HTTP tramite l'estensione pg_net dopo l'inserimento, l'aggiornamento o l'eliminazione di una riga.

L'esempio qui è una tabella `orders`. Quando `status` passa a `ready_for_pickup`, il cliente riceve un modello con tre pulsanti: Today (Oggi), Tomorrow (Domani) e Cancel my order (Annulla il mio ordine). Il tocco scrive `pickup_plan` o una richiesta di annullamento sull'ordine.

## Il ciclo dal cambio di riga alla riga aggiornata

1. Un aggiornamento cambia `status`, e un trigger con una clausola `WHEN` scatta una volta per quel cambio.
2. pg_net invia la riga vecchia e quella nuova alla Edge Function `notify-pickup` dopo il commit della transazione.
3. La funzione rivendica la riga, controlla il consenso e invia il modello `pickup_ready` tramite la WhatsApp Cloud API.
4. Il cliente tocca un pulsante, e Meta invia un messaggio `type: "button"` alla funzione `whatsapp-inbound`.
5. Quella funzione deduplica sull'ID del messaggio, controlla lo stato dell'ordine e scrive la risposta sulla riga.

Supabase descrive i Database Webhook come un modo per «inviare dati in tempo reale dal tuo database a un altro sistema ogni volta che si verifica un evento su una tabella». Sono un involucro attorno a trigger che usano pg_net, che «è asincrono, e quindi non bloccherà le modifiche al database per richieste di rete di lunga durata» ([Supabase Database Webhooks](https://supabase.com/docs/guides/database/webhooks), consultato il 2026-11-27).

## Le tabelle

La tabella `orders` contiene quello che serve al ciclo: un telefono E.164, la data del consenso, la rivendicazione dell'invio, l'ID del messaggio del modello e la risposta del cliente. `wa_inbound` salva ogni wamid in arrivo una sola volta, così un webhook ritentato non può applicare due volte lo stesso tocco. Queste istruzioni girano su qualsiasi Postgres, PGlite compreso.

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

Normalizza il telefono prima che arrivi alla riga, come mostra [la normalizzazione dei numeri E.164](/academy/it/articles/whatsapp-phone-number-format-e164-normalization/). Compila `whatsapp_opt_in_at` solo da una casella che nomina WhatsApp e lo scopo, come spiega [come raccogliere l'opt-in WhatsApp](/academy/it/articles/whatsapp-opt-in-how-to-collect-consent/).

## Il trigger e cosa invia

Il modulo della dashboard di Supabase genera un trigger su `supabase_functions.http_request`. Il suo esempio passa cinque argomenti posizionali, e la pagina non dà un nome agli ultimi due. Lo schema di migrazione documentato per chiamare una Edge Function è più chiaro: legge l'URL del progetto e una chiave segreta dal Vault e chiama `net.http_post` con argomenti nominati.

L'esempio di Supabase è un trigger `after insert` con `'old_record', null`. La versione qui sotto è il nostro adattamento per gli aggiornamenti. Invia `to_jsonb(old)` e aggiunge `WHEN (old.status is distinct from new.status)`, così gli aggiornamenti successivi ad altre colonne non lo fanno scattare. Questo blocco richiede Supabase, perché il Vault è una funzione di Supabase e pg_net non è nell'elenco delle estensioni di PGlite.

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

Ruoli come `authenticated` non possono leggere il Vault, quindi senza `security definer` i loro aggiornamenti falliscono con un errore di permessi. pg_net aspetta anche il commit: «le richieste HTTP non partono finché la transazione non è confermata» ([pg_net](https://supabase.com/docs/guides/database/extensions/pg_net), consultato il 2026-11-27). Un aggiornamento annullato con rollback non invia niente.

### La forma del payload

Supabase pubblica il payload come tipi TypeScript, non come esempio JSON. Un aggiornamento porta `type: 'UPDATE'`, `table`, `schema`, `record` e `old_record`. Abbiamo costruito l'esempio qui sotto da quei tipi, con valori della tabella `orders`.

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

### Come viene autenticata la richiesta

Supabase non firma i Database Webhook. Nessun header di firma è documentato, quindi l'unica prova di provenienza è l'header che aggiungi tu. Per una Edge Function, la documentazione dice di «accettarla nella funzione con `auth: 'secret'` e `verify_jwt = false`» ([Supabase Database Webhooks](https://supabase.com/docs/guides/database/webhooks), consultato il 2026-11-27). L'header `apikey` qui sopra porta quella chiave segreta.

La chiave non è nascosta mentre passa per il database. La pagina di Supabase dice che pg_net «scrive la chiave decifrata in net.http_request_queue finché non invia la richiesta», e qualsiasi ruolo che può fare login la può leggere mentre la richiesta è in attesa. Con il modulo della dashboard, la chiave «compare ovunque compaia l'SQL del trigger, per esempio in un dump del database». Una chiave dedicata con un nome, accettata con `auth: 'secret:<name>'`, tiene la chiave del trigger separata da quella usata dagli altri tuoi servizi.

Se il ricevitore è un servizio Node fuori da Supabase, aggiungi un tuo header `Authorization: Bearer <shared secret>` e confrontalo in tempo costante. Supabase non documenta un header del genere, quindi questo è nostro.

## Il messaggio e perché passa come utility

La pagina sulla categorizzazione di Meta dice che i modelli utility «di solito sono attivati da un'azione o una richiesta dell'utente». Devono essere non promozionali e o «specifici per l'utente o da lui richiesti» o «essenziali o critici» ([categorizzazione dei modelli](https://developers.facebook.com/documentation/business-messaging/whatsapp/templates/template-categorization), consultata il 2026-11-27). Un avviso di ritiro per un ordine fatto dal cliente supera entrambe le prove. L'esempio Order Management di Meta è vicino: «Il tuo ordine {{order_number}} è confermato. Ti avviseremo quando il pacco sarà in viaggio.»

Tieni fuori le offerte. Meta classifica come marketing i modelli con contenuti misti, «come un aggiornamento d'ordine con una promozione». Crea il modello una volta sola.

```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" }
        ]
      }
    ]
  }'
```

Al momento dell'invio, ogni pulsante di risposta rapida riceve un payload come `pk|1042|today`, così il tocco indica l'ordine. [Conferma d'ordine con i pulsanti Confirm e Cancel](/academy/it/articles/whatsapp-order-confirmation-confirm-cancel-buttons/) approfondisce il design dei pulsanti per i messaggi sugli ordini.

## La Edge Function che invia

Salvala come `supabase/functions/notify-pickup/index.ts`. Accetta il payload del trigger, oppure `{"drain": true}` per lavorare la coda descritta più avanti. La rivendicazione è un aggiornamento condizionale: torna solo una riga ancora in `ready_for_pickup`, con consenso e senza `notified_at`. Una seconda chiamata per lo stesso cambio non ottiene nulla e non invia nulla.

```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` aggira la row level security, quindi tieni questa funzione dietro la chiave segreta. Imposta `WA_TOKEN` e `PHONE_NUMBER_ID` come segreti della funzione. Le Edge Function hanno 2 secondi di tempo CPU e limiti di tempo reale di 150 secondi sul piano Free e 400 secondi sui piani a pagamento ([limiti delle Edge Function](https://supabase.com/docs/guides/functions/limits), consultato il 2026-11-27). Uno svuotamento di 10 invii sta comodamente dentro entrambi.

Le due funzioni di questo articolo saltano il controllo JWT del gateway, perché pg_net e Meta non inviano un JWT utente.

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

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

## La risposta che ricevi e la scrittura sulla riga

Un tocco su una risposta rapida di un modello arriva con `"type": "button"`. `button.payload` contiene il payload che hai impostato, e `context.id` è «l'ID del messaggio WhatsApp contenente il pulsante toccato dall'utente WhatsApp» ([riferimento del webhook button](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/reference/messages/button), consultato il 2026-11-27). L'esempio completo di Meta è in [promemoria di appuntamento WhatsApp con Confirm e Reschedule](/academy/it/articles/whatsapp-appointment-reminders-confirm-reschedule/). Ora porta `from_user_id` accanto a `from`, come spiega [la guida alla migrazione verso i BSUID](/academy/it/articles/migrate-contact-database-phone-number-to-bsuid/).

Meta firma i suoi webhook, quindi questa funzione gira con `auth: 'none'`, che la pagina sull'autenticazione di Supabase descrive come «Qualsiasi chiamante, nessun controllo (per webhook firmati)». La funzione controlla da sola `X-Hub-Signature-256` sul body grezzo, come in [verifica di X-Hub-Signature-256](/academy/it/articles/whatsapp-webhook-signature-verification-x-hub-signature-256/). Diamo per scontato che `ctx.supabaseAdmin` sia presente anche in questa modalità, dato che Supabase lo mostra solo nell'esempio `secret`. Verificalo per primo.

```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')
  }),
}
```

La scrittura filtra su `status = 'ready_for_pickup'` oltre che sull'ID. Un tocco su un messaggio vecchio, quando il personale ha già consegnato l'ordine, non cambia nulla e riceve una breve risposta. Il pulsante di annullamento imposta `cancel_requested` invece di `cancelled`, così è una persona a decidere sui rimborsi. Il trigger non scatta su quel cambio, perché la sua clausola `WHEN` corrisponde solo a `ready_for_pickup`.

Le risposte sono testo libero. Sono ammesse perché il tocco ha aperto una finestra di assistenza clienti di 24 ore.

Lo stesso ciclo funziona su Telegram con un chat ID collegato al posto del telefono, come mostra [collegare un account Telegram per le notifiche degli ordini](/academy/it/articles/telegram-bot-link-account-order-notifications/).

## Quando il ciclo si rompe

### pg_net perde una richiesta

pg_net non documenta nuovi tentativi. Trovi i fallimenti in `net._http_response`, dove la pagina di Supabase indica `status_code >= 400` o un `error_msg` non nullo. «Una volta restituita, di default una risposta viene conservata per 6 ore», quindi controlla spesso o copia altrove i fallimenti. La tabella è unlogged, e le tabelle unlogged non vengono conservate «in caso di crash o arresto non pulito». Le richieste in coda possono andare perse allo stesso modo.

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

Cerca anche le rivendicazioni mai concluse: `notified_at` impostato e `wa_message_id` ancora nullo dopo qualche minuto. Quella riga è stata rivendicata, poi la funzione si è fermata prima o durante l'invio.

Nel percorso pg_net, un invio fallito rilascia la rivendicazione, e nessuno richiama la funzione. Cerca `status = 'ready_for_pickup'` con `notified_at` nullo, oppure usa la coda qui sotto.

### Usa una coda quando un avviso perso conta

Se ogni avviso deve partire, scrivilo in una coda nella stessa transazione e lascia che un worker lo invii. Le Supabase Queues sono «costruite sull'estensione di database pgmq», e «un messaggio viene consegnato esattamente una volta a un consumatore entro una finestra di visibilità personalizzabile» ([Supabase Queues](https://supabase.com/docs/guides/queues), consultato il 2026-11-27). Questo trigger sostituisce quello con pg_net. Gira su PGlite con l'estensione `@electric-sql/pglite-pgmq`, dopo le tabelle qui sopra.

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

Chiama `notify-pickup` con `{"drain": true}` a intervalli programmati. Lo svuotamento chiama i wrapper `read` e `archive` in `pgmq_public`, documentati nella [pagina Queues API di Supabase](https://supabase.com/docs/guides/queues/api) (consultata il 2026-11-27). Le code non si possono creare tramite quei wrapper, quindi `pgmq.create` resta in SQL. Legge con un timeout di visibilità di 60 secondi, invia, poi archivia. Un crash prima dell'archiviazione fa tornare il messaggio dopo il timeout, quindi è la rivendicazione su `notified_at` a evitare un secondo modello. Una semplice tabella outbox con `FOR UPDATE SKIP LOCKED` funziona allo stesso modo, come mostra [architettura a coda per i webhook con worker](/academy/it/articles/whatsapp-webhook-queue-architecture-workers/).

### Il cliente non risponde

Lascia `pickup_plan` nullo e non inviare un secondo modello. Una query giornaliera del personale su `status = 'ready_for_pickup' and pickup_plan is null` trasforma il silenzio in una lista di chiamate.

### Meta consegna un tocco due volte

Meta ritenta i webhook che ritiene falliti, come spiega [cosa fa Meta quando il tuo webhook è giù](/academy/it/articles/whatsapp-webhook-retries-endpoint-down/). La chiave primaria di `wa_inbound` rifiuta la seconda copia con l'errore `23505`, e il filtro sullo stato blocca qualsiasi tocco dopo un annullamento o una consegna. Un secondo tocco su Today o Tomorrow sovrascrive il primo, così il cliente può cambiare idea. Se il gestore fallisce dopo l'inserimento, il nuovo tentativo viene ignorato. Sposta l'inserimento dopo la scrittura se preferisci una rara risposta doppia a un tocco perso.

### Un cliente risponde STOP

Una risposta STOP azzera `whatsapp_opt_in_at` per tutti gli ordini di quel numero, e la rivendicazione in `notify-pickup` salta le righe senza consenso. Registralo dove il tuo checkout legge il consenso, così l'ordine successivo non lo riattiva.

### Sviluppo locale

In locale Postgres gira in Docker, quindi un trigger deve chiamare `host.docker.internal`, non `localhost`.

## Dove si colloca Z-API Omni

Z-API Omni può sostituire la chiamata alla Graph API in `sendTemplate`. I modelli partono tramite `POST https://api.omni.z-api.io/v1/channels/{channelId}/messages` con `content.type` `TEMPLATE`, solo sui canali Meta Cloud API. I payload delle risposte rapide usano lo stesso componente `button` con `sub_type` `quick_reply`. Le risposte arrivano come webhook `MESSAGE_RECEIVED`: verifica `x-webhook-signature` e deduplica su `x-webhook-delivery-id`. La documentazione non mostra il JSON di un tocco su un pulsante di modello, e non è documentata un'integrazione con Supabase.

Sulla connessione QR, i messaggi `TEXT` o `INTERACTIVE_BUTTON` possono partire in qualsiasi momento. WhatsApp, Messenger, Instagram e Telegram sono inclusi in un solo abbonamento. Ogni numero costa US$29 al mese da 1 a 10 numeri, US$26 da 11 a 50, US$23 da 51 a 100 e US$20 oltre 100. Sulla connessione ufficiale le tariffe di Meta vengono riaddebitate.

<!-- 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" }
                ]
              }
            ]
          }
        }
      ]
    }
  }'
```

[Vedi la documentazione](https://developer.omni.z-api.io/en)

*Il team di Z-API Omni*
