Put an AFTER UPDATE trigger on the table, let it call an Edge Function through net.http_post, and send a utility template from that function. The customer’s quick-reply tap comes back to a second Edge Function, which verifies Meta’s signature and updates the row. A Supabase Database Webhook is a Postgres trigger that sends an HTTP request through the pg_net extension after a row is inserted, updated or deleted.
The example here is an orders table. When status moves to ready_for_pickup, the customer gets a template with three buttons: Today, Tomorrow and Cancel my order. The tap writes pickup_plan or a cancellation request back to the order.
The loop from row change to updated row
- A row update changes
status, and a trigger with aWHENclause fires once for that change. - pg_net posts the old and new row to the
notify-pickupEdge Function after the transaction commits. - The function claims the row, checks consent and sends the
pickup_readytemplate through the WhatsApp Cloud API. - The customer taps a button, and Meta posts a
type: "button"message to thewhatsapp-inboundfunction. - That function dedupes on the message ID, checks the order state and writes the answer to the row.
Supabase describes Database Webhooks as a way to “send real-time data from your database to another system whenever a table event occurs.” They are a wrapper around triggers that use pg_net, which “is asynchronous, and therefore will not block your database changes for long-running network requests” (Supabase Database Webhooks, accessed 2026-11-27).
The tables
The orders table carries what the loop needs: an E.164 phone, the consent timestamp, the send claim, the template’s message ID and the customer’s answer. wa_inbound stores every inbound wamid once, so a retried webhook can’t apply a tap twice. These statements run on any Postgres, PGlite included.
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()
);
Normalize the phone before it reaches the row, as shown in E.164 phone number normalization. Fill whatsapp_opt_in_at only from a checkbox that names WhatsApp and the purpose, as covered in how to collect WhatsApp opt-in.
The trigger and what it sends
Supabase’s dashboard form generates a trigger on supabase_functions.http_request. Its example passes five positional arguments, and the page doesn’t label the last two. The documented migration pattern for calling an Edge Function is clearer: it reads the project URL and a secret key from Vault and calls net.http_post with named arguments.
Supabase’s example is an after insert trigger with 'old_record', null. The version below is our adaptation for updates. It sends to_jsonb(old) and adds WHEN (old.status is distinct from new.status), so later updates to other columns don’t fire it. This block needs Supabase, because Vault is a Supabase feature and pg_net isn’t in PGlite’s extension list.
-- 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();
Roles such as authenticated can’t read Vault, so without security definer their updates fail with a permission error. pg_net also waits for the commit: “HTTP requests are not started until the transaction is committed” (pg_net, accessed 2026-11-27). A rolled-back update sends nothing.
The payload shape
Supabase publishes the payload as TypeScript types, not as a JSON sample. An update carries type: 'UPDATE', table, schema, record and old_record. We built the sample below from those types, with values from the orders table.
{
"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"
}
}
How the request is authenticated
Supabase doesn’t sign Database Webhooks. No signature header is documented, so the only proof of origin is the header you add. For an Edge Function, the docs say to “accept it in the function with auth: 'secret' and verify_jwt = false” (Supabase Database Webhooks, accessed 2026-11-27). The apikey header above carries that secret key.
The key isn’t hidden in transit through the database. Supabase’s rendered page says pg_net “writes the decrypted key to net.http_request_queue until it sends the request”, and any role that can log in can read it while the request waits. With the dashboard form, the key “appears anywhere the trigger’s SQL does, such as a database dump.” A dedicated named key, accepted with auth: 'secret:<name>', keeps the trigger’s key separate from the one your other services use.
If the receiver is a Node service outside Supabase, add your own Authorization: Bearer <shared secret> header and compare it in constant time. Supabase documents no such header, so this one is ours.
The message and why it passes as utility
Meta’s categorization page says utility templates “are typically triggered by a user action or request.” They must be non-promotional and either “specific to or requested by the user” or “essential or critical” (template categorization, accessed 2026-11-27). A pickup notice for an order the customer placed meets both tests. Meta’s Order Management example is close: “Your order {{order_number}} is confirmed. We will let you know once your package is on its way.”
Keep offers out of it. Meta classes templates with mixed content, “such as an order update with a promo”, as marketing. Create the template once.
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" }
]
}
]
}'
At send time, each quick-reply button gets a payload such as pk|1042|today, so the tap names the order. Order confirmation with Confirm and Cancel buttons covers button design for order messages in more depth.
The Edge Function that sends
Save this as supabase/functions/notify-pickup/index.ts. It accepts the trigger payload, or {"drain": true} to work the queue described further down. The claim is a conditional update: only a row still in ready_for_pickup, with consent and no notified_at, comes back. A second call for the same change gets nothing and sends nothing.
// 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 bypasses row level security, so keep this function behind the secret key. Set WA_TOKEN and PHONE_NUMBER_ID as function secrets. Edge Functions have 2 seconds of CPU time, and wall clock limits of 150 seconds on Free and 400 seconds on paid plans (Edge Function limits, accessed 2026-11-27). A drain of 10 sends fits well inside both.
Both functions in this post skip the gateway’s JWT check, because pg_net and Meta don’t send a user JWT.
[functions.notify-pickup]
verify_jwt = false
[functions.whatsapp-inbound]
verify_jwt = false
The reply you receive and the write-back
A quick-reply tap on a template arrives with "type": "button". button.payload holds the payload you set, and context.id is the “WhatsApp message ID of the message containing the button the WhatsApp user tapped” (button webhook reference, accessed 2026-11-27). Meta’s full sample is in WhatsApp appointment reminders with Confirm and Reschedule. It now carries from_user_id next to from, which the BSUID migration guide explains.
Meta signs its webhooks, so this function runs with auth: 'none', which the Supabase auth page describes as “Any caller, no check (for signed webhooks).” The function checks X-Hub-Signature-256 against the raw body itself, as in X-Hub-Signature-256 verification. We assume ctx.supabaseAdmin is present in this mode too, since Supabase shows it only in the secret example. Test that first.
// 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')
}),
}
The write-back filters on status = 'ready_for_pickup' as well as the ID. A tap on a stale message, after staff already handed the order over, changes nothing and gets a short reply. The cancel button sets cancel_requested rather than cancelled, so a person decides on refunds. The trigger doesn’t fire on that change, because its WHEN clause only matches ready_for_pickup.
The replies are free-form text. They are allowed because the tap opened a 24-hour customer service window.
The same loop works for Telegram with a linked chat ID instead of a phone, as shown in Telegram account linking for order notifications.
When the loop breaks
pg_net drops a request
pg_net documents no retries. Find failures in net._http_response, where Supabase’s page points to status_code >= 400 or a non-null error_msg. “Once a response is returned, by default, it is stored for 6 hours,” so check often or copy failures out. The table is unlogged, and unlogged tables are not preserved “during a crash or unclean shutdown.” Queued requests can be lost the same way.
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;
Also find claims that never finished: notified_at set and wa_message_id still null after a few minutes. That row was claimed, then the function died before or during the send.
In the pg_net path, a failed send releases the claim, and nothing calls the function again. Look for status = 'ready_for_pickup' with notified_at null, or use the queue below.
Use a queue when a lost notice matters
If every notice must go out, write it to a queue in the same transaction and let a worker send it. Supabase Queues are “built on the pgmq database extension”, and “A Message is delivered exactly once to a consumer within a customizable visibility window” (Supabase Queues, accessed 2026-11-27). This trigger replaces the pg_net one. It runs on PGlite with the @electric-sql/pglite-pgmq extension, after the tables above.
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);
Call notify-pickup with {"drain": true} on a schedule. The drain calls the read and archive wrappers in pgmq_public, documented on Supabase’s Queues API page (accessed 2026-11-27). Queues can’t be created through those wrappers, so pgmq.create stays in SQL. It reads with a 60-second visibility timeout, sends, then archives. A crash before the archive means the message comes back after the timeout, so the notified_at claim is what stops a second template. A plain outbox table with FOR UPDATE SKIP LOCKED works the same way, as shown in webhook queue architecture with workers.
The customer stays silent
Leave pickup_plan null and don’t send a second template. A daily staff query for status = 'ready_for_pickup' and pickup_plan is null turns silence into a call list.
Meta delivers a tap twice
Meta retries webhooks it thinks failed, as covered in what Meta does when your webhook is down. The wa_inbound primary key rejects the second copy with error 23505, and the status filter stops any tap after a cancellation or handover. A second Today or Tomorrow tap overwrites the first, so the customer can change their mind. If the handler fails after the insert, the retry is ignored. Move the insert after the write-back if you prefer a rare double reply to a lost tap.
A customer replies STOP
A reply of STOP clears whatsapp_opt_in_at for every order on that number, and the claim in notify-pickup skips rows without consent. Record it where your checkout reads consent, so the next order doesn’t switch it back on.
Local development
Postgres runs in Docker locally, so a trigger must call host.docker.internal, not localhost.
Where Z-API Omni fits
Z-API Omni can replace the Graph API call in sendTemplate. Templates go out through POST https://api.omni.z-api.io/v1/channels/{channelId}/messages with content.type TEMPLATE, on Meta Cloud API channels only. Quick-reply payloads use the same button component with sub_type quick_reply. Replies arrive as MESSAGE_RECEIVED webhooks: verify x-webhook-signature and dedupe on x-webhook-delivery-id. The docs don’t show the JSON of a template button tap, and no Supabase integration is documented.
On the QR connection, TEXT or INTERACTIVE_BUTTON messages can go out at any time. WhatsApp, Messenger, Instagram and Telegram come in one subscription. Each number costs US$29 per month for 1 to 10 numbers, US$26 for 11 to 50, US$23 for 51 to 100 and US$20 above 100. Meta’s fees are passed through on the official connection.
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" }
]
}
]
}
}
]
}
}'
Z-API Omni team