WhatsApp· 7 min di lettura

Ricevere i webhook di WhatsApp su Cloudflare Workers


Un Worker riceve i webhook di WhatsApp nel suo handler fetch. Un GET restituisce hub.challenge quando il verify token corrisponde. Un POST legge il corpo grezzo con request.arrayBuffer() e verifica X-Hub-Signature-256 con crypto.subtle.verify. Poi attende l’invio di un messaggio Cloudflare Queues per ogni messaggio o stato e restituisce 200. Lo stesso Worker consuma la coda, deduplica per ID del messaggio e fa il lavoro. Usa una coda invece di ctx.waitUntil(), perché il lavoro in waitUntil viene annullato dopo 30 secondi e Meta non reinvia dopo un 200.

Creare il Worker e la coda

npm create cloudflare@latest -- whatsapp-webhook
cd whatsapp-webhook
npx wrangler queues create whatsapp-events

Scegli un Worker TypeScript quando il setup te lo chiede. I comandi seguono la guida ai Workers e la guida alle Queues di Cloudflare (entrambe consultate il 2026-11-04).

Sostituisci il wrangler.jsonc generato con questo. Il Worker è sia producer sia consumer di whatsapp-events.

{
  "name": "whatsapp-webhook",
  "main": "src/index.ts",
  "compatibility_date": "2026-11-04",
  "queues": {
    "producers": [{ "queue": "whatsapp-events", "binding": "WHATSAPP_EVENTS" }],
    "consumers": [{ "queue": "whatsapp-events", "max_batch_size": 10, "max_batch_timeout": 5 }]
  }
}

Cloudflare dice che quando avvii un progetto «dovresti sempre impostare compatibility_date alla data corrente» (date di compatibilità, consultato il 2026-11-04). Esegui npx wrangler types dopo aver modificato la configurazione. Rigenera worker-configuration.d.ts, un file che non dovresti modificare a mano (TypeScript nei Workers).

Il Worker

// src/index.ts
type WaMessage = {
  id: string
  from?: string
  from_user_id?: string
  timestamp: string
  type: string
  text?: { body: string }
}

type WaStatus = {
  id: string
  status: string
  recipient_id?: string
  recipient_user_id?: string
  errors?: unknown[]
}

type WaPayload = {
  object?: string
  entry?: Array<{
    changes?: Array<{
      field?: string
      value?: {
        metadata?: { phone_number_id?: string }
        messages?: WaMessage[]
        statuses?: WaStatus[]
      }
    }>
  }>
}

type WaEvent =
  | { kind: 'message'; phoneNumberId: string; message: WaMessage }
  | { kind: 'status'; phoneNumberId: string; status: WaStatus }

interface WebhookEnv {
  WHATSAPP_APP_SECRET: string
  WHATSAPP_VERIFY_TOKEN: string
  WHATSAPP_EVENTS: Queue<WaEvent>
}

const seen = new Set<string>() // demo dedupe in one isolate; use a unique key in your database

function hexToBytes(hex: string) {
  if (!/^[0-9a-fA-F]{64}$/.test(hex)) return null // SHA-256 is 32 bytes, 64 hex characters
  const bytes = new Uint8Array(32)
  for (let i = 0; i < 32; i++) bytes[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16)
  return bytes
}

async function validSignature(secret: string, body: ArrayBuffer, header: string | null): Promise<boolean> {
  if (header === null || !header.startsWith('sha256=')) return false
  const signature = hexToBytes(header.slice('sha256='.length))
  if (signature === null) return false
  const key = await crypto.subtle.importKey(
    'raw',
    new TextEncoder().encode(secret),
    { name: 'HMAC', hash: 'SHA-256' },
    false,
    ['verify'],
  )
  return crypto.subtle.verify('HMAC', key, signature, body)
}

function toEvents(payload: WaPayload): WaEvent[] {
  const events: WaEvent[] = []
  if (payload.object !== 'whatsapp_business_account') return events
  for (const entry of payload.entry ?? []) {
    for (const change of entry.changes ?? []) {
      if (change.field !== 'messages' || change.value === undefined) continue
      const phoneNumberId = change.value.metadata?.phone_number_id ?? ''
      for (const message of change.value.messages ?? []) events.push({ kind: 'message', phoneNumberId, message })
      for (const status of change.value.statuses ?? []) events.push({ kind: 'status', phoneNumberId, status })
    }
  }
  return events
}

function dedupeKey(event: WaEvent): string {
  return event.kind === 'message'
    ? `msg:${event.message.id}`
    : `status:${event.status.id}:${event.status.status}`
}

function handle(event: WaEvent): void {
  if (event.kind === 'message') {
    const msg = event.message
    // Meta omits `from` when it cannot include the phone number; fall back to the BSUID
    const sender = msg.from ?? msg.from_user_id
    const text = msg.type === 'text' ? msg.text?.body : `[${msg.type}]`
    console.log(`message ${msg.id} to ${event.phoneNumberId} from ${sender}: ${text}`)
  } else {
    const st = event.status
    console.log(`status ${st.status} for ${st.id} to ${st.recipient_id ?? st.recipient_user_id}`)
    if (st.status === 'failed') console.log(JSON.stringify(st.errors))
  }
}

export default {
  async fetch(request, env): Promise<Response> {
    if (request.method === 'GET') {
      const params = new URL(request.url).searchParams
      const challenge = params.get('hub.challenge')
      const valid =
        env.WHATSAPP_VERIFY_TOKEN !== '' &&
        params.get('hub.mode') === 'subscribe' &&
        params.get('hub.verify_token') === env.WHATSAPP_VERIFY_TOKEN &&
        challenge !== null
      if (!valid) return new Response(null, { status: 403 })
      return new Response(challenge, { status: 200, headers: { 'Content-Type': 'text/plain' } })
    }
    if (request.method !== 'POST') {
      return new Response(null, { status: 405, headers: { Allow: 'GET, POST' } })
    }
    if (!env.WHATSAPP_APP_SECRET) return new Response('WHATSAPP_APP_SECRET is not set', { status: 500 })

    const body = await request.arrayBuffer() // the exact bytes Meta signed
    if (!(await validSignature(env.WHATSAPP_APP_SECRET, body, request.headers.get('x-hub-signature-256')))) {
      return new Response(null, { status: 401 })
    }

    let payload: WaPayload
    try {
      payload = JSON.parse(new TextDecoder().decode(body)) as WaPayload
    } catch {
      return new Response(null, { status: 400 })
    }

    const events = toEvents(payload)
    try {
      // One small message per event: a queue message is capped at 128 KB, a webhook at 3 MB.
      // sendBatch takes up to 100 messages (or 256 KB in total) per call.
      for (let i = 0; i < events.length; i += 100) {
        await env.WHATSAPP_EVENTS.sendBatch(events.slice(i, i + 100).map((event) => ({ body: event })))
      }
    } catch (err) {
      console.error('enqueue failed', err)
      return new Response(null, { status: 500 }) // non-200, so Meta retries
    }
    return new Response(null, { status: 200 })
  },

  async queue(batch): Promise<void> {
    for (const msg of batch.messages) {
      const key = dedupeKey(msg.body)
      if (seen.has(key)) {
        msg.ack()
        continue
      }
      try {
        handle(msg.body)
        seen.add(key)
        msg.ack()
      } catch (err) {
        console.error('handler failed', err)
        msg.retry()
      }
    }
  },
} satisfies ExportedHandler<WebhookEnv, WaEvent>

L’interfaccia WebhookEnv dà un tipo ai due segreti e al binding della coda. L’esempio introduttivo di Cloudflare usa il segnaposto env.<MY_QUEUE>, che non compila, quindi il codice usa il binding reale, env.WHATSAPP_EVENTS. Un solo handler fetch serve tutti i metodi, quindi tutto ciò che non è GET o POST riceve 405.

Verificare la firma con Web Crypto

Meta definisce l’header come un «hash HMAC-SHA256, calcolato usando il payload del corpo del post e il tuo app secret come chiave segreta». Lo confronti con «tutto ciò che segue sha256=» (Meta, creare un endpoint webhook, consultato il 2026-11-04). Il Worker calcola l’hash dei byte di arrayBuffer() e li decodifica per JSON.parse solo dopo che la verifica è passata.

Le chiamate a importKey e verify seguono l’esempio di firma delle richieste di Cloudflare (consultato il 2026-11-04). Quell’esempio sconsiglia di calcolare l’HMAC e confrontare stringhe, perché «i confronti tra stringhe si interrompono alla prima differenza».

L’esempio decodifica una firma base64 con Buffer. Meta invia esadecimale, quindi hexToBytes fa quella conversione senza import. Rifiuta anche tutto ciò che non sia esattamente 64 caratteri esadecimali. Cloudflare non documenta cosa fa verify con una firma di lunghezza sbagliata, quindi il codice non gliene passa mai una. Un header mancante, corto o malformato restituisce 401.

I Workers documentano anche crypto.subtle.timingSafeEqual, un’estensione non standard. I suoi buffer «devono avere la stessa lunghezza, altrimenti viene sollevata un’eccezione» (esempio sugli attacchi di timing, consultato il 2026-11-04). Inoltre «non è a tempo costante rispetto alla lunghezza dei parametri». Con verify non devi gestire nessuno dei due casi.

Se preferisci condividere codice Node, funziona anche node:crypto. Con una data di compatibilità uguale o successiva al 2026-08-04, i Workers attivano nodejs_compat per default (compatibilità Node.js dei Workers, consultato il 2026-11-04). La versione Next.js mostra createHmac con timingSafeEqual. La guida alla verifica della firma spiega perché un corpo riserializzato non supera la verifica dell’hash.

ctx.waitUntil o una coda

Meta non pubblica una scadenza di risposta in secondi. Con qualsiasi stato diverso da 200 ritenta «con frequenza decrescente finché la richiesta non va a buon fine, per un massimo di 7 giorni» (Meta, panoramica dei webhook, consultato il 2026-11-04). «Questi nuovi tentativi possono generare notifiche webhook duplicate.» Rispondi 200 in fretta, poi fai il lavoro in un posto dove il 200 non può fartelo perdere.

ctx.waitUntil() Cloudflare Queues
Tempo dopo la risposta Fino a 30 s, condivisi da tutte le chiamate della richiesta Il consumer gira fino a 15 min di tempo reale per batch
Quando il lavoro fallisce Le promise non risolte vengono annullate dopo 30 s Il messaggio viene ritentato, 3 volte per default
Dopo il 200 di Meta Il lavoro annullato è perso Il messaggio è su disco appena send() si risolve

La riga di waitUntil viene dalla pagina Context di Cloudflare, che suggerisce essa stessa di «inviare messaggi a una Queue ed elaborarli in un Worker consumer separato». Questo articolo tiene producer e consumer in un solo Worker, come fa l’esempio introduttivo delle Queues di Cloudflare. Le righe delle Queues vengono dalle pagine API JavaScript, batching e nuovi tentativi e limiti (tutte consultate il 2026-11-04). Su send(), Cloudflare scrive: «Quando la promise si risolve, il messaggio risulta confermato come scritto su disco.» Il Worker attende ogni chiamata a sendBatch() prima di restituire 200, quindi una scrittura fallita diventa un 500 che Meta ritenta.

waitUntil va bene per i log e per altro lavoro che puoi permetterti di perdere. Tutto il resto, se va perso dopo il 200, resta perso, perché «non esistono API per recuperare dati storici dei webhook» (Meta, creare un endpoint webhook). Architettura a coda per i webhook descrive la stessa separazione fuori da Cloudflare.

Perché un messaggio di coda per evento

Un messaggio di coda è limitato a 128 KB (limiti delle Queues). Meta dice che «i payload dei webhook possono arrivare fino a 3 MB», quindi il corpo grezzo non sempre ci sta. Un POST porta anche fino a 1000 aggiornamenti, e «il raggruppamento non può essere garantito». Il Worker invia un messaggio di coda per ogni elemento di messages[] o statuses[], con il phone_number_id su cui è arrivato. Li raggruppa in chiamate sendBatch da 100, il massimo per chiamata. Una chiamata è limitata anche a 256 KB in totale, quindi usa blocchi più piccoli se i tuoi eventi sono grandi.

Se un invio fallisce, il Worker restituisce 500 e Meta ritenta l’intero POST. Gli eventi già accodati arrivano allora due volte, e la deduplicazione del consumer li assorbe. Se ti serve anche il corpo grezzo, salva i payload più grandi altrove e accoda un riferimento.

Il consumer: ack, retry, deduplicazione

Ogni messaggio del batch viene confermato singolarmente. Se l’handler solleva un errore senza ack() per messaggio, «l’intero batch viene ritentato» (batching e nuovi tentativi). retry() rimette un messaggio in coda per un batch successivo. Esauriti i tentativi, la consegna viene marcata come fallita, oppure scritta in una dead letter queue se ne configuri una.

I duplicati arrivano da due direzioni. I nuovi tentativi di Meta reinviano gli eventi, e le Queues «forniscono per default una consegna at least once» (garanzie di consegna, consultato il 2026-11-04). Il consumer usa come chiave il wamid in id per i messaggi e id più status per gli stati. Il Set vive in un solo isolate, quindi sostituiscilo con una chiave univoca nel tuo database. Nuovi tentativi dei webhook copre il lato dei retry.

L’handler legge il mittente come from ?? from_user_id e il destinatario dello stato come recipient_id ?? recipient_user_id. Meta dice che from «viene omesso se il numero di telefono non può essere incluso». Per gli stati, recipient_id «viene impostato sul numero di telefono dell’utente, se hai inviato il messaggio al numero di telefono dell’utente» (Meta, business-scoped user ID, consultato il 2026-11-04). recipient_user_id porta il BSUID.

Limiti di CPU e di tempo

Il tempo di CPU per richiesta HTTP è di 10 ms su Workers Free. Su Workers Paid il default è 30 secondi, e limits.cpu_ms nella configurazione lo porta fino a 5 minuti (limiti dei Workers, consultato il 2026-11-04). Il tempo passato ad aspettare richieste di rete non conta come tempo di CPU. Il limite del corpo della richiesta parte da 100 MB, ben sopra i 3 MB di Meta.

Un Worker oltre il suo limite di CPU fallisce con l’Error 1102, “Worker exceeded resource limits”. Cloudflare non pubblica un valore per una singola verifica HMAC, quindi sul piano Free tieni d’occhio il tempo di CPU nei log.

Provare in locale, poi fare il deploy

Il Worker legge due segreti. WHATSAPP_APP_SECRET è l’app secret della tua app Meta. WHATSAPP_VERIFY_TOKEN è una stringa qualsiasi che scegli tu e inserisci nell’App Dashboard. Per le esecuzioni in locale, crea .dev.vars accanto a wrangler.jsonc e tienilo fuori dal controllo di versione (segreti dei Workers, consultato il 2026-11-04).

WHATSAPP_APP_SECRET="APP_SECRET"
WHATSAPP_VERIFY_TOKEN="VERIFY_TOKEN"

Avvia npx wrangler dev, che serve il Worker su http://localhost:8787. In un secondo terminale, esporta gli stessi due valori. Poi controlla il GET e invia l’esempio di webhook di testo di Meta, compattato su una riga e firmato con il tuo app secret.

curl -i "http://localhost:8787/?hub.mode=subscribe&hub.challenge=12345&hub.verify_token=$WHATSAPP_VERIFY_TOKEN"

cat > sample.json <<'EOF'
{"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"}],"messages":[{"from":"16505551234","id":"wamid.HBgLMTY1MDM4Nzk0MzkVAgASGBQzQTRBNjU5OUFFRTAzODEwMTQ0RgA=","timestamp":"1749416383","type":"text","text":{"body":"Does it come in another color?"}}]},"field":"messages"}]}]}
EOF
SIG=$(openssl dgst -sha256 -hmac "$WHATSAPP_APP_SECRET" sample.json | awk '{print $NF}')
curl -i -X POST http://localhost:8787/ \
  -H "Content-Type: application/json" \
  -H "X-Hub-Signature-256: sha256=$SIG" \
  --data-binary @sample.json

Il GET restituisce 12345 e il POST restituisce 200. Le Queues funzionano sotto wrangler dev, dove «il tuo Worker e le risorse vengono simulati in locale tramite Miniflare» (sviluppo in locale delle Queues, consultato il 2026-11-04). Entro il timeout del batch il consumer registra il messaggio. Un secondo POST identico non registra nulla. Cambia un carattere in sample.json senza firmarlo di nuovo e il Worker restituisce 401.

npx wrangler deploy
npx wrangler secret put WHATSAPP_APP_SECRET
npx wrangler secret put WHATSAPP_VERIFY_TOKEN

Una volta impostati, «i valori dei segreti non sono visibili in Wrangler né nella dashboard di Cloudflare». Senza l’app secret il POST risponde 500, e senza il verify token il GET risponde 403. Imposta l’URL di callback sull’URL HTTPS del Worker nell’App Dashboard e iscriviti al campo messages.

Il team di Z-API Omni