Guia de Configuração de Webhook
Os webhooks permitem a comunicação em tempo real entre o Brevo e a sua plataforma de fidelidade Tajo. Este guia orienta-o através do processo de configuração completo.
Visão Geral
Os webhooks permitem ao Brevo notificar automaticamente a sua aplicação Tajo quando ocorrem eventos específicos, como:
- Eventos de e-mail: Entregue, aberto, clicado, rejeitado
- Eventos SMS: Enviado, entregue, falhado, respondido
- Eventos de contacto: Criado, atualizado, cancelou subscrição
- Eventos de campanha: Iniciada, concluída, pausada
Pré-requisitos
Antes de configurar webhooks, certifique-se de que tem:
- Endpoint HTTPS para receber webhooks (SSL obrigatório)
- Segredo de webhook para verificação de assinatura
- Ambiente de servidor capaz de processar pedidos HTTP POST
- Conta Brevo com permissões de acesso a webhooks
Passo 1: Preparar o Seu Endpoint de Webhook
Criar Handler de Webhook
import express from 'express';import crypto from 'crypto';import { TajoLoyaltyService } from './loyalty-service.js';
const app = express();const loyaltyService = new TajoLoyaltyService();
// Middleware para capturar corpo raw para verificação de assinaturaapp.use('/webhooks/brevo', express.raw({ type: 'application/json', limit: '10mb'}));
// Handler principal de webhookapp.post('/webhooks/brevo', async (req, res) => { try { // Verificar assinatura do webhook const signature = req.headers['x-brevo-signature']; if (!verifyWebhookSignature(req.body, signature)) { console.warn('Assinatura de webhook inválida recebida'); return res.status(401).json({ error: 'Não autorizado: Assinatura inválida' }); }
// Analisar payload do webhook const event = JSON.parse(req.body.toString()); console.log('Evento webhook recebido:', event.event, event.email);
// Encaminhar para o handler adequado await handleWebhookEvent(event);
// Responder rapidamente (Brevo espera resposta em 5 segundos) res.status(200).json({ success: true, eventId: event['message-id'], timestamp: new Date().toISOString() });
} catch (error) { console.error('Erro no processamento do webhook:', error); res.status(500).json({ error: 'Erro interno do servidor', message: error.message }); }});
// Função de verificação de assinaturafunction verifyWebhookSignature(payload, signature) { if (!process.env.BREVO_WEBHOOK_SECRET || !signature) { return false; }
const expectedSignature = crypto .createHmac('sha256', process.env.BREVO_WEBHOOK_SECRET) .update(payload) .digest('hex');
return crypto.timingSafeEqual( Buffer.from(signature.replace('sha256=', ''), 'hex'), Buffer.from(expectedSignature, 'hex') );}
// Roteador de eventosasync function handleWebhookEvent(event) { switch (event.event) { // Eventos de e-mail case 'delivered': await handleEmailDelivered(event); break; case 'opened': await handleEmailOpened(event); break; case 'clicked': await handleEmailClicked(event); break; case 'bounced': case 'hard_bounced': await handleEmailBounced(event); break; case 'spam': await handleEmailSpam(event); break; case 'unsubscribed': await handleEmailUnsubscribed(event); break;
// Eventos SMS case 'sms_delivered': await handleSMSDelivered(event); break; case 'sms_failed': await handleSMSFailed(event); break; case 'sms_reply': await handleSMSReply(event); break;
// Eventos de contacto case 'contact_created': await handleContactCreated(event); break; case 'contact_updated': await handleContactUpdated(event); break; case 'list_addition': await handleListAddition(event); break;
default: console.warn('Evento webhook não tratado:', event.event); }}Handlers de Eventos de E-mail
// Tratar confirmação de entrega de e-mailasync function handleEmailDelivered(event) { const customerEmail = event.email; const messageId = event['message-id'];
await loyaltyService.updateCustomerEngagement(customerEmail, { lastEmailDelivered: new Date(), emailDeliveryRate: 'increment' });
// Registar para análise console.log(`E-mail entregue a ${customerEmail}: ${messageId}`);}
// Tratar aberturas de e-mail (métrica chave de envolvimento)async function handleEmailOpened(event) { const customerEmail = event.email; const subject = event.subject; const timestamp = new Date(event.ts * 1000);
// Atualizar score de envolvimento do cliente await loyaltyService.updateCustomerEngagement(customerEmail, { lastEmailOpened: timestamp, emailOpenRate: 'increment', engagementScore: 'increase' });
// Rastrear envolvimento de campanha de fidelidade if (event.tag?.includes('loyalty')) { await loyaltyService.trackLoyaltyEngagement(customerEmail, { event: 'email_opened', campaign: extractCampaignFromSubject(subject), timestamp: timestamp }); }
console.log(`E-mail aberto por ${customerEmail}: "${subject}"`);}
// Tratar cliques em e-mail (envolvimento de alto valor)async function handleEmailClicked(event) { const customerEmail = event.email; const clickedUrl = event.link; const timestamp = new Date(event.ts * 1000);
// Envolvimento de alto valor - impulsionar score do cliente await loyaltyService.updateCustomerEngagement(customerEmail, { lastEmailClicked: timestamp, emailClickRate: 'increment', engagementScore: 'boost' });
// Rastrear visitas à página de recompensas if (clickedUrl.includes('/rewards') || clickedUrl.includes('/loyalty')) { await loyaltyService.trackEvent(customerEmail, 'Rewards Page Visited', { source: 'email', referrer_url: clickedUrl, timestamp: timestamp }); }
console.log(`Link de e-mail clicado por ${customerEmail}: ${clickedUrl}`);}
// Tratar rejeições de e-mail (problemas de entrega)async function handleEmailBounced(event) { const customerEmail = event.email; const bounceReason = event.reason; const bounceType = event.event; // 'bounced' ou 'hard_bounced'
if (bounceType === 'hard_bounced') { // Hard bounce - endereço de e-mail inválido await loyaltyService.updateCustomerStatus(customerEmail, { emailStatus: 'invalid', emailBounced: true, bounceReason: bounceReason, lastBounce: new Date() });
// Considerar mudar para SMS para notificações críticas await loyaltyService.suggestAlternativeChannel(customerEmail, 'sms'); } else { // Soft bounce - problema temporário await loyaltyService.updateCustomerEngagement(customerEmail, { emailBounceCount: 'increment', lastBounce: new Date() }); }
console.warn(`E-mail rejeitado para ${customerEmail}: ${bounceReason}`);}
// Tratar relatórios de spam (gestão de reputação)async function handleEmailSpam(event) { const customerEmail = event.email;
// Marcar cliente como não envolvido para evitar futuros relatórios de spam await loyaltyService.updateCustomerStatus(customerEmail, { emailStatus: 'spam_reported', marketingEnabled: false, lastSpamReport: new Date() });
// Alertar equipa de marketing para revisão await loyaltyService.alertMarketing('spam_report', { email: customerEmail, campaign: event.tag });
console.warn(`Spam reportado por ${customerEmail}`);}Handlers de Eventos SMS
// Tratar confirmação de entrega de SMSasync function handleSMSDelivered(event) { const customerPhone = event.phone; const messageId = event['message-id'];
await loyaltyService.updateCustomerEngagement(customerPhone, { lastSMSDelivered: new Date(), smsDeliveryRate: 'increment' });
console.log(`SMS entregue a ${customerPhone}: ${messageId}`);}
// Tratar falhas de SMSasync function handleSMSFailed(event) { const customerPhone = event.phone; const failureReason = event.reason;
await loyaltyService.updateCustomerStatus(customerPhone, { smsStatus: 'failed', smsFailureReason: failureReason, lastSMSFailure: new Date() });
// Se o SMS falhar, considerar e-mail como alternativa const customer = await loyaltyService.getCustomerByPhone(customerPhone); if (customer?.email) { await loyaltyService.suggestAlternativeChannel(customer.email, 'email'); }
console.warn(`SMS falhado para ${customerPhone}: ${failureReason}`);}
// Tratar respostas a SMS (comunicação bidirecional)async function handleSMSReply(event) { const customerPhone = event.phone; const replyText = event.text.toLowerCase().trim();
// Processar respostas comuns if (replyText === 'stop' || replyText === 'unsubscribe' || replyText === 'parar') { await loyaltyService.unsubscribeFromSMS(customerPhone); } else if (replyText === 'help' || replyText === 'info' || replyText === 'ajuda') { await loyaltyService.sendSMSHelp(customerPhone); } else { // Encaminhar para apoio ao cliente await loyaltyService.forwardSMSToSupport(customerPhone, replyText); }
console.log(`Resposta SMS de ${customerPhone}: "${replyText}"`);}Passo 2: Configurar Webhook no Brevo
Via Painel Brevo
- Faça login na conta Brevo
- Navegue para Developers > Webhooks
- Clique em “Adicionar um novo webhook”
- Configure as definições do webhook:
{ "url": "https://your-tajo-domain.com/webhooks/brevo", "description": "Integração da Plataforma de Fidelidade Tajo", "events": [ "delivered", "opened", "clicked", "bounced", "hard_bounced", "spam", "unsubscribed", "sms_delivered", "sms_failed", "sms_reply", "contact_created", "contact_updated" ]}Via API
import { WebhooksApi } from '@brevo/brevo-js';
async function createWebhook() { const webhooksApi = new WebhooksApi();
const createWebhook = { url: 'https://your-tajo-domain.com/webhooks/brevo', description: 'Integração da Plataforma de Fidelidade Tajo', events: [ 'delivered', 'opened', 'clicked', 'bounced', 'hard_bounced', 'spam', 'unsubscribed', 'sms_delivered', 'sms_failed', 'sms_reply', 'contact_created', 'contact_updated' ] };
try { const response = await webhooksApi.createWebhook(createWebhook); console.log('Webhook criado com sucesso:', response.id); return response; } catch (error) { console.error('Erro ao criar webhook:', error); throw error; }}Passo 3: Implementação de Segurança
Variáveis de Ambiente
# ficheiro .envBREVO_WEBHOOK_SECRET=your-super-secure-webhook-secret-hereBREVO_API_KEY=xkeysib-your-api-key-hereWEBHOOK_RATE_LIMIT=1000WEBHOOK_TIMEOUT=5000Limitação de Taxa
import rateLimit from 'express-rate-limit';
const webhookLimiter = rateLimit({ windowMs: 15 * 60 * 1000, // 15 minutos max: 1000, // Limitar cada IP a 1000 pedidos por windowMs message: 'Demasiados pedidos de webhook deste IP', standardHeaders: true, legacyHeaders: false,});
app.use('/webhooks/brevo', webhookLimiter);Lista Branca de IPs (Opcional)
const brevoIPs = [ '185.41.28.0/24', '185.41.29.0/24', '217.182.196.0/24'];
function isBrevoIP(ip) { // Implementar verificação de intervalo de IP return brevoIPs.some(range => ipInRange(ip, range));}
app.use('/webhooks/brevo', (req, res, next) => { const clientIP = req.ip || req.connection.remoteAddress;
if (process.env.NODE_ENV === 'production' && !isBrevoIP(clientIP)) { return res.status(403).json({ error: 'Proibido: IP de origem inválido' }); }
next();});Passo 4: Testar Webhooks
Handler de Teste de Webhook
// Endpoint de teste para verificação de webhookapp.post('/webhooks/brevo/test', (req, res) => { const testEvent = { event: 'test', 'message-id': 'test-message-id', timestamp: Date.now() / 1000, tags: ['test', 'loyalty'] };
console.log('Webhook de teste recebido:', testEvent);
res.status(200).json({ success: true, message: 'Webhook de teste processado com sucesso', receivedAt: new Date().toISOString() });});Testes Manuais
# Testar endpoint de webhook com curlcurl -X POST https://your-domain.com/webhooks/brevo/test \ -H "Content-Type: application/json" \ -H "X-Brevo-Signature: sha256=test-signature" \ -d '{ "event": "delivered", "email": "[email protected]", "message-id": "test-123", "ts": 1640995200 }'Validação de Webhook
class WebhookValidator { static validateEvent(event) { const required = ['event', 'email', 'message-id']; const missing = required.filter(field => !event[field]);
if (missing.length > 0) { throw new Error(`Campos obrigatórios em falta: ${missing.join(', ')}`); }
// Validar formato de e-mail if (!this.isValidEmail(event.email)) { throw new Error('Formato de e-mail inválido'); }
// Validar tipo de evento const validEvents = [ 'delivered', 'opened', 'clicked', 'bounced', 'hard_bounced', 'spam', 'unsubscribed', 'sms_delivered', 'sms_failed' ];
if (!validEvents.includes(event.event)) { throw new Error(`Tipo de evento inválido: ${event.event}`); }
return true; }
static isValidEmail(email) { return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email); }}Passo 5: Monitorização e Logging
Monitorização de Webhook
import winston from 'winston';
const webhookLogger = winston.createLogger({ level: 'info', format: winston.format.combine( winston.format.timestamp(), winston.format.json() ), transports: [ new winston.transports.File({ filename: 'webhook-error.log', level: 'error' }), new winston.transports.File({ filename: 'webhook-combined.log' }) ]});
// Adicionar middleware de monitorizaçãoapp.use('/webhooks/brevo', (req, res, next) => { const startTime = Date.now();
res.on('finish', () => { const duration = Date.now() - startTime;
webhookLogger.info('Webhook processado', { method: req.method, url: req.url, statusCode: res.statusCode, duration: duration, userAgent: req.headers['user-agent'], contentLength: req.headers['content-length'] }); });
next();});Endpoint de Verificação de Saúde
app.get('/webhooks/brevo/health', async (req, res) => { const health = { status: 'healthy', timestamp: new Date().toISOString(), uptime: process.uptime(), version: process.env.npm_package_version, environment: process.env.NODE_ENV, checks: { database: await checkDatabaseConnection(), redis: await checkRedisConnection(), brevoAPI: await checkBrevoAPIConnection() } };
const allHealthy = Object.values(health.checks).every(check => check.status === 'ok');
res.status(allHealthy ? 200 : 503).json(health);});Passo 6: Tratamento de Erros e Recuperação
Lógica de Retry
class WebhookProcessor { constructor() { this.maxRetries = 3; this.retryDelay = 1000; // 1 segundo }
async processEvent(event, retries = 0) { try { await this.handleEvent(event); } catch (error) { if (retries < this.maxRetries && this.isRetryableError(error)) { console.warn(`Processamento de webhook falhado, a tentar novamente... (${retries + 1}/${this.maxRetries})`);
await this.delay(this.retryDelay * Math.pow(2, retries)); // Backoff exponencial return this.processEvent(event, retries + 1); }
// Máximo de retries atingido ou erro não recuperável await this.handleFailedEvent(event, error); throw error; } }
isRetryableError(error) { // Tentar novamente em falhas temporárias return error.code === 'ECONNRESET' || error.code === 'ETIMEDOUT' || (error.status >= 500 && error.status < 600); }
delay(ms) { return new Promise(resolve => setTimeout(resolve, ms)); }}Fila de Mensagens Mortas
import Bull from 'bull';
const webhookQueue = new Bull('webhook processing', process.env.REDIS_URL);const deadLetterQueue = new Bull('webhook failed', process.env.REDIS_URL);
webhookQueue.process(async (job) => { const { event } = job.data; await handleWebhookEvent(event);});
webhookQueue.on('failed', async (job, err) => { console.error(`Trabalho de webhook falhado: ${err.message}`);
// Adicionar à fila de mensagens mortas para processamento manual await deadLetterQueue.add('failed webhook', { originalEvent: job.data.event, error: err.message, failedAt: new Date(), attempts: job.attemptsMade });});Resolução de Problemas Comuns
1. Verificação de Assinatura Falha
// Depurar verificação de assinaturafunction debugSignature(payload, receivedSignature) { const expectedSignature = crypto .createHmac('sha256', process.env.BREVO_WEBHOOK_SECRET) .update(payload) .digest('hex');
console.log('Assinatura recebida:', receivedSignature); console.log('Assinatura esperada:', expectedSignature); console.log('Comprimento do payload:', payload.length); console.log('Primeiros 100 chars:', payload.slice(0, 100));
return expectedSignature === receivedSignature.replace('sha256=', '');}2. Eventos em Falta
Verifique a configuração do webhook:
async function auditWebhookConfig() { const webhooksApi = new WebhooksApi();
try { const webhooks = await webhooksApi.getWebhooks();
webhooks.webhooks.forEach(webhook => { console.log('ID do Webhook:', webhook.id); console.log('URL:', webhook.url); console.log('Eventos:', webhook.events); console.log('Estado:', webhook.is_enabled ? 'ativo' : 'desativo'); }); } catch (error) { console.error('Erro ao auditar webhooks:', error); }}3. Alta Latência
Otimize o processamento de webhooks:
// Processar webhooks de forma assíncronaapp.post('/webhooks/brevo', async (req, res) => { // Verificar assinatura rapidamente if (!verifyWebhookSignature(req.body, req.headers['x-brevo-signature'])) { return res.status(401).json({ error: 'Não autorizado' }); }
// Responder imediatamente res.status(200).json({ success: true });
// Processar evento de forma assíncrona const event = JSON.parse(req.body.toString()); webhookQueue.add('process event', { event }, { attempts: 3, backoff: { type: 'exponential', delay: 2000 } });});Próximos Passos
- Guia de Segurança de Webhook, Práticas avançadas de segurança
- Referência de Tipos de Eventos, Documentação completa de eventos
- Testar Webhooks, Guia de testes e depuração
- Análise de Webhook, Monitorizar desempenho de webhooks