Guida alla Configurazione dei Webhook

I webhook consentono la comunicazione in tempo reale tra Brevo e la tua piattaforma fedeltà Tajo. Questa guida ti accompagna nell’intero processo di configurazione.

Panoramica

I webhook consentono a Brevo di notificare automaticamente la tua applicazione Tajo quando si verificano eventi specifici, come:

  • Eventi email: Consegnata, aperta, cliccata, rimbalzata
  • Eventi SMS: Inviato, consegnato, fallito, risposto
  • Eventi contatto: Creato, aggiornato, cancellato
  • Eventi campagna: Avviata, completata, in pausa

Prerequisiti

Prima di configurare i webhook, assicurati di avere:

  • Endpoint HTTPS per ricevere i webhook (SSL obbligatorio)
  • Segreto webhook per la verifica della firma
  • Ambiente server in grado di gestire richieste HTTP POST
  • Account Brevo con permessi di accesso ai webhook

Passo 1: Prepara il Tuo Endpoint Webhook

Crea il Gestore Webhook

import express from 'express';
import crypto from 'crypto';
import { TajoLoyaltyService } from './loyalty-service.js';
const app = express();
const loyaltyService = new TajoLoyaltyService();
// Middleware per acquisire il corpo raw per la verifica della firma
app.use('/webhooks/brevo', express.raw({
type: 'application/json',
limit: '10mb'
}));
// Gestore principale webhook
app.post('/webhooks/brevo', async (req, res) => {
try {
// Verifica la firma del webhook
const signature = req.headers['x-brevo-signature'];
if (!verifyWebhookSignature(req.body, signature)) {
console.warn('Ricevuta firma webhook non valida');
return res.status(401).json({ error: 'Unauthorized: Invalid signature' });
}
// Analizza il payload del webhook
const event = JSON.parse(req.body.toString());
console.log('Evento webhook ricevuto:', event.event, event.email);
// Instrada al gestore appropriato
await handleWebhookEvent(event);
// Risposta rapida (Brevo si aspetta una risposta entro 5 secondi)
res.status(200).json({
success: true,
eventId: event['message-id'],
timestamp: new Date().toISOString()
});
} catch (error) {
console.error('Errore nell\'elaborazione del webhook:', error);
res.status(500).json({
error: 'Internal server error',
message: error.message
});
}
});
// Funzione di verifica della firma
function 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')
);
}
// Router degli eventi
async function handleWebhookEvent(event) {
switch (event.event) {
// Eventi email
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;
// Eventi SMS
case 'sms_delivered':
await handleSMSDelivered(event);
break;
case 'sms_failed':
await handleSMSFailed(event);
break;
case 'sms_reply':
await handleSMSReply(event);
break;
// Eventi contatto
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 non gestito:', event.event);
}
}

Gestori degli Eventi Email

// Gestisci la conferma di consegna email
async function handleEmailDelivered(event) {
const customerEmail = event.email;
const messageId = event['message-id'];
await loyaltyService.updateCustomerEngagement(customerEmail, {
lastEmailDelivered: new Date(),
emailDeliveryRate: 'increment'
});
console.log(`Email consegnata a ${customerEmail}: ${messageId}`);
}
// Gestisci le aperture email (metrica chiave di coinvolgimento)
async function handleEmailOpened(event) {
const customerEmail = event.email;
const subject = event.subject;
const timestamp = new Date(event.ts * 1000);
// Aggiorna il punteggio di coinvolgimento del cliente
await loyaltyService.updateCustomerEngagement(customerEmail, {
lastEmailOpened: timestamp,
emailOpenRate: 'increment',
engagementScore: 'increase'
});
// Traccia il coinvolgimento nelle campagne fedeltà
if (event.tag?.includes('loyalty')) {
await loyaltyService.trackLoyaltyEngagement(customerEmail, {
event: 'email_opened',
campaign: extractCampaignFromSubject(subject),
timestamp: timestamp
});
}
console.log(`Email aperta da ${customerEmail}: "${subject}"`);
}
// Gestisci i clic nelle email (coinvolgimento di alto valore)
async function handleEmailClicked(event) {
const customerEmail = event.email;
const clickedUrl = event.link;
const timestamp = new Date(event.ts * 1000);
// Coinvolgimento di alto valore - aumenta il punteggio del cliente
await loyaltyService.updateCustomerEngagement(customerEmail, {
lastEmailClicked: timestamp,
emailClickRate: 'increment',
engagementScore: 'boost'
});
// Traccia le visite alla pagina premi
if (clickedUrl.includes('/rewards') || clickedUrl.includes('/loyalty')) {
await loyaltyService.trackEvent(customerEmail, 'Rewards Page Visited', {
source: 'email',
referrer_url: clickedUrl,
timestamp: timestamp
});
}
console.log(`Link email cliccato da ${customerEmail}: ${clickedUrl}`);
}
// Gestisci i rimbalzi email (problemi di consegna)
async function handleEmailBounced(event) {
const customerEmail = event.email;
const bounceReason = event.reason;
const bounceType = event.event; // 'bounced' o 'hard_bounced'
if (bounceType === 'hard_bounced') {
// Rimbalzo permanente - indirizzo email non valido
await loyaltyService.updateCustomerStatus(customerEmail, {
emailStatus: 'invalid',
emailBounced: true,
bounceReason: bounceReason,
lastBounce: new Date()
});
// Considera SMS come canale alternativo per le notifiche critiche
await loyaltyService.suggestAlternativeChannel(customerEmail, 'sms');
} else {
// Rimbalzo temporaneo - problema temporaneo
await loyaltyService.updateCustomerEngagement(customerEmail, {
emailBounceCount: 'increment',
lastBounce: new Date()
});
}
console.warn(`Email rimbalzata per ${customerEmail}: ${bounceReason}`);
}
// Gestisci le segnalazioni spam (gestione della reputazione)
async function handleEmailSpam(event) {
const customerEmail = event.email;
// Segna il cliente come non coinvolto per prevenire future segnalazioni
await loyaltyService.updateCustomerStatus(customerEmail, {
emailStatus: 'spam_reported',
marketingEnabled: false,
lastSpamReport: new Date()
});
// Avvisa il team marketing per revisione
await loyaltyService.alertMarketing('spam_report', {
email: customerEmail,
campaign: event.tag
});
console.warn(`Spam segnalato da ${customerEmail}`);
}

Gestori degli Eventi SMS

// Gestisci la conferma di consegna SMS
async function handleSMSDelivered(event) {
const customerPhone = event.phone;
const messageId = event['message-id'];
await loyaltyService.updateCustomerEngagement(customerPhone, {
lastSMSDelivered: new Date(),
smsDeliveryRate: 'increment'
});
console.log(`SMS consegnato a ${customerPhone}: ${messageId}`);
}
// Gestisci i fallimenti SMS
async function handleSMSFailed(event) {
const customerPhone = event.phone;
const failureReason = event.reason;
await loyaltyService.updateCustomerStatus(customerPhone, {
smsStatus: 'failed',
smsFailureReason: failureReason,
lastSMSFailure: new Date()
});
// Se l'SMS fallisce, considera l'email come alternativa
const customer = await loyaltyService.getCustomerByPhone(customerPhone);
if (customer?.email) {
await loyaltyService.suggestAlternativeChannel(customer.email, 'email');
}
console.warn(`SMS fallito per ${customerPhone}: ${failureReason}`);
}
// Gestisci le risposte SMS (comunicazione bidirezionale)
async function handleSMSReply(event) {
const customerPhone = event.phone;
const replyText = event.text.toLowerCase().trim();
// Elabora le risposte comuni
if (replyText === 'stop' || replyText === 'unsubscribe') {
await loyaltyService.unsubscribeFromSMS(customerPhone);
} else if (replyText === 'help' || replyText === 'info') {
await loyaltyService.sendSMSHelp(customerPhone);
} else {
// Inoltra al servizio clienti
await loyaltyService.forwardSMSToSupport(customerPhone, replyText);
}
console.log(`Risposta SMS da ${customerPhone}: "${replyText}"`);
}

Passo 2: Configura il Webhook in Brevo

Tramite Dashboard Brevo

  1. Accedi al tuo account Brevo
  2. Vai su Sviluppatori > Webhook
  3. Fai clic su “Aggiungi un nuovo webhook”
  4. Configura le impostazioni webhook:
{
"url": "https://your-tajo-domain.com/webhooks/brevo",
"description": "Integrazione Piattaforma Fedeltà Tajo",
"events": [
"delivered",
"opened",
"clicked",
"bounced",
"hard_bounced",
"spam",
"unsubscribed",
"sms_delivered",
"sms_failed",
"sms_reply",
"contact_created",
"contact_updated"
]
}

Tramite 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: 'Integrazione Piattaforma Fedeltà 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 creato con successo:', response.id);
return response;
} catch (error) {
console.error('Errore nella creazione del webhook:', error);
throw error;
}
}

Passo 3: Implementazione della Sicurezza

Variabili d’Ambiente

Terminal window
# .env file
BREVO_WEBHOOK_SECRET=your-super-secure-webhook-secret-here
BREVO_API_KEY=xkeysib-your-api-key-here
WEBHOOK_RATE_LIMIT=1000
WEBHOOK_TIMEOUT=5000

Rate Limiting

import rateLimit from 'express-rate-limit';
const webhookLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minuti
max: 1000, // Limita ogni IP a 1000 richieste per windowMs
message: 'Troppe richieste webhook da questo IP',
standardHeaders: true,
legacyHeaders: false,
});
app.use('/webhooks/brevo', webhookLimiter);

Whitelist IP (Opzionale)

const brevoIPs = [
'185.41.28.0/24',
'185.41.29.0/24',
'217.182.196.0/24'
];
function isBrevoIP(ip) {
// Implementa il controllo degli intervalli 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: 'Forbidden: Invalid source IP' });
}
next();
});

Passo 4: Test dei Webhook

Gestore di Test Webhook

// Endpoint di test per la verifica del webhook
app.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 di test ricevuto:', testEvent);
res.status(200).json({
success: true,
message: 'Webhook di test elaborato con successo',
receivedAt: new Date().toISOString()
});
});

Test Manuale

Terminal window
# Testa l'endpoint webhook con curl
curl -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
}'

Passo 5: Monitoraggio e Logging

Monitoraggio 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' })
]
});
// Aggiungi middleware di monitoraggio
app.use('/webhooks/brevo', (req, res, next) => {
const startTime = Date.now();
res.on('finish', () => {
const duration = Date.now() - startTime;
webhookLogger.info('Webhook elaborato', {
method: req.method,
url: req.url,
statusCode: res.statusCode,
duration: duration,
userAgent: req.headers['user-agent'],
contentLength: req.headers['content-length']
});
});
next();
});

Passo 6: Gestione degli Errori e Recupero

Logica di Retry

class WebhookProcessor {
constructor() {
this.maxRetries = 3;
this.retryDelay = 1000; // 1 secondo
}
async processEvent(event, retries = 0) {
try {
await this.handleEvent(event);
} catch (error) {
if (retries < this.maxRetries && this.isRetryableError(error)) {
console.warn(`Elaborazione webhook fallita, nuovo tentativo... (${retries + 1}/${this.maxRetries})`);
await this.delay(this.retryDelay * Math.pow(2, retries)); // Backoff esponenziale
return this.processEvent(event, retries + 1);
}
// Numero massimo di tentativi raggiunto o errore non recuperabile
await this.handleFailedEvent(event, error);
throw error;
}
}
isRetryableError(error) {
// Riprova su fallimenti temporanei
return error.code === 'ECONNRESET' ||
error.code === 'ETIMEDOUT' ||
(error.status >= 500 && error.status < 600);
}
delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
}

Risoluzione dei Problemi Comuni

1. Verifica della Firma Fallita

// Debug della verifica della firma
function debugSignature(payload, receivedSignature) {
const expectedSignature = crypto
.createHmac('sha256', process.env.BREVO_WEBHOOK_SECRET)
.update(payload)
.digest('hex');
console.log('Firma ricevuta:', receivedSignature);
console.log('Firma attesa:', expectedSignature);
console.log('Lunghezza payload:', payload.length);
return expectedSignature === receivedSignature.replace('sha256=', '');
}

2. Eventi Mancanti

Verifica la configurazione del webhook:

async function auditWebhookConfig() {
const webhooksApi = new WebhooksApi();
try {
const webhooks = await webhooksApi.getWebhooks();
webhooks.webhooks.forEach(webhook => {
console.log('Webhook ID:', webhook.id);
console.log('URL:', webhook.url);
console.log('Events:', webhook.events);
console.log('Stato:', webhook.is_enabled ? 'abilitato' : 'disabilitato');
});
} catch (error) {
console.error('Errore nell\'audit dei webhook:', error);
}
}

3. Alta Latenza

Ottimizza l’elaborazione dei webhook:

// Elabora i webhook in modo asincrono
app.post('/webhooks/brevo', async (req, res) => {
// Verifica la firma rapidamente
if (!verifyWebhookSignature(req.body, req.headers['x-brevo-signature'])) {
return res.status(401).json({ error: 'Unauthorized' });
}
// Rispondi immediatamente
res.status(200).json({ success: true });
// Elabora l'evento in modo asincrono
const event = JSON.parse(req.body.toString());
webhookQueue.add('process event', { event }, {
attempts: 3,
backoff: {
type: 'exponential',
delay: 2000
}
});
});

Passi Successivi

Assistente AI

Ciao! Chiedimi qualsiasi cosa sulla documentazione.

Inizia gratis con Brevo