Webhooks
Recibe notificaciones HTTP automáticas en tu servidor cuando ocurren eventos importantes en WAzion.
1. Introducción
Los webhooks permiten que tu servidor reciba notificaciones automáticas cuando ocurren eventos específicos en WAzion. En lugar de consultar periódicamente si hay novedades, WAzion envía una petición HTTP POST a tu servidor cuando algo relevante sucede.
¿Cómo funciona?
- 1 Configuras una URL de tu servidor en el Dashboard de WAzion
- 2 Seleccionas qué eventos quieres recibir
- 3 Cuando ocurre un evento, WAzion envía un POST a tu URL
- 4 Tu servidor procesa el evento y responde con HTTP 200
Casos de uso
- • Sincronizar nuevos contactos con tu CRM
- • Crear leads automáticamente
- • Disparar automatizaciones en Zapier/Make
- • Notificar a sistemas internos
2. Eventos Disponibles
phone.detected
PrincipalSe dispara cuando se detecta un nuevo número de teléfono en una conversación. Útil para capturar leads automáticamente.
Payload de ejemplo
{
"event_type": "phone.detected",
"phone": "+34612345678",
"detected_at": "2025-01-15T14:30:00Z",
"shop_id": 123,
"conversation_hash": "a1b2c3d4e5f6..."
}
Campos del payload
| event_type | Tipo de evento |
| phone | Número detectado (E.164) |
| detected_at | Fecha/hora ISO 8601 |
| shop_id | ID de tu tienda en WAzion |
| conversation_hash | Hash único de la conversación |
test
Evento de prueba que puedes disparar manualmente desde el Dashboard para verificar que tu endpoint funciona correctamente.
{
"event_type": "test",
"message": "Este es un webhook de prueba desde WAzion",
"timestamp": "2025-01-15T14:30:00+01:00",
"shop_id": 123,
"test": true
}
3. Headers HTTP
WAzion envía los siguientes headers en cada petición webhook:
| Header | Descripción | Ejemplo |
|---|---|---|
| Content-Type | Tipo de contenido | application/json |
| User-Agent | Identificador de WAzion | WAzion-Webhooks/1.0 |
| X-Webhook-ID | ID único del webhook (formato wh_XXXXXXXX) | wh_00012345 |
| X-Webhook-Event | Tipo de evento | phone.detected |
| X-Webhook-Attempt | Número de intento (1-6) | 1 |
| X-Webhook-Timestamp | Unix timestamp de envío | 1705329000 |
| X-Webhook-Signature | Firma HMAC-SHA256 hex (si hay secret) | a1b2c3d4e5f6... |
4. Firma HMAC-SHA256
Si configuras un webhook secret, WAzion firmará cada petición usando HMAC-SHA256. Esto te permite verificar que la petición realmente viene de WAzion.
Cómo se genera la firma
// 1. Concatenar timestamp + "." + payload JSON
signature_payload = timestamp + "." + payload_json
// 2. Calcular HMAC-SHA256 y convertir a hexadecimal
signature = HMAC-SHA256(signature_payload, webhook_secret).toHex()
// 3. El header X-Webhook-Signature contiene la firma directamente:
"a1b2c3d4e5f6789..." // Sin prefijo, solo el hash hex
Verificación en PHP
<?php
function verificarFirmaWebhook($payload, $signatureRecibida, $secret, $timestamp) {
// Verificar que el timestamp no sea muy antiguo (5 min)
if (abs(time() - intval($timestamp)) > 300) {
return false;
}
// Construir payload firmado
$signedPayload = $timestamp . '.' . $payload;
// Calcular firma esperada
$expectedSignature = hash_hmac('sha256', $signedPayload, $secret);
// Comparar de forma segura (timing-safe)
return hash_equals($expectedSignature, $signatureRecibida);
}
// Uso:
$payload = file_get_contents('php://input');
$signature = $_SERVER['HTTP_X_WEBHOOK_SIGNATURE'] ?? '';
$timestamp = $_SERVER['HTTP_X_WEBHOOK_TIMESTAMP'] ?? '';
$secret = 'tu-webhook-secret';
if (!verificarFirmaWebhook($payload, $signature, $secret, $timestamp)) {
http_response_code(401);
exit('Firma inválida');
}
Verificación en Node.js
const crypto = require('crypto');
function verificarFirmaWebhook(payload, signatureRecibida, secret, timestamp) {
// Verificar que el timestamp no sea muy antiguo (5 min)
const currentTime = Math.floor(Date.now() / 1000);
if (Math.abs(currentTime - parseInt(timestamp)) > 300) {
return false;
}
// Construir payload firmado
const signedPayload = `${timestamp}.${payload}`;
// Calcular firma esperada
const expectedSignature = crypto
.createHmac('sha256', secret)
.update(signedPayload)
.digest('hex');
// Comparar de forma segura (timing-safe)
return crypto.timingSafeEqual(
Buffer.from(signatureRecibida),
Buffer.from(expectedSignature)
);
}
Importante: También deberías verificar que el timestamp no sea muy antiguo (ej: máximo 5 minutos) para prevenir ataques de replay.
5. Especificaciones Técnicas
Timeouts
| Timeout por petición | 10 segundos |
| Máximo en cola | 100 webhooks |
Reintentos
| Máximo de intentos | 6 |
| Estrategia | Backoff exponencial |
Calendario de reintentos
Después del intento 6, el webhook se marca como fallo permanente.
Respuestas aceptadas
Cualquier código 2xx se considera éxito.
Códigos que activan reintento
Códigos sin reintento (fallo permanente)
Deduplicación automática
WAzion evita enviar el mismo número de teléfono dos veces. Se almacena un hash SHA256 de cada teléfono enviado. Si el teléfono ya fue notificado anteriormente, no se envía de nuevo.
Rate Limiting
Máximo 100 webhooks en cola por tienda. Si se supera el límite, los nuevos webhooks se descartan. El procesador envía máximo 50 webhooks por ejecución con 1 segundo de delay entre cada uno.
Configuración de conexión
Los webhooks NO siguen redirecciones. Tu endpoint debe responder directamente sin redireccionar.
6. Código de Ejemplo Completo
<?php
// webhook-handler.php
header('Content-Type: application/json');
// Configuración
$webhookSecret = 'tu-webhook-secret'; // Deja vacío si no usas firma
// Obtener datos
$payload = file_get_contents('php://input');
$signature = $_SERVER['HTTP_X_WEBHOOK_SIGNATURE'] ?? '';
$timestamp = $_SERVER['HTTP_X_WEBHOOK_TIMESTAMP'] ?? '';
$eventType = $_SERVER['HTTP_X_WEBHOOK_EVENT'] ?? '';
// Verificar firma (si hay secret configurado)
if ($webhookSecret) {
$expectedSignature = hash_hmac(
'sha256',
$timestamp . '.' . $payload,
$webhookSecret
);
if (!hash_equals($expectedSignature, $signature)) {
http_response_code(401);
echo json_encode(['error' => 'Invalid signature']);
exit;
}
// Verificar timestamp (máximo 5 minutos de antigüedad)
if (abs(time() - intval($timestamp)) > 300) {
http_response_code(401);
echo json_encode(['error' => 'Timestamp too old']);
exit;
}
}
// Decodificar payload
$data = json_decode($payload, true);
// Procesar según tipo de evento
switch ($eventType) {
case 'phone.detected':
$phone = $data['phone'];
$shopId = $data['shop_id'];
// Guardar en tu base de datos, CRM, etc.
guardarNuevoLead($phone, $shopId);
echo json_encode(['status' => 'ok', 'message' => 'Lead saved']);
break;
case 'test':
// Evento de prueba
echo json_encode(['status' => 'ok', 'message' => 'Test received']);
break;
default:
echo json_encode(['status' => 'ok', 'message' => 'Event not handled']);
}
function guardarNuevoLead($phone, $shopId) {
// Tu lógica aquí: guardar en BD, enviar a CRM, etc.
error_log("Nuevo lead: $phone de shop $shopId");
}
const express = require('express');
const crypto = require('crypto');
const app = express();
const WEBHOOK_SECRET = 'tu-webhook-secret'; // Deja vacío si no usas firma
// Middleware para raw body
app.use('/webhook', express.raw({ type: 'application/json' }));
app.post('/webhook', (req, res) => {
const payload = req.body.toString();
const signature = req.headers['x-webhook-signature'] || '';
const timestamp = req.headers['x-webhook-timestamp'] || '';
const eventType = req.headers['x-webhook-event'] || '';
// Verificar firma (si hay secret)
if (WEBHOOK_SECRET) {
const expectedSignature = crypto
.createHmac('sha256', WEBHOOK_SECRET)
.update(`${timestamp}.${payload}`)
.digest('hex');
const sigBuffer = Buffer.from(signature);
const expectedBuffer = Buffer.from(expectedSignature);
if (sigBuffer.length !== expectedBuffer.length ||
!crypto.timingSafeEqual(sigBuffer, expectedBuffer)) {
return res.status(401).json({ error: 'Invalid signature' });
}
// Verificar timestamp
if (Math.abs(Date.now() / 1000 - parseInt(timestamp)) > 300) {
return res.status(401).json({ error: 'Timestamp too old' });
}
}
const data = JSON.parse(payload);
// Procesar evento
switch (eventType) {
case 'phone.detected':
console.log(`Nuevo lead: ${data.phone} de shop ${data.shop_id}`);
// Tu lógica aquí
break;
case 'test':
console.log('Test webhook received');
break;
}
res.json({ status: 'ok' });
});
app.listen(3000, () => console.log('Webhook server running on port 3000'));
Historial de cambios
Sin cambios recientes en esta documentación.