WhatsApp official API on Cloudflare Workers

Receive CRPRO Hub webhooks and reply on official WhatsApp with a Cloudflare Worker: request.text(), HMAC via crypto.subtle.verify, ctx.waitUntil and limits.

A Cloudflare Worker is a good CRPRO Hub webhook receiver: it has HTTPS ready, starts fast and uses Web Crypto to check the signature. It also has limits that change the design, mainly CPU time per request on the free plan and the number of subrequests. This article shows a complete Worker that validates the HMAC, answers 200 and sends the reply in the background, and explains what Cloudflare's documentation confirms about each piece.

The fetch handler and where secrets live

Short answer: the Worker exports an object with the method fetch(request, env, ctx). The request is the incoming request, env carries secrets and bindings, and ctx carries waitUntil. Secrets go in through wrangler secret put.

The Workers documentation defines the signature as export default { async fetch(request, env, ctx) {} } and notes the incoming request is immutable. request.text() returns the body as a string and request.arrayBuffer() as an ArrayBuffer; request.headers is a read-only Headers object. Create the API key in the Hub dashboard with the messages:send and webhooks:write scopes (authentication): it is shown only once. The whsec_ secret is also shown once, in the POST /api/v1/webhooks response.

npx wrangler secret put CRPRO_API_KEY npx wrangler secret put CRPRO_WEBHOOK_SECRET

How to validate the signature with crypto.subtle

Short answer: read the body with request.text(), build timestamp.delivery_id.body, import the secret with importKey as HMAC SHA-256 and call crypto.subtle.verify with the decoded signature. verify returns a promise of a boolean.

According to the documentation, crypto.subtle.importKey(format, keyData, algorithm, extractable, keyUsages) returns a CryptoKey, sign returns an ArrayBuffer and verify(algorithm, key, signature, data) returns a promise of a boolean; HMAC is listed as supported for sign, verify and importKey. There is also crypto.subtle.timingSafeEqual(a, b), described as a non-standard extension resistant to timing attacks. The example prefers verify because it does the computation and the comparison in one standard operation, and first checks that the header has 64 hexadecimal characters.

The Hub signs timestamp.delivery_id.body with HMAC SHA-256 and sends the X-Hub-Timestamp, X-Hub-Delivery-Id, X-Hub-Signature-Version and X-Hub-Signature-256 headers, the last as sha256=HEX. The read must be of the raw text: re-serializing already parsed JSON can change the result.

curl -X POST https://crprohub.com/api/v1/webhooks \ -H "Authorization: Bearer hub_pk_EXEMPLO_NAO_REAL" \ -H "Content-Type: application/json" \ -d '{"name":"Recebimento","url":"https://your-worker.your-subdomain.workers.dev","event_types":["message.received"]}'// src/index.js const codificador = new TextEncoder() async function assinaturaValida(request, corpo, segredo) { const recebido = (request.headers.get('x-hub-signature-256') ?? '').replace('sha256=', '') if (!/^[0-9a-f]{64}$/.test(recebido)) return false const assinado = request.headers.get('x-hub-timestamp') + '.' + request.headers.get('x-hub-delivery-id') + '.' + corpo const chave = await crypto.subtle.importKey( 'raw', codificador.encode(segredo), { name: 'HMAC', hash: 'SHA-256' }, false, ['verify'], ) const bytes = Uint8Array.from(recebido.match(/../g), (h) => parseInt(h, 16)) return crypto.subtle.verify('HMAC', chave, bytes, codificador.encode(assinado)) } async function responder(env, evento) { if (evento.event !== 'message.received' || !evento.data.text) return const resposta = await fetch( 'https://crprohub.com/api/v1/channels/' + evento.channel_id + '/messages', { method: 'POST', headers: { Authorization: 'Bearer ' + env.CRPRO_API_KEY, 'Content-Type': 'application/json', 'Idempotency-Key': 'resp-' + evento.data.message_id, }, body: JSON.stringify({ to: evento.data.from, type: 'text', text: { body: 'Recebemos sua mensagem.' }, }), }, ) if (resposta.status !== 202) console.error('CRPRO Hub', resposta.status, await resposta.text()) } export default { async fetch(request, env, ctx) { if (request.method !== 'POST') return new Response('metodo nao permitido', { status: 405 }) const corpo = await request.text() // texto cru, antes de qualquer JSON.parse if (!(await assinaturaValida(request, corpo, env.CRPRO_WEBHOOK_SECRET))) { return new Response('assinatura invalida', { status: 401 }) } const evento = JSON.parse(corpo) ctx.waitUntil(responder(env, evento)) // continua depois da resposta return new Response(null, { status: 200 }) }, }{ "id": "6f1f0f6a-3b2c-4d1e-9a8b-0c1d2e3f4a5b", "event": "message.received", "channel_id": "9f6a9c1e-2f3d-4a5b-8c7d-1e2f3a4b5c6d", "occurred_at": "2026-08-21T12:00:00.000Z", "data": { "message_id": "wamid.EXEMPLO123", "from": "5521999999999", "type": "text", "text": "Oi, ainda tem em estoque?" } }

How to reply in the background with ctx.waitUntil

Short answer: return 200 right away and pass the send promise to ctx.waitUntil(). The Hub expects a 2xx within 10 seconds, and waitUntil keeps the Worker alive to finish the send.

The context documentation says ctx.waitUntil() accepts a promise and keeps the Worker running after it returns the response, for up to 30 seconds in HTTP-triggered Workers, a limit shared by all waitUntil calls in the same request. Promises still pending after that are canceled, and a rejected promise does not stop the others. For work that does not fit, such as a slow AI model, the documentation recommends Queues. The send to the Hub is fast and fits comfortably.

  • The Idempotency-Key is mandatory and must be stable per message. Using the received message_id means a redelivery of the same event does not produce two replies: the same key with the same body returns the original response; with a different body, the Hub answers 409 IDEMPOTENCY_KEY_REUSED.
  • The 202 only says the Hub accepted and queued the message; the final state arrives through the message.status webhook.
  • The Hub limits are 60 messages per minute per channel and 120 requests per minute per organization and credential.

Worker limits that matter here

Short answer: on the free plan, CPU time is 10 ms per HTTP request and the limit is 50 subrequests; on the paid plan, the default is 30 seconds of CPU, with a 5-minute maximum, and 10,000 subrequests. The HMAC fits comfortably, but heavy code does not.

LimitWorkers FreeWorkers Paid
CPU time per HTTP request10 msdefault 30 s, maximum 5 min
Subrequests per invocation5010,000 by default

Each fetch to the Hub counts as a subrequest. Since the Worker makes one per event, the limit of 50 is no problem for this flow. The CPU limit measures processing, not network waiting, so waiting for the Hub response does not consume it. If your handling includes deduplication or history, use a Cloudflare or external data store, because the Worker keeps no state between invocations. The Hub repeats a delivery up to nine times over about four days and pauses the endpoint after 20 consecutive failures; the body id stays the same on retry and replay, and is the deduplication key.

How to test the Worker

Short answer: run npx wrangler dev, fire a request with a wrong signature and confirm the 401; then register the URL in the Hub and use POST /api/v1/webhooks/{id}/test to receive a truly signed event, up to 10 times per hour per endpoint.

# conferir localmente, sem o Hub (npx wrangler dev) curl -i -X POST http://localhost:8787 \ -H "X-Hub-Timestamp: 1" -H "X-Hub-Delivery-Id: d-1" \ -H "X-Hub-Signature-256: sha256=0000000000000000000000000000000000000000000000000000000000000000" \ -d '{"id":"e1","event":"webhook.test"}' # esperado: 401

If deliveries stop, reactivate the endpoint with PATCH /api/v1/webhooks/{id} and {"status":"active"}. Events during the pause generate no delivery; recover them with GET /api/v1/channels/{id}/messages and direction=inbound. The full rules are on the webhooks page, and the quickstart shows the first call.

Frequently asked questions

Does the free Workers plan handle the webhook?

To validate the HMAC and fire a send, generally yes: the computation is light. The free limit is 10 ms of CPU per HTTP request and 50 subrequests, according to the documentation, so avoid heavy code in the handler.

Should I use crypto.subtle.verify or timingSafeEqual?

The example uses verify, which does the computation and comparison in one standard operation. timingSafeEqual exists, but the documentation describes it as a non-standard extension.

How long does waitUntil keep the Worker alive?

Up to 30 seconds after the response, in HTTP-triggered Workers, shared among all waitUntil calls in the request.

How do I avoid replying twice to the same event?

Use the message_id as the Idempotency-Key on send and deduplicate on the event body id in a persistent store.

Fontes

Documentação oficial da Meta, conferida em 31 de outubro de 2026.