Webhook与事件
Ricevi notifiche in tempo reale quando accadono eventi nel tuo workspace NotifyHub. I webhook inviano richieste HTTP POST al tuo server con i dettagli di ogni evento.
Configurare un endpoint
Un endpoint webhook e' un URL sul tuo server che riceve le notifiche degli eventi. Deve rispondere con un codice HTTP 2xx entro 30 secondi.
- Vai su Impostazioni → Webhook nel portale NotifyHub
- Clicca "Nuovo endpoint" e inserisci l'URL del tuo server (deve essere HTTPS)
- Seleziona gli eventi che vuoi ricevere
- Copia il Webhook Secret generato per verificare le firme HMAC
- Salva e invia un evento di test per verificare la connessione
Eventi disponibili
Puoi sottoscrivere uno o piu' dei seguenti eventi:
Inviato quando un messaggio viene consegnato con successo al canale di destinazione.
Inviato quando un destinatario risponde su un canale (WhatsApp, Telegram, Messenger, ecc.).
Aggiornamenti sullo stato di consegna: queued, sent, delivered, read, failed.
Inviato quando un nuovo contatto viene aggiunto al workspace (manualmente, via CSV, API o onboarding).
Inviato quando i dati di un contatto vengono modificati (tag, metadati, canale preferito).
Inviato quando un'automazione si attiva per un contatto.
Struttura del payload
Tutti i webhook vengono inviati come richieste POST con Content-Type application/json.
{
"id": "evt_abc123def456",
"type": "message.sent",
"created_at": "2026-05-08T14:32:00Z",
"workspace_id": "ws_xyz789",
"data": {
"message_id": "msg_abc123",
"channel": "whatsapp",
"to": "+393331234567",
"template": "order_confirmation",
"status": "sent",
"sent_at": "2026-05-08T14:32:00Z",
"recipient": {
"id": "rec_def456",
"name": "Mario Rossi",
"email": "[email protected]"
}
}
}
{
"id": "evt_ghi789jkl012",
"type": "message.received",
"created_at": "2026-05-08T14:35:12Z",
"workspace_id": "ws_xyz789",
"data": {
"message_id": "msg_def456",
"channel": "whatsapp",
"from": "+393331234567",
"body": "Quando arriva il mio ordine?",
"media": null,
"recipient": {
"id": "rec_def456",
"name": "Mario Rossi"
},
"conversation_id": "conv_mno345"
}
}
{
"id": "evt_pqr678stu901",
"type": "delivery.status",
"created_at": "2026-05-08T14:32:05Z",
"workspace_id": "ws_xyz789",
"data": {
"message_id": "msg_abc123",
"channel": "whatsapp",
"status": "delivered",
"previous_status": "sent",
"timestamp": "2026-05-08T14:32:05Z",
"error": null
}
}
Verifica firma HMAC
Ogni richiesta webhook include un header X-NotifyHub-Signature con la firma HMAC-SHA256 del body.
Verifica SEMPRE la firma per assicurarti che la richiesta provenga da NotifyHub.
Headers inviati:
X-NotifyHub-Signature— HMAC-SHA256 hex digestX-NotifyHub-Event— Tipo di evento (es.message.sent)X-NotifyHub-Delivery-Id— ID univoco della consegna (per idempotenza)X-NotifyHub-Timestamp— Unix timestamp della richiesta
<?php
// Il tuo webhook secret (dalla configurazione NotifyHub)
$secret = 'whsec_your_webhook_secret_here';
// Leggi il body raw della richiesta
$payload = file_get_contents('php://input');
// Leggi la firma dall'header
$signature = $_SERVER['HTTP_X_NOTIFYHUB_SIGNATURE'] ?? '';
// Calcola la firma attesa
$expected = hash_hmac('sha256', $payload, $secret);
// Confronto timing-safe
if (!hash_equals($expected, $signature)) {
http_response_code(401);
echo json_encode(['error' => 'Invalid signature']);
exit;
}
// Firma valida - processa l'evento
$event = json_decode($payload, true);
$type = $event['type'];
switch ($type) {
case 'message.sent':
// Gestisci messaggio inviato
break;
case 'message.received':
// Gestisci risposta ricevuta
break;
case 'delivery.status':
// Aggiorna stato consegna
break;
}
http_response_code(200);
echo json_encode(['received' => true]);
const crypto = require('crypto');
const express = require('express');
const app = express();
app.use(express.raw({ type: 'application/json' }));
const WEBHOOK_SECRET = 'whsec_your_webhook_secret_here';
app.post('/webhook/notifyhub', (req, res) => {
const signature = req.headers['x-notifyhub-signature'];
const payload = req.body;
// Calcola la firma attesa
const expected = crypto
.createHmac('sha256', WEBHOOK_SECRET)
.update(payload)
.digest('hex');
// Confronto timing-safe
if (!crypto.timingSafeEqual(
Buffer.from(expected, 'hex'),
Buffer.from(signature, 'hex')
)) {
return res.status(401).json({ error: 'Invalid signature' });
}
// Firma valida
const event = JSON.parse(payload);
console.log('Evento ricevuto:', event.type);
res.json({ received: true });
});
Sicurezza: Non elaborare MAI un webhook senza verificare la firma HMAC. Un attaccante potrebbe inviare payload falsificati al tuo endpoint.
Policy di retry
Se il tuo endpoint non risponde con un codice 2xx entro 30 secondi, NotifyHub riprova automaticamente con backoff esponenziale:
Disattivazione automatica: Se un endpoint fallisce per 3 giorni consecutivi, viene automaticamente disattivato. Riceverai un'email di notifica. Puoi riattivarlo dalla dashboard dopo aver risolto il problema.
Testare i webhook
Puoi testare il tuo endpoint localmente con curl simulando un evento NotifyHub:
# Genera la firma HMAC
SECRET="whsec_your_webhook_secret_here"
PAYLOAD='{"id":"evt_test123","type":"message.sent","created_at":"2026-05-08T14:32:00Z","workspace_id":"ws_test","data":{"message_id":"msg_test","channel":"email","to":"[email protected]","status":"sent"}}'
SIGNATURE=$(echo -n "$PAYLOAD" | openssl dgst -sha256 -hmac "$SECRET" | cut -d' ' -f2)
# Invia la richiesta
curl -X POST http://localhost:8000/webhook/notifyhub \
-H "Content-Type: application/json" \
-H "X-NotifyHub-Signature: $SIGNATURE" \
-H "X-NotifyHub-Event: message.sent" \
-H "X-NotifyHub-Delivery-Id: dlv_test123" \
-H "X-NotifyHub-Timestamp: $(date +%s)" \
-d "$PAYLOAD"
Dalla dashboard: Puoi anche inviare eventi di test direttamente dalla sezione Webhook del portale NotifyHub. Clicca "Invia test" su qualsiasi endpoint configurato.
Best practice
- Rispondi velocemente: Processa l'evento in background (queue) e rispondi subito con
200 OK - Idempotenza: Usa
X-NotifyHub-Delivery-Idper evitare di elaborare lo stesso evento due volte - HTTPS obbligatorio: Gli endpoint webhook devono usare HTTPS in produzione
- Verifica firma: Controlla SEMPRE
X-NotifyHub-Signatureprima di elaborare - Log delle consegne: Usa la sezione Deliveries del portale per monitorare successi e fallimenti