Riferimento Tipi di Evento

Questo riferimento completo descrive tutti i tipi di evento webhook disponibili in Brevo, con esempi specifici per l’integrazione con la piattaforma fedeltà Tajo.

Eventi Email

delivered

Attivato quando un’email viene consegnata con successo alla casella del destinatario.

Esempio di Payload:

{
"event": "delivered",
"email": "[email protected]",
"id": 123456,
"date": "2024-01-25 14:30:00",
"ts": 1640995200,
"message-id": "<[email protected]>",
"template_id": 101,
"tags": ["loyalty", "points-earned"],
"sending_ip": "185.107.232.1",
"event_id": "evt_abc123"
}

Casi d’Uso per l’Integrazione Tajo:

  • Aggiorna il tasso di successo delle consegne nei profili clienti
  • Attiva azioni di follow-up per le campagne fedeltà
  • Monitora le prestazioni di consegna email per livello
async function handleEmailDelivered(event) {
const customer = await loyaltyService.getCustomer(event.email);
// Aggiorna le statistiche di consegna
await loyaltyService.updateEngagement(event.email, {
emailsDelivered: customer.emailsDelivered + 1,
lastEmailDelivered: new Date(event.date),
deliveryRate: calculateDeliveryRate(customer)
});
// Traccia la consegna della campagna fedeltà
if (event.tags.includes('loyalty')) {
await loyaltyService.trackCampaignMetric('loyalty_email_delivered', {
email: event.email,
template_id: event.template_id,
tier: customer.loyaltyTier
});
}
}

opened

Attivato quando un destinatario apre un’email (traccia il caricamento del pixel).

Esempio di Payload:

{
"event": "opened",
"email": "[email protected]",
"date": "2024-01-25 15:45:00",
"ts": 1641000300,
"message-id": "<[email protected]>",
"template_id": 101,
"tags": ["loyalty", "tier-upgrade"],
"user-agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X)",
"geo": {
"country": "US",
"region": "CA",
"city": "San Francisco"
}
}

Casi d’Uso per l’Integrazione Tajo:

  • Aumenta i punteggi di coinvolgimento dei clienti
  • Traccia l’efficacia delle campagne fedeltà
  • Attiva premi basati sul comportamento
  • Personalizza le comunicazioni future
async function handleEmailOpened(event) {
const customer = await loyaltyService.getCustomer(event.email);
// Coinvolgimento significativo - aumenta il punteggio
await loyaltyService.updateEngagement(event.email, {
emailsOpened: customer.emailsOpened + 1,
lastEmailOpened: new Date(event.date),
engagementScore: customer.engagementScore + 5,
preferredDevice: getDeviceType(event['user-agent'])
});
// Premia il coinvolgimento per i membri fedeltà
if (event.tags.includes('loyalty') && customer.loyaltyTier) {
await loyaltyService.awardEngagementBonus(event.email, {
type: 'email_engagement',
points: getEngagementPoints(customer.loyaltyTier),
reason: 'Email aperta'
});
}
}

clicked

Attivato quando un destinatario fa clic su un link in un’email.

Esempio di Payload:

{
"event": "clicked",
"email": "[email protected]",
"date": "2024-01-25 16:20:00",
"ts": 1641002400,
"message-id": "<[email protected]>",
"template_id": 101,
"tags": ["loyalty", "rewards-reminder"],
"link": "https://yourdomain.com/rewards?utm_source=brevo&utm_campaign=loyalty",
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
}

Casi d’Uso per l’Integrazione Tajo:

  • Traccia le prestazioni del funnel di conversione
  • Assegna bonus per click-through
  • Identifica i contenuti di alto valore
  • Ottimizza il flusso email-sito web
async function handleEmailClicked(event) {
const customer = await loyaltyService.getCustomer(event.email);
const clickedUrl = new URL(event.link);
// Coinvolgimento di alto valore
await loyaltyService.updateEngagement(event.email, {
emailsClicked: customer.emailsClicked + 1,
lastEmailClicked: new Date(event.date),
engagementScore: customer.engagementScore + 15,
clickThroughRate: calculateCTR(customer)
});
// Traccia tipi specifici di link
if (clickedUrl.pathname.includes('/rewards')) {
await loyaltyService.trackEvent(event.email, 'Rewards Page Clicked', {
source: 'email',
campaign: event.template_id,
utm_campaign: clickedUrl.searchParams.get('utm_campaign')
});
// Assegna bonus per l'esplorazione
await loyaltyService.awardEngagementBonus(event.email, {
type: 'rewards_exploration',
points: 10,
reason: 'Cliccato link premi'
});
}
}

bounced / hard_bounced

Attivato quando un’email rimbalza (fallimento temporaneo) o rimbalza definitivamente (fallimento permanente).

Esempio di Payload:

{
"event": "hard_bounced",
"email": "[email protected]",
"date": "2024-01-25 14:35:00",
"ts": 1640995500,
"message-id": "<[email protected]>",
"template_id": 101,
"tags": ["loyalty"],
"reason": "550 5.1.1 User unknown",
"bounce_type": "hard"
}

Casi d’Uso per l’Integrazione Tajo:

  • Aggiorna lo stato di validità dell’email
  • Passa a canali di comunicazione alternativi
  • Pulisce il database dei clienti
  • Impedisce l’invio a indirizzi non validi
async function handleEmailBounced(event) {
const isHardBounce = event.event === 'hard_bounced' || event.bounce_type === 'hard';
if (isHardBounce) {
// Fallimento permanente - segna l'email come non valida
await loyaltyService.updateCustomerStatus(event.email, {
emailStatus: 'invalid',
emailBounced: true,
bounceReason: event.reason,
lastBounce: new Date(event.date),
communicationPreference: 'sms' // Passa a SMS se disponibile
});
// Rimuovi dalle liste di marketing email
await loyaltyService.removeFromEmailMarketing(event.email);
} else {
// Rimbalzo temporaneo - problema temporaneo
await loyaltyService.updateEngagement(event.email, {
softBounceCount: customer.softBounceCount + 1,
lastSoftBounce: new Date(event.date)
});
}
}

spam

Attivato quando un destinatario segnala un’email come spam.

Esempio di Payload:

{
"event": "spam",
"email": "[email protected]",
"date": "2024-01-25 17:10:00",
"ts": 1641005400,
"message-id": "<[email protected]>",
"template_id": 101,
"tags": ["loyalty", "promotional"]
}

Casi d’Uso per l’Integrazione Tajo:

  • Sospende immediatamente le comunicazioni email
  • Revisiona e migliora i contenuti email
  • Analizza i pattern di spam per segmento
  • Implementa processi di opt-in più rigorosi
async function handleEmailSpam(event) {
// Disabilita immediatamente il marketing email
await loyaltyService.updateCustomerPreferences(event.email, {
emailMarketing: false,
marketingEnabled: false,
spamReported: true,
spamReportDate: new Date(event.date)
});
// Avvisa il team marketing per revisione
await loyaltyService.alertMarketing('spam_complaint', {
email: event.email,
template: event.template_id,
campaign_tags: event.tags,
severity: 'high'
});
}

Eventi SMS

sms_delivered

Attivato quando un SMS viene consegnato con successo al telefono del destinatario.

Esempio di Payload:

{
"event": "sms_delivered",
"phone": "+1234567890",
"date": "2024-01-25 14:45:00",
"ts": 1640996700,
"message-id": "sms_abc123",
"tags": ["loyalty", "points-alert"],
"sender": "TAJO",
"content": "🎉 Ottime notizie! Hai guadagnato 150 punti dal tuo recente acquisto. Totale: 1.250 punti."
}

Casi d’Uso per l’Integrazione Tajo:

  • Conferma la consegna SMS avvenuta con successo
  • Traccia i tassi di coinvolgimento SMS
  • Valida l’accuratezza dei numeri di telefono
  • Monitora le prestazioni di consegna degli operatori
async function handleSMSDelivered(event) {
const customer = await loyaltyService.getCustomerByPhone(event.phone);
await loyaltyService.updateEngagement(customer.email, {
smsDelivered: customer.smsDelivered + 1,
lastSMSDelivered: new Date(event.date),
smsDeliveryRate: calculateSMSDeliveryRate(customer),
phoneStatus: 'valid'
});
// Traccia le prestazioni degli SMS fedeltà
if (event.tags.includes('loyalty')) {
await loyaltyService.trackCampaignMetric('loyalty_sms_delivered', {
phone: event.phone,
content_type: getSMSContentType(event.content),
customer_tier: customer.loyaltyTier
});
}
}

sms_failed

Attivato quando la consegna SMS fallisce.

Esempio di Payload:

{
"event": "sms_failed",
"phone": "+1234567890",
"date": "2024-01-25 14:32:00",
"ts": 1640996320,
"message-id": "sms_def456",
"tags": ["loyalty", "urgent"],
"sender": "TAJO",
"reason": "Invalid phone number format",
"error_code": "30006"
}

Casi d’Uso per l’Integrazione Tajo:

  • Aggiorna la validità del numero di telefono
  • Passa alle notifiche email
  • Pulisce il database dei numeri di telefono
  • Avvisa il servizio clienti per la verifica manuale
async function handleSMSFailed(event) {
const customer = await loyaltyService.getCustomerByPhone(event.phone);
await loyaltyService.updateCustomerStatus(customer.email, {
phoneStatus: 'invalid',
smsEnabled: false,
smsFailureReason: event.reason,
lastSMSFailure: new Date(event.date),
communicationPreference: 'email'
});
// Per le notifiche fedeltà urgenti, usa l'email come alternativa
if (event.tags.includes('urgent') || event.tags.includes('loyalty')) {
await loyaltyService.sendEmailFallback(customer.email, {
originalSMS: event.content,
reason: 'Consegna SMS fallita'
});
}
}

sms_reply

Attivato quando un destinatario risponde a un SMS.

Esempio di Payload:

{
"event": "sms_reply",
"phone": "+1234567890",
"date": "2024-01-25 15:20:00",
"ts": 1641000000,
"message-id": "sms_reply_123",
"text": "BALANCE",
"original_message_id": "sms_abc123"
}

Casi d’Uso per l’Integrazione Tajo:

  • Elabora i comandi del programma fedeltà
  • Gestisce le richieste del servizio clienti
  • Aggiorna le preferenze di comunicazione
  • Attiva risposte automatizzate
async function handleSMSReply(event) {
const customer = await loyaltyService.getCustomerByPhone(event.phone);
const replyText = event.text.toUpperCase().trim();
// Alto coinvolgimento - cliente attivamente partecipante
await loyaltyService.updateEngagement(customer.email, {
smsReplies: customer.smsReplies + 1,
lastSMSReply: new Date(event.date),
engagementScore: customer.engagementScore + 10
});
// Elabora i comandi fedeltà
switch (replyText) {
case 'BALANCE':
await loyaltyService.sendPointsBalance(event.phone);
break;
case 'REWARDS':
await loyaltyService.sendAvailableRewards(event.phone, customer.loyaltyTier);
break;
case 'TIER':
await loyaltyService.sendTierInfo(event.phone, customer);
break;
case 'HELP':
await loyaltyService.sendSMSHelp(event.phone);
break;
case 'STOP':
case 'UNSUBSCRIBE':
await loyaltyService.unsubscribeFromSMS(event.phone);
break;
default:
// Inoltra al servizio clienti
await loyaltyService.forwardToSupport(customer.email, {
channel: 'sms',
message: event.text,
timestamp: new Date(event.date)
});
}
}

Eventi Contatto

contact_created

Attivato quando viene aggiunto un nuovo contatto a Brevo.

Esempio di Payload:

{
"event": "contact_created",
"email": "[email protected]",
"date": "2024-01-25 13:15:00",
"ts": 1640992500,
"attributes": {
"FIRSTNAME": "Mario",
"LASTNAME": "Rossi",
"LOYALTY_ID": "LYL-2024-001",
"LOYALTY_TIER": "Bronze",
"LOYALTY_POINTS": 0
},
"lists": [1, 5]
}

Casi d’Uso per l’Integrazione Tajo:

  • Attiva campagne di benvenuto
  • Configura l’iscrizione al programma fedeltà
  • Inizializza il percorso del cliente
  • Assegna bonus di registrazione
async function handleContactCreated(event) {
const isLoyaltyMember = event.attributes?.LOYALTY_ID;
if (isLoyaltyMember) {
// Nuovo membro fedeltà - attiva il flusso di benvenuto
await loyaltyService.triggerWelcomeFlow(event.email, {
loyaltyId: event.attributes.LOYALTY_ID,
tier: event.attributes.LOYALTY_TIER || 'Bronze',
signupBonus: 500
});
// Assegna il bonus di registrazione
await loyaltyService.awardPoints(event.email, {
amount: 500,
reason: 'Bonus di benvenuto',
type: 'signup_bonus'
});
// Pianifica la sequenza di onboarding
await loyaltyService.scheduleOnboardingSequence(event.email, {
tier: event.attributes.LOYALTY_TIER,
preferences: event.attributes
});
}
}

contact_updated

Attivato quando le informazioni di contatto vengono aggiornate.

Esempio di Payload:

{
"event": "contact_updated",
"email": "[email protected]",
"date": "2024-01-25 16:45:00",
"ts": 1641003900,
"updated_attributes": {
"LOYALTY_POINTS": 1250,
"LOYALTY_TIER": "Silver",
"TOTAL_SPENT": 899.99
},
"previous_attributes": {
"LOYALTY_POINTS": 750,
"LOYALTY_TIER": "Bronze",
"TOTAL_SPENT": 549.99
}
}

Casi d’Uso per l’Integrazione Tajo:

  • Rileva gli aggiornamenti di livello
  • Traccia i cambiamenti del saldo punti
  • Monitora la completezza del profilo
  • Attiva campagne specifiche per livello
async function handleContactUpdated(event) {
const updated = event.updated_attributes;
const previous = event.previous_attributes;
// Controlla l'aggiornamento di livello
if (updated.LOYALTY_TIER && updated.LOYALTY_TIER !== previous.LOYALTY_TIER) {
await loyaltyService.handleTierUpgrade(event.email, {
previousTier: previous.LOYALTY_TIER,
newTier: updated.LOYALTY_TIER,
pointsBalance: updated.LOYALTY_POINTS
});
// Invia le congratulazioni
await loyaltyService.sendTierUpgradeEmail(event.email, {
newTier: updated.LOYALTY_TIER,
benefits: loyaltyService.getTierBenefits(updated.LOYALTY_TIER)
});
}
// Traccia i significativi incrementi di punti
const pointIncrease = updated.LOYALTY_POINTS - previous.LOYALTY_POINTS;
if (pointIncrease > 0) {
await loyaltyService.trackPointsEarned(event.email, {
amount: pointIncrease,
newTotal: updated.LOYALTY_POINTS,
source: 'profile_update'
});
}
}

Best Practice per l’Elaborazione degli Eventi

1. Gestione dell’Idempotenza

class WebhookProcessor {
constructor() {
this.processedEvents = new Set();
}
async processEvent(event) {
const eventKey = `${event.event}_${event.email}_${event.ts}`;
if (this.processedEvents.has(eventKey)) {
console.log('Evento duplicato ignorato:', eventKey);
return;
}
this.processedEvents.add(eventKey);
try {
await this.handleEvent(event);
} catch (error) {
this.processedEvents.delete(eventKey); // Consente il retry
throw error;
}
}
}

2. Sequenziamento degli Eventi

async function processEventInSequence(event) {
const customer = await loyaltyService.getCustomer(event.email);
const lastProcessedTime = customer.lastWebhookProcessed || 0;
// Assicura che gli eventi vengano elaborati in ordine cronologico
if (event.ts < lastProcessedTime) {
console.warn('Evento fuori ordine ricevuto, accodato per elaborazione successiva');
await loyaltyService.queueEventForLaterProcessing(event);
return;
}
await handleWebhookEvent(event);
// Aggiorna il timestamp dell'ultimo evento elaborato
await loyaltyService.updateCustomer(event.email, {
lastWebhookProcessed: event.ts
});
}

3. Elaborazione in Batch

class BatchEventProcessor {
constructor() {
this.eventBatch = [];
this.batchSize = 100;
this.flushInterval = 5000; // 5 secondi
setInterval(() => this.flushBatch(), this.flushInterval);
}
addEvent(event) {
this.eventBatch.push(event);
if (this.eventBatch.length >= this.batchSize) {
this.flushBatch();
}
}
async flushBatch() {
if (this.eventBatch.length === 0) return;
const batch = this.eventBatch.splice(0);
try {
await loyaltyService.processBatchEvents(batch);
} catch (error) {
console.error('Elaborazione batch fallita:', error);
// Riaccodata gli eventi falliti
this.eventBatch.unshift(...batch);
}
}
}

Passi Successivi

Assistente AI

Ciao! Chiedimi qualsiasi cosa sulla documentazione.

Inizia gratis con Brevo