> ## Documentation Index
> Fetch the complete documentation index at: https://docs.cardapioweb.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Exemplo de integração

> Exemplo em Node.js de validação HMAC, armazenamento em SQLite, deduplicação e testes para os webhooks de cobrança.

Este exemplo recebe os webhooks de cobrança da CW, valida a assinatura e grava o evento antes de responder. Ele separa a **recepção durável** do **processamento das regras do seu app**.

Os arquivos `webhook.mjs`, `simulate.mjs` e `webhook.test.mjs` estão nesta página. Você pode copiá-los sem acesso ao repositório da Cardápio Web.

## Pré-requisitos

* Node.js **22.23 ou superior**, com suporte a `node:sqlite`.
* Um arquivo SQLite persistente e gravável pelo processo.
* ID e `webhook_token` fictícios para a simulação local; na integração com a CW, use o ID e o token que seu app já possui.
* Para receber eventos da CW: adapte o endpoint HTTPS já cadastrado no app.

Não há dependências npm para este exemplo. `node:sqlite` ainda é experimental na versão Node.js 22 usada para validá-lo. Para produção, adapte a inbox ao banco e à estratégia de execução que sua aplicação já utiliza.

## Código completo

Crie uma pasta local e salve os três arquivos abaixo nela, mantendo os nomes e a extensão `.mjs`. Cada bloco permite copiar o conteúdo completo.

> [accordion] webhook.mjs
>
> ```javascript webhook.mjs theme={null}
> import { createHmac, timingSafeEqual } from 'node:crypto';
> import { createServer } from 'node:http';
> import { DatabaseSync } from 'node:sqlite';
> import { pathToFileURL } from 'node:url';
>
> const EVENT_TYPES = new Set([
>   'MARKETPLACE_APP_BILLING_STATUS_UPDATED',
>   'MARKETPLACE_APP_PAYMENT_SUCCEEDED',
>   'MARKETPLACE_APP_ACCESS_UPDATED',
> ]);
> const MAX_BODY_BYTES = 256 * 1024;
> const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
> const positiveInteger = value => Number.isSafeInteger(value) && value > 0;
> const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
> const instant = value => typeof value === 'string' && Number.isFinite(Date.parse(value));
>
> export class RequestError extends Error {
>   constructor(status, message) {
>     super(message);
>     this.status = status;
>   }
> }
>
> export function verifySignature(rawBody, headers, secret, now = Date.now()) {
>   const timestamp = headers['x-cardapio-timestamp'];
>   const signature = headers['x-cardapio-signature'];
>   if (typeof timestamp !== 'string' || !/^\d+$/.test(timestamp) ||
>       typeof signature !== 'string' || !/^v1=[0-9a-f]{64}$/.test(signature)) {
>     throw new RequestError(401, 'Assinatura inválida');
>   }
>   const seconds = Number(timestamp);
>   if (!Number.isSafeInteger(seconds) || Math.abs(Math.floor(now / 1000) - seconds) > 300) {
>     throw new RequestError(401, 'Timestamp fora da janela');
>   }
>   const expected = createHmac('sha256', secret)
>     .update(timestamp + '.')
>     .update(rawBody)
>     .digest();
>   const provided = Buffer.from(signature.slice(3), 'hex');
>   if (provided.length !== expected.length || !timingSafeEqual(provided, expected)) {
>     throw new RequestError(401, 'Assinatura inválida');
>   }
> }
>
> export function parseEvent(rawBody, headers, expectedAppId) {
>   let event;
>   try {
>     event = JSON.parse(rawBody.toString('utf8'));
>   } catch {
>     throw new RequestError(400, 'JSON inválido');
>   }
>   if (!object(event) || typeof event.event_id !== 'string' || !UUID.test(event.event_id) ||
>       typeof event.event_type !== 'string' || !positiveInteger(event.version) ||
>       !positiveInteger(event.sequence) || !positiveInteger(event.company_id) ||
>       !instant(event.occurred_at)) {
>     throw new RequestError(400, 'Envelope inválido');
>   }
>   if (headers['x-cardapio-event-id'] !== event.event_id ||
>       headers['x-cardapio-event-type'] !== event.event_type ||
>       headers['x-cardapio-event-version'] !== String(event.version)) {
>     throw new RequestError(400, 'Headers inconsistentes com o corpo');
>   }
>   // Preserve eventos autenticados de versões/tipos futuros para análise, sem efeitos.
>   if (event.version !== 1 || !EVENT_TYPES.has(event.event_type)) {
>     return { event, status: 'quarantine' };
>   }
>
>   const entitlement = event.entitlement;
>   if (!object(entitlement) || typeof entitlement.allowed !== 'boolean' ||
>       !(entitlement.access_until === null || instant(entitlement.access_until))) {
>     throw new RequestError(400, 'Entitlement inválido');
>   }
>   if (event.event_type === 'MARKETPLACE_APP_ACCESS_UPDATED') {
>     if (event.marketplace_app_id !== expectedAppId || !positiveInteger(event.installation_id) ||
>         !(entitlement.reason === null || typeof entitlement.reason === 'string')) {
>       throw new RequestError(400, 'Contexto de acesso inválido');
>     }
>   } else {
>     const subscription = event.subscription;
>     if (!object(subscription) || typeof subscription.status !== 'string' ||
>         typeof subscription.stripe_status !== 'string') {
>       throw new RequestError(400, 'Assinatura inválida');
>     }
>     if (event.event_type === 'MARKETPLACE_APP_BILLING_STATUS_UPDATED') {
>       if (subscription.app_id !== expectedAppId || !positiveInteger(subscription.id) ||
>           !positiveInteger(subscription.installation_id) || !object(subscription.plan) ||
>           !positiveInteger(subscription.plan.id)) {
>         throw new RequestError(400, 'Contexto contratual inválido');
>       }
>     } else if (!object(event.payment) || !positiveInteger(event.payment.id) ||
>                event.payment.status !== 'paid' || !positiveInteger(event.payment.amount_paid)) {
>       throw new RequestError(400, 'Pagamento inválido');
>     }
>   }
>   // O worker ainda deve validar o contrato completo e o vínculo atual da loja.
>   return { event, status: 'pending' };
> }
>
> export function openInbox(filename) {
>   if (!filename || filename === ':memory:') throw new Error('Informe um arquivo persistente para a inbox');
>   const db = new DatabaseSync(filename);
>   db.exec(`
>     PRAGMA journal_mode = WAL;
>     PRAGMA synchronous = FULL;
>     PRAGMA busy_timeout = 1000;
>     CREATE TABLE IF NOT EXISTS webhook_inbox (
>       app_id INTEGER NOT NULL,
>       event_id TEXT NOT NULL,
>       event_type TEXT NOT NULL,
>       company_id INTEGER NOT NULL,
>       payload BLOB NOT NULL,
>       received_at TEXT NOT NULL,
>       status TEXT NOT NULL,
>       PRIMARY KEY (app_id, event_id)
>     );
>   `);
>   const insert = db.prepare(`
>     INSERT INTO webhook_inbox
>       (app_id, event_id, event_type, company_id, payload, received_at, status)
>     VALUES (?, ?, ?, ?, ?, ?, ?)
>     ON CONFLICT (app_id, event_id) DO NOTHING
>   `);
>   const find = db.prepare('SELECT payload FROM webhook_inbox WHERE app_id = ? AND event_id = ?');
>   return {
>     // O INSERT só retorna depois do commit; nenhuma fila em memória participa do ACK.
>     save(appId, event, rawBody, status) {
>       const result = insert.run(appId, event.event_id, event.event_type, event.company_id,
>         rawBody, new Date().toISOString(), status);
>       if (result.changes > 0) return true;
>       const previous = find.get(appId, event.event_id);
>       if (!previous || !Buffer.from(previous.payload).equals(rawBody)) {
>         throw new RequestError(409, 'ID reutilizado com conteúdo diferente');
>       }
>       return false;
>     },
>     close() { db.close(); },
>   };
> }
>
> export function createWebhookServer({ appId, secret, inbox, onError = () => {} }) {
>   if (!positiveInteger(appId) || typeof secret !== 'string' || !secret.length) {
>     throw new Error('Configure CARDAPIO_APP_ID e CARDAPIO_WEBHOOK_TOKEN');
>   }
>   return createServer(async (request, response) => {
>     try {
>       // Exemplo dedicado aos eventos de cobrança de um único app.
>       if (request.method !== 'POST' || request.url !== '/webhooks/cardapio') {
>         throw new RequestError(404, 'Rota não encontrada');
>       }
>       if (request.headers['content-type']?.split(';')[0].trim().toLowerCase() !== 'application/json' ||
>           request.headers['content-encoding']) {
>         throw new RequestError(415, 'Envie JSON sem compressão');
>       }
>       const chunks = [];
>       let size = 0;
>       // Consuma sem parsear; limite escolhido por este exemplo, não limite do contrato CW.
>       for await (const chunk of request) {
>         size += chunk.length;
>         if (size <= MAX_BODY_BYTES) chunks.push(chunk);
>       }
>       if (size > MAX_BODY_BYTES) throw new RequestError(413, 'Corpo acima do limite do exemplo');
>       const rawBody = Buffer.concat(chunks);
>       verifySignature(rawBody, request.headers, secret);
>       const { event, status } = parseEvent(rawBody, request.headers, appId);
>       const inserted = await inbox.save(appId, event, rawBody, status);
>       response.writeHead(inserted ? 202 : 204);
>       response.end();
>     } catch (error) {
>       const status = error instanceof RequestError ? error.status : 503;
>       // O log expõe somente classe/status, sem corpo, segredo ou headers.
>       onError({ status, errorType: error.constructor.name });
>       response.writeHead(status, { 'Content-Type': 'application/json' });
>       response.end(JSON.stringify({ error: status === 503 ? 'Persistência indisponível' : error.message }));
>     }
>   });
> }
>
> if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
>   const inbox = openInbox(process.env.CARDAPIO_INBOX_DB);
>   const server = createWebhookServer({
>     appId: Number(process.env.CARDAPIO_APP_ID),
>     secret: process.env.CARDAPIO_WEBHOOK_TOKEN,
>     inbox,
>     onError: info => console.error(JSON.stringify(info)),
>   });
>   server.requestTimeout = 4000;
>   server.headersTimeout = 4000;
>   server.listen(Number(process.env.PORT || 3000), '127.0.0.1', () => {
>     console.log('Webhook disponível em http://127.0.0.1:' + server.address().port + '/webhooks/cardapio');
>   });
>   const stop = () => server.close(() => { inbox.close(); });
>   process.on('SIGINT', stop);
>   process.on('SIGTERM', stop);
> }
> ```

> [accordion] simulate.mjs
>
> ```javascript simulate.mjs theme={null}
> import { createHmac, randomUUID } from 'node:crypto';
>
> // Restrito a localhost para evitar simular pagamentos em endpoints reais por engano.
> const target = new URL(process.env.CARDAPIO_TEST_URL || 'http://127.0.0.1:3000/webhooks/cardapio');
> if (!['127.0.0.1', 'localhost', '[::1]'].includes(target.hostname)) {
>   throw new Error('O simulador aceita somente um endereço local');
> }
> const secret = process.env.CARDAPIO_WEBHOOK_TOKEN;
> const appId = Number(process.env.CARDAPIO_APP_ID);
> if (!secret || !Number.isSafeInteger(appId) || appId <= 0) {
>   throw new Error('Configure o segredo fictício e o ID do app de teste');
> }
> const event = {
>   event_id: randomUUID(),
>   event_type: 'MARKETPLACE_APP_ACCESS_UPDATED',
>   version: 1, sequence: 1, occurred_at: new Date().toISOString(),
>   company_id: 100, marketplace_app_id: appId, installation_id: 500,
>   entitlement: { allowed: true, reason: null, access_until: new Date(Date.now() + 3600000).toISOString() },
> };
> const body = JSON.stringify(event);
> const timestamp = String(Math.floor(Date.now() / 1000));
> const signature = createHmac('sha256', secret).update(timestamp + '.' + body).digest('hex');
> const response = await fetch(target, {
>   method: 'POST', body,
>   headers: {
>     'Content-Type': 'application/json',
>     'X-Cardapio-Event-Id': event.event_id,
>     'X-Cardapio-Event-Type': event.event_type,
>     'X-Cardapio-Event-Version': String(event.version),
>     'X-Cardapio-Timestamp': timestamp,
>     'X-Cardapio-Signature': 'v1=' + signature,
>   },
> });
> console.log(JSON.stringify({ event_id: event.event_id, http_status: response.status }));
> if (![200, 202, 204].includes(response.status)) process.exitCode = 1;
> ```

> [accordion] webhook.test.mjs
>
> ```javascript webhook.test.mjs theme={null}
> import assert from 'node:assert/strict';
> import { createHmac } from 'node:crypto';
> import { mkdtempSync, rmSync } from 'node:fs';
> import { tmpdir } from 'node:os';
> import { join } from 'node:path';
> import { test } from 'node:test';
> import { createWebhookServer, openInbox, parseEvent, verifySignature } from './webhook.mjs';
>
> const secret = 'segredo-ficticio-exclusivo-destes-testes';
> const now = 1_800_000_000_000;
> const event = {
>   event_id: '169ee546-6d69-49ab-8ff0-4caf7de5cd43',
>   event_type: 'MARKETPLACE_APP_ACCESS_UPDATED',
>   version: 1, sequence: 8, occurred_at: '2026-10-29T10:00:02.000-03:00',
>   company_id: 100, marketplace_app_id: 42, installation_id: 500,
>   entitlement: { allowed: true, reason: null, access_until: null },
> };
> const body = Buffer.from(JSON.stringify(event));
> function headers(payload = body, value = event, at = now, key = secret) {
>   const timestamp = String(Math.floor(at / 1000));
>   return {
>     'content-type': 'application/json',
>     'x-cardapio-timestamp': timestamp,
>     'x-cardapio-signature': 'v1=' + createHmac('sha256', key).update(timestamp + '.').update(payload).digest('hex'),
>     'x-cardapio-event-id': value.event_id,
>     'x-cardapio-event-type': value.event_type,
>     'x-cardapio-event-version': String(value.version),
>   };
> }
> test('aceita assinatura válida sobre bytes UTF-8 originais', () => {
>   const raw = Buffer.from('{ "texto": "ação", "n": 1 }');
>   assert.doesNotThrow(() => verifySignature(raw, headers(raw), secret, now));
> });
> test('rejeita corpo adulterado e JSON reserializado', () => {
>   const pretty = Buffer.from(JSON.stringify(event, null, 2));
>   assert.throws(() => verifySignature(pretty, headers(), secret, now), { status: 401 });
> });
> test('rejeita segredo incorreto e assinatura malformada', () => {
>   assert.throws(() => verifySignature(body, headers(), 'outro', now), { status: 401 });
>   for (const signature of ['', 'v1=aa', 'v2=' + 'a'.repeat(64), ['v1=' + 'a'.repeat(64)]]) {
>     assert.throws(() => verifySignature(body, { ...headers(), 'x-cardapio-signature': signature }, secret, now), { status: 401 });
>   }
> });
> test('rejeita timestamp antigo, futuro e não numérico', () => {
>   for (const at of [now - 301000, now + 301000]) {
>     assert.throws(() => verifySignature(body, headers(body, event, at), secret, now), { status: 401 });
>   }
>   assert.throws(() => verifySignature(body, { ...headers(), 'x-cardapio-timestamp': 'abc' }, secret, now), { status: 401 });
> });
> test('aceita reentrega de evento antigo com timestamp de entrega atual', () => {
>   const historical = { ...event, occurred_at: '2020-01-01T00:00:00Z' };
>   const raw = Buffer.from(JSON.stringify(historical));
>   verifySignature(raw, headers(raw, historical), secret, now);
>   assert.equal(parseEvent(raw, headers(raw, historical), 42).status, 'pending');
> });
> test('rejeita divergência entre headers e corpo', () => {
>   for (const header of ['x-cardapio-event-id', 'x-cardapio-event-type', 'x-cardapio-event-version']) {
>     assert.throws(() => parseEvent(body, { ...headers(), [header]: 'diferente' }, 42), { status: 400 });
>   }
> });
> test('rejeita evento de outro app e envelope inválido', () => {
>   assert.throws(() => parseEvent(body, headers(), 99), { status: 400 });
>   for (const value of [{ ...event, sequence: 0 }, { ...event, company_id: null }, { ...event, entitlement: [] }]) {
>     const raw = Buffer.from(JSON.stringify(value));
>     assert.throws(() => parseEvent(raw, headers(raw, value), 42), { status: 400 });
>   }
>   assert.throws(() => parseEvent(Buffer.from('{'), headers(), 42), { status: 400 });
> });
> test('preserva campos extras e coloca tipos e versões futuros em quarentena', () => {
>   for (const value of [{ ...event, version: 2 }, { ...event, event_type: 'MARKETPLACE_APP_NEW_EVENT' }]) {
>     const raw = Buffer.from(JSON.stringify(value));
>     assert.equal(parseEvent(raw, headers(raw, value), 42).status, 'quarantine');
>   }
>   const value = { ...event, extra: 'campo futuro' };
>   const raw = Buffer.from(JSON.stringify(value));
>   assert.equal(parseEvent(raw, headers(raw, value), 42).event.extra, 'campo futuro');
> });
> test('inbox preserva evento após reinício, deduplica e separa apps', t => {
>   const dir = mkdtempSync(join(tmpdir(), 'cw-inbox-'));
>   const file = join(dir, 'inbox.sqlite');
>   let inbox = openInbox(file);
>   t.after(() => { inbox.close(); rmSync(dir, { recursive: true, force: true }); });
>   assert.equal(inbox.save(42, event, body, 'pending'), true);
>   inbox.close();
>   inbox = openInbox(file);
>   assert.equal(inbox.save(42, event, body, 'pending'), false);
>   assert.equal(inbox.save(43, event, body, 'pending'), true);
>   assert.throws(() => inbox.save(42, event, Buffer.from('{}'), 'pending'), { status: 409 });
> });
> test('recusa inbox em memória', () => {
>   assert.throws(() => openInbox(':memory:'));
> });
> async function serve(t, inbox) {
>   const errors = [];
>   const server = createWebhookServer({ appId: 42, secret, inbox, onError: info => errors.push(info) });
>   await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
>   t.after(() => new Promise(resolve => { server.closeAllConnections(); server.close(resolve); }));
>   return { url: 'http://127.0.0.1:' + server.address().port + '/webhooks/cardapio', errors };
> }
> test('HTTP confirma somente depois da persistência e responde 204 à duplicata', async t => {
>   const dir = mkdtempSync(join(tmpdir(), 'cw-http-'));
>   const inbox = openInbox(join(dir, 'inbox.sqlite'));
>   const { url } = await serve(t, inbox);
>   t.after(() => { inbox.close(); rmSync(dir, { recursive: true, force: true }); });
>   const send = () => fetch(url, { method: 'POST', headers: headers(body, event, Date.now()), body });
>   assert.equal((await send()).status, 202);
>   assert.equal((await send()).status, 204);
> });
> test('HTTP retorna 503 quando falha a persistência, sem expor segredo', async t => {
>   const { url, errors } = await serve(t, { async save() { throw new Error(secret); } });
>   const response = await fetch(url, { method: 'POST', headers: headers(body, event, Date.now()), body });
>   assert.equal(response.status, 503);
>   assert.equal((await response.text()).includes(secret), false);
>   assert.deepEqual(errors, [{ status: 503, errorType: 'Error' }]);
> });
> test('HTTP rejeita assinatura inválida antes de persistir', async t => {
>   let saved = false;
>   const { url } = await serve(t, { save() { saved = true; } });
>   const response = await fetch(url, { method: 'POST', headers: headers(body, event, Date.now(), 'incorreto'), body });
>   assert.equal(response.status, 401);
>   assert.equal(saved, false);
> });
> test('HTTP encaminha evento futuro para quarentena antes do ACK', async t => {
>   let status;
>   const { url } = await serve(t, { save(_appId, _event, _raw, value) { status = value; return true; } });
>   const future = { ...event, version: 2 };
>   const raw = Buffer.from(JSON.stringify(future));
>   const response = await fetch(url, { method: 'POST', headers: headers(raw, future, Date.now()), body: raw });
>   assert.equal(response.status, 202);
>   assert.equal(status, 'quarantine');
> });
> ```

## 1. Execute localmente

Na pasta em que salvou os arquivos, configure um **segredo fictício**, usado apenas na simulação local:

```bash theme={null}
export CARDAPIO_APP_ID=42
export CARDAPIO_WEBHOOK_TOKEN='somente-teste-local-nao-use-em-producao'
export CARDAPIO_INBOX_DB='/tmp/cw-billing-inbox.sqlite'
export PORT=3000
node webhook.mjs
```

O servidor atende `POST http://127.0.0.1:3000/webhooks/cardapio`. HTTP e o endereço local são usados somente entre os processos da simulação. Para receber os eventos da CW, adapte este tratamento ao endpoint HTTPS já cadastrado no app e use o ID e o `webhook_token` existentes.

O arquivo em `/tmp` serve para o exercício e preserva eventos entre reinícios do processo enquanto o arquivo existir. Em produção, use armazenamento persistente com backup; não dependa de uma pasta temporária, container efêmero ou banco em memória.

## 2. Envie um evento de teste

Em outro terminal, configure o **mesmo segredo fictício** e execute:

```bash theme={null}
export CARDAPIO_APP_ID=42
export CARDAPIO_WEBHOOK_TOKEN='somente-teste-local-nao-use-em-producao'
node simulate.mjs
```

O resultado esperado contém `http_status: 202` e o ID do evento simulado. O simulador cria um evento de acesso e o assina; ele **não executa cobrança, não chama a Stripe e não altera uma assinatura CW**. Por proteção contra envio acidental, ele aceita somente destinos locais.

Use o simulador para testar o processamento dos eventos no webhook e os testes automatizados para conferir assinatura, persistência e tratamento de erros. Os eventos reais chegam quando os restaurantes contratam e gerenciam as assinaturas pela CW.

## 3. Entenda a validação criptográfica

```javascript Node.js theme={null}
import { createHmac, timingSafeEqual } from 'node:crypto';

function validSignature(rawBody, timestamp, signature, webhookToken) {
  if (typeof timestamp !== 'string' || !/^\d+$/.test(timestamp)) return false;
  if (typeof signature !== 'string' || !/^v1=[0-9a-f]{64}$/.test(signature)) return false;

  const seconds = Number(timestamp);
  if (!Number.isSafeInteger(seconds)) return false;
  if (Math.abs(Math.floor(Date.now() / 1000) - seconds) > 300) return false;

  const expected = createHmac('sha256', webhookToken)
    .update(timestamp + '.')
    .update(rawBody)
    .digest();
  const provided = Buffer.from(signature.slice(3), 'hex');
  return provided.length === expected.length && timingSafeEqual(provided, expected);
}
```

```ruby Ruby theme={null}
require "openssl"

def valid_signature?(raw_body:, timestamp:, signature:, webhook_token:)
  return false unless timestamp.is_a?(String) && timestamp.match?(/\A\d+\z/)
  return false unless signature.is_a?(String) && signature.match?(/\Av1=[0-9a-f]{64}\z/)
  return false if (Time.now.to_i - Integer(timestamp, 10)).abs > 300

  expected = OpenSSL::HMAC.hexdigest(
    "SHA256", webhook_token, "#{timestamp}.#{raw_body}"
  )
  provided = signature.delete_prefix("v1=")
  provided.bytesize == expected.bytesize &&
    OpenSSL.fixed_length_secure_compare(provided, expected)
end
```

Esses trechos verificam somente a assinatura e o timestamp. No Rails, obtenha o corpo com `request.raw_post`; no Express, registre o parser de corpo bruto nessa rota **antes** do parser JSON. Depois da verificação, faça o parse e confira os headers de identidade, tipo e versão contra o corpo.

O arquivo `webhook.mjs` acima implementa também a validação básica de envelope e contexto, limitação de corpo, persistência e respostas HTTP. Ele atende um app por configuração. Mantenha a inbox da simulação local separada dos eventos reais.

## 4. Grave antes de responder

O exemplo salva o payload original em `webhook_inbox`, com chave única `(app_id, event_id)`. O `INSERT` termina antes do ACK. Configure o banco persistente usado pelo webhook para armazenar os eventos.

| Resultado | Resposta do exemplo |
| - | - |
| Evento novo gravado | `202` |
| Mesmo evento já gravado, mesmo corpo | `204` |
| Mesmo ID com corpo diferente | `409`, para investigação |
| Assinatura ou timestamp inválido | `401` |
| JSON, envelope ou headers inválidos | `400` |
| Falha ao persistir | `503` |
| Tipo ou versão futura autenticada | Grava com status `quarantine` e retorna `202` |

A deduplicação usa o banco de dados. Reiniciar o processo mantém a proteção enquanto o banco persistir. A quarentena também precisa ser monitorada: armazenar e confirmar não significa que o evento foi aplicado ao cliente.

## 5. Implemente o worker do seu app

O exemplo termina na inbox. Você deve implementar um worker durável que leia eventos `pending`, valide os campos completos usados pelo seu domínio, confirme os vínculos e aplique as regras. Este exemplo não cria usuários, não concede planos e não implementa cobrança.

```text theme={null}
Para cada evento pendente:
  Iniciar transação
  Bloquear evento da inbox e estado afetado
  Se o evento já foi processado: encerrar sem efeitos
  Confirmar app, empresa e vínculo atual

  Se ainda não há vínculo confirmado:
    Manter pendente para conciliação; não liberar acesso

  Se BILLING_STATUS_UPDATED:
    Validar os campos completos do snapshot
    Confirmar a assinatura correspondente ao vínculo
    Se sequence é maior que a última sequência de status dessa assinatura:
      Salvar plano, status e datas
      Mapear recursos pelo ID do plano

  Se PAYMENT_SUCCEEDED:
    Registrar fatura por app + payment.id, de forma idempotente
    Não alterar plano, acesso ou sequência do snapshot contratual

  Se ACCESS_UPDATED:
    Confirmar a instalação correspondente ao vínculo
    Se sequence é maior que a última sequência de acesso dessa instalação:
      Salvar allowed, reason, access_until e transition

  Marcar o evento processado
  Confirmar transação
```

O pseudocódigo mostra responsabilidades, não um framework ou API fornecidos pela Cardápio Web. Use transações e locks do seu banco. Se o processamento falhar, preserve o evento pendente e permita nova tentativa interna. Depois do ACK, a CW considera a entrega concluída; a retentativa do seu worker é responsabilidade do seu app.

Quando a operação exige e-mail ou outra chamada externa, grave uma tarefa durável na mesma transação e envie depois. Isso evita perder a ação após marcar o evento processado e permite deduplicá-la por evento ou pagamento.

### Exemplo de decisão de acesso

Este trecho considera que o evento já foi validado e pertence ao vínculo atual:

```javascript theme={null}
function accessIsCurrent(entitlement, now = Date.now()) {
  if (entitlement?.allowed !== true) return false;
  if (entitlement.access_until === null) return true;
  const deadline = Date.parse(entitlement.access_until);
  return Number.isFinite(deadline) && now < deadline;
}
```

Use o `entitlement` do último **evento de acesso** aplicável. Combine essa verificação com as permissões do usuário e os recursos do plano. Não passe o `entitlement` de um pagamento para essa função como substituto do estado de acesso.

## 6. Rode os testes

```bash theme={null}
node --test webhook.test.mjs
```

Os testes cobrem bytes originais, adulteração, segredo errado, timestamps, headers inconsistentes, contexto de outro app, campos adicionais, quarentena, persistência após reinício, duplicatas, falha de armazenamento e respostas HTTP. A execução dos três arquivos publicados nesta página inclui 14 testes de processamento dos webhooks.

## Adapte para produção

Antes de usar o padrão no seu app:

* Termine HTTPS no seu servidor ou proxy e preserve os bytes do corpo.
* Use o segredo real de cada app, fornecido por configuração protegida.
* Execute e monitore o worker da inbox, com retries internos e tratamento de quarentena.
* Valide a associação da empresa, instalação e assinatura antes de atualizar permissões.
* Garanta a unicidade e a atualização condicional de sequência no banco compartilhado por suas réplicas.
* Defina retenção e proteção de acesso aos payloads armazenados, sem registrar segredos em logs.
* Valide o consumidor com os [testes locais e cenários de acesso](https://docs.cardapioweb.com/cobranca/testes-e-solucao-de-problemas.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.