Configurar Webhooks
Reciba notificaciones en tiempo real sobre mensajes entrantes, actualizaciones de estado de entrega y otros eventos en su aplicación.
Definición
¿Qué son los Webhooks?
Before you start
Antes de empezar
Asegúrese de tener lo siguiente listo antes de configurar webhooks.
Cómo funciona
Abra los ajustes de webhook
Navegue a Ajustes > Webhooks en su panel de SendSeven y haga clic en "Agregar endpoint" para crear una nueva configuración de webhook. Settings → Webhooks.

Agregue la URL del endpoint
Introduzca la URL de su endpoint HTTPS donde SendSeven enviará los eventos de webhook mediante POST. Seleccione los tipos de evento que desea recibir.
- URL: Su endpoint HTTPS público
- Eventos: Seleccione los eventos que desea recibir
- Descripción: Nota opcional sobre este webhook
- Encabezado Authorization (opcional): Encabezado de autenticación personalizado enviado con cada entrega
A través de la API también puede configurar: retry_strategy (exponential/linear/none), max_retries (predeterminado 8, rango 0–15) y timeout_seconds (predeterminado 10, solo se puede acortar)

Copie su clave secreta: se muestra solo una vez
Tras guardar, su clave secreta de webhook aparece inmediatamente. Esta es la única vez que se mostrará: cópiela ahora y almacénela de forma segura.

¡Mantenga este secreto seguro!
¡Listo!
Su webhook está ahora activo. La página de detalle muestra la URL del endpoint, los eventos suscritos, el historial de entregas y el estado de salud. Desde aquí puede re-verificar el endpoint, enviar un evento de prueba, regenerar el secreto o eliminar el webhook en cualquier momento.

Configure su Endpoint de Webhook
Express.js (Node.js)
// Express.js webhook handler
const express = require('express');
const crypto = require('crypto');
const app = express();
// Parse JSON bodies
app.use(express.json());
// Webhook endpoint
app.post('/webhooks/sendseven', (req, res) => {
// Handle verification challenge
if (req.body.type === 'sendseven_verification') {
console.log('Verification challenge received');
return res.status(200).json({ challenge: req.body.challenge });
}
// Verify signature (recommended)
const signature = req.headers['x-webhook-signature'];
const isValid = verifySignature(req.body, signature);
if (!isValid) {
return res.status(401).json({ error: 'Invalid signature' });
}
// Process the event envelope
const { type, data, id: eventId } = req.body;
switch (type) {
case 'message.received':
console.log('New message from:', data.message.from_id);
console.log('Text:', data.message.text);
break;
case 'message.sent':
case 'message.delivered':
case 'message.read':
console.log('Status update:', type, data.message.id);
break;
case 'message.failed':
console.log('Message failed:', data.message.meta);
break;
case 'email.opened':
case 'email.bounced':
case 'email.complained':
console.log('Email event:', type, data.email.id);
break;
case 'conversation.created':
case 'conversation.closed':
console.log('Conversation event:', type, data.conversation.id);
break;
case 'contact.created':
case 'contact.updated':
console.log('Contact event:', type, data.contact.id);
break;
case 'link.clicked':
console.log('Link clicked:', data.url);
break;
}
// Always respond with 200 OK
res.status(200).json({ received: true });
});
// Signature verification
function verifySignature(payload, signature) {
const secret = process.env.WEBHOOK_SECRET;
const expected = 'sha256=' + crypto
.createHmac('sha256', secret)
.update(JSON.stringify(payload))
.digest('hex');
return crypto.timingSafeEqual(
Buffer.from(signature || ''),
Buffer.from(expected)
);
}
app.listen(3000);Mostrar ejemplo de Python (Flask)
# Flask webhook handler
from flask import Flask, request, jsonify
import hmac
import hashlib
import os
app = Flask(__name__)
@app.route('/webhooks/sendseven', methods=['POST'])
def webhook():
payload = request.json
# Handle verification challenge
if payload.get('type') == 'sendseven_verification':
return jsonify({'challenge': payload['challenge']}), 200
# Verify signature (recommended)
signature = request.headers.get('X-Webhook-Signature')
if not verify_signature(request.data, signature):
return jsonify({'error': 'Invalid signature'}), 401
# Process the event envelope
event_type = payload.get('type')
data = payload.get('data')
if event_type == 'message.received':
msg = data.get('message', {})
print(f"New message from: {msg.get('from_id')}")
print(f"Text: {msg.get('text')}")
elif event_type in ('message.sent', 'message.delivered', 'message.read'):
msg = data.get('message', {})
print(f"Status update: {event_type} {msg.get('id')}")
elif event_type == 'message.failed':
msg = data.get('message', {})
print(f"Message failed: {msg.get('meta')}")
# Handle failure
# Always respond with 200 OK
return jsonify({'received': True}), 200
def verify_signature(payload, signature):
secret = os.environ.get('WEBHOOK_SECRET', '').encode()
expected = 'sha256=' + hmac.new(secret, payload, hashlib.sha256).hexdigest()
return hmac.compare_digest(signature or '', expected)
if __name__ == '__main__':
app.run(port=3000)Siempre Responda con 200
Verificación de webhook
Cuando crea un webhook o cambia su URL, SendSeven envía un desafío de verificación para confirmar que su endpoint es accesible y está bajo su control. Su servidor debe responder correctamente antes de que el webhook se active.
Cuándo ocurre la verificación
- Automáticamente al crear un webhook desde el panel
- Automáticamente al crear un webhook vía la API (POST /api/v1/webhook-endpoints)
- Automáticamente cuando se actualiza la URL del webhook
- Bajo demanda mediante el endpoint de verificación (POST /api/v1/webhook-endpoints/{id}/verify)
Lo que recibe su servidor
SendSeven envía una solicitud POST a la URL de su webhook con un desafío de verificación. La solicitud incluye un encabezado X-Sendseven-Event: verification y un cuerpo JSON que contiene una cadena de desafío única.
// Verification challenge sent by SendSeven
// POST to your webhook URL
// Headers:
// Content-Type: application/json
// X-Sendseven-Event: verification
// Authorization: <your_configured_auth_header> (if set)
{
"type": "sendseven_verification",
"challenge": "a1b2c3d4e5f6789012345678abcdef01",
"webhook_id": "wh_abc123",
"timestamp": "2026-03-05T10:30:00Z"
}Cómo debe responder su servidor
Su servidor debe responder con HTTP 200 y un cuerpo JSON que devuelva el valor del desafío. El desafío es una cadena hexadecimal de 32 caracteres.
// Your server must respond with HTTP 200
// and echo back the challenge value
{
"challenge": "a1b2c3d4e5f6789012345678abcdef01"
}Expiración de 5 minutos
No se necesita verificación de firma
Tras una verificación exitosa
Una vez que su servidor responde correctamente, el webhook se activa automáticamente (is_active: true, is_verified: true) y comenzará a recibir eventos para los tipos de eventos suscritos.
Re-verificación programática
Si cambia la URL del webhook o necesita re-verificar un endpoint, puede iniciar la verificación programáticamente a través de la API. Esto es útil para pipelines de CI/CD o configuraciones de infraestructura automatizadas.
# Manually trigger re-verification for a webhook
curl -X POST https://api.sendseven.com/api/v1/webhook-endpoints/{id}/verify \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json"Probar verificación localmente
Antes de desplegar, puede simular un desafío de verificación localmente usando cURL para asegurarse de que su handler responde correctamente:
# Simulate a verification challenge locally
curl -X POST https://your-server.com/webhooks/sendseven \
-H "Content-Type: application/json" \
-H "X-Sendseven-Event: verification" \
-d '{
"type": "sendseven_verification",
"challenge": "a1b2c3d4e5f6789012345678abcdef01",
"webhook_id": "wh_test123",
"timestamp": "2026-03-05T10:30:00Z"
}'
# Expected response: {"challenge":"a1b2c3d4e5f6789012345678abcdef01"}Referencia de Carga Útil de Eventos
Aquí hay ejemplos de las cargas útiles que recibirá para diferentes eventos:
Referencia completa del esquema
Envolvente del evento
Todos los eventos de webhook comparten esta estructura envolvente. El campo data contiene el payload específico del evento.
id — ID único del evento (usar para deduplicación)
type — Cadena de tipo de evento (p. ej., message.received)
created_at — Marca de tiempo ISO 8601 de cuando ocurrió el evento
tenant_id — Su identificador de tenant
event_id — ID del recurso que generó el evento
data — Payload específico del evento (varía según el tipo de evento)
Eventos de mensajes▼
message.received
Se dispara cuando llega un mensaje entrante de un cliente en cualquier canal de mensajería. Incluye el array completo contact_methods[] con todos los identificadores del contacto.
{
"id": "evt_a1b2c3d4e5f67890",
"type": "message.received",
"created_at": "2026-03-05T10:30:00Z",
"tenant_id": "tenant_abc123",
"event_id": "msg_abc123",
"data": {
"message": {
"id": "msg_abc123",
"conversation_id": "conv_xyz789",
"platform": "whatsapp",
"channel_id": "ch_123",
"contact_id": "ct_456",
"contact_method_id": "cm_789",
"contact_method": {
"id": "cm_789",
"method_type": "whatsapp_id",
"value": "+1234567890",
"display_name": "+1234567890",
"is_primary": true
},
"direction": "inbound",
"message_type": "text",
"text": "Hello, I need help with my order",
"status": "received",
"created_at": "2026-03-05T10:30:00Z",
"from_id": "+1234567890",
"to_id": null,
"external_id": "wamid.abc123",
"meta": {}
},
"conversation": {
"id": "conv_xyz789",
"channel_id": "ch_123",
"contact_id": "ct_456",
"status": "open",
"created_at": "2026-03-05T10:29:00Z"
},
"contact": {
"id": "ct_456",
"name": "John Doe",
"email": "john@example.com",
"phone": "+1234567890",
"contact_methods": [
{ "id": "cm_789", "method_type": "whatsapp_id", "value": "1234567890", "is_primary": true },
{ "id": "cm_790", "method_type": "phone", "value": "+1234567890", "phone_type": "mobile", "is_primary": true },
{ "id": "cm_791", "method_type": "email", "value": "john@example.com", "is_primary": true }
]
}
}
}Mostrar ejemplo con archivo adjunto
El array attachments solo está presente cuando el mensaje incluye archivos multimedia. Cada adjunto incluye un id único, content_type, file_size y dos URLs de descarga. Tipos admitidos: image, video, audio, document, sticker.
// When an image, video, or document is included,
// the "attachments" array contains structured objects.
{
"message_type": "image",
"text": "Check this out",
"attachments": [
{
"id": "att_abc123",
"type": "image",
"filename": "whatsapp_image_abc123.jpg",
"content_type": "image/jpeg",
"file_size": 245000,
"url": "https://api.sendseven.com/api/v1/attachments/att_abc123/download",
"signed_url": "https://storage.googleapis.com/...?X-Goog-Signature=..."
}
]
}Tipos de URL de adjuntos
- url: Endpoint de API estable. Requiere autenticación (API key o token de sesión). Nunca expira.
- signed_url: URL pre-firmada de GCS. No requiere autenticación. Expira después de 24 horas.
- Si la descarga multimedia de la plataforma falla, los datos sin procesar de la plataforma se pasan con un marcador "source": "platform" en lugar de los campos enriquecidos. Los tipos que no son archivos (ubicación, contactos, reacciones) no se ven afectados.
message.sent
Se dispara cuando un mensaje saliente se envía correctamente al proveedor del canal. La marca de tiempo sent_at se completa y la dirección es outbound. Cuando el mensaje incluye archivos adjuntos, el array attachments se incluye con el mismo esquema enriquecido que los mensajes entrantes.
{
"id": "evt_b2c3d4e5f6a78901",
"type": "message.sent",
"created_at": "2026-03-05T10:31:00Z",
"tenant_id": "tenant_abc123",
"event_id": "msg_def456",
"data": {
"message": {
"id": "msg_def456",
"conversation_id": "conv_xyz789",
"platform": "whatsapp",
"direction": "outbound",
"message_type": "image",
"text": "Here is the invoice for your order.",
"status": "sent",
"sent_at": "2026-03-05T10:31:00Z",
"from_id": "+1987654321",
"to_id": "+1234567890",
"attachments": [
{
"id": "att_def456",
"type": "document",
"filename": "invoice_12345.pdf",
"content_type": "application/pdf",
"file_size": 184320,
"url": "https://api.sendseven.com/api/v1/attachments/att_def456/download"
}
]
},
"conversation": { "id": "conv_xyz789", "status": "open" },
"contact": { "id": "ct_456", "name": "John Doe" }
}
}Los mensajes salientes que incluyen archivos adjuntos contienen el mismo esquema enriquecido de adjuntos (id, url, signed_url, content_type, file_size) que los mensajes entrantes.
message.failed
Se dispara cuando la entrega del mensaje falla. Incluye un campo error separado a nivel de datos con el motivo del fallo.
{
"id": "evt_e5f6a7b8c9d01234",
"type": "message.failed",
"created_at": "2026-03-05T10:31:00Z",
"tenant_id": "tenant_abc123",
"event_id": "msg_ghi789",
"data": {
"message": {
"id": "msg_ghi789",
"conversation_id": "conv_xyz789",
"platform": "whatsapp",
"direction": "outbound",
"message_type": "text",
"text": "Your order #1234 has been shipped!",
"status": "failed",
"from_id": "+1987654321",
"to_id": "+1234567890"
},
"error": "Message undeliverable",
"conversation": { "id": "conv_xyz789", "status": "open" },
"contact": { "id": "ct_456", "name": "John Doe" }
}
}El campo error está a nivel de datos (no dentro de message.meta). Los objetos conversation y contact completos también se incluyen.
Eventos de email▼
Esquema diferente
email.received
Se dispara cuando se recibe un email entrante. Incluye cabeceras completas del email, contenido del cuerpo (texto y HTML), información de hilos y cualquier adjunto.
{
"id": "evt_f6a7b8c9d0e12345",
"type": "email.received",
"created_at": "2026-03-05T10:29:00Z",
"tenant_id": "tenant_abc123",
"event_id": "em_abc123",
"data": {
"email": {
"id": "em_abc123",
"conversation_id": "conv_email_456",
"direction": "inbound",
"status": "delivered",
"subject": "Re: Order #12345",
"from_email": "john@example.com",
"from_name": "John Doe",
"to_emails": [
{ "email": "support@yourcompany.com", "name": "Support" }
],
"body_text": "Hi, I have a question about my order...",
"body_html": "<p>Hi, I have a question about my order...</p>",
"message_id": "<abc123@mail.example.com>",
"thread_id": "thread_xyz",
"integration_type": "aws_ses",
"attachment_count": 1,
"attachments": [
{ "filename": "invoice.pdf", "size": 245000 }
]
},
"conversation": {
"id": "conv_email_456",
"channel_id": "ch_email_01",
"contact_id": "ct_456",
"status": "open"
},
"contact": { "id": "ct_456", "name": "John Doe", "email": "john@example.com" }
}
}Los objetos de conversación de email incluyen campos adicionales: email_integration_id y email_thread_id para el contexto de hilos.
email.bounced
Se dispara cuando un email saliente rebota. Incluye bounce_type (Permanent/Transient), bounce_subtype y la lista de direcciones de destinatarios rebotados.
{
"id": "evt_a7b8c9d0e1f23456",
"type": "email.bounced",
"created_at": "2026-03-05T10:30:00Z",
"tenant_id": "tenant_abc123",
"data": {
"email": {
"id": "em_def456",
"direction": "outbound",
"status": "bounced",
"subject": "Your order confirmation",
"from_email": "support@yourcompany.com"
},
"bounce_type": "Permanent",
"bounce_subtype": "General",
"bounced_recipients": ["invalid@example.com"]
}
}email.opened
Se dispara cuando un destinatario abre un email (mediante píxel de seguimiento). Incluye open_count con el número acumulado de aperturas.
{
"id": "evt_b8c9d0e1f2a34567",
"type": "email.opened",
"created_at": "2026-03-05T10:45:00Z",
"tenant_id": "tenant_abc123",
"data": {
"email": {
"id": "em_def456",
"direction": "outbound",
"subject": "Your order confirmation"
},
"open_count": 3,
"contact": { "id": "ct_456", "name": "John Doe" }
}
}Eventos de conversaciones▼
conversation.created
Se dispara cuando se crea una nueva conversación. Incluye el objeto de conversación completo con el array de etiquetas y el contacto asociado.
{
"id": "evt_d0e1f2a3b4c56789",
"type": "conversation.created",
"created_at": "2026-03-05T10:29:00Z",
"tenant_id": "tenant_abc123",
"data": {
"conversation": {
"id": "conv_xyz789",
"channel_id": "ch_123",
"contact_id": "ct_456",
"status": "open",
"tags": []
},
"contact": { "id": "ct_456", "name": "John Doe" }
}
}conversation.closed
Se dispara cuando se cierra una conversación. Incluye closed_by con el ID de usuario, una marca de tiempo closed_at en la conversación y el contacto asociado.
{
"id": "evt_f2a3b4c5d6e78901",
"type": "conversation.closed",
"created_at": "2026-03-05T11:00:00Z",
"tenant_id": "tenant_abc123",
"data": {
"conversation": {
"id": "conv_xyz789",
"status": "closed",
"closed_at": "2026-03-05T11:00:00Z"
},
"closed_by": { "id": "user_789" },
"contact": { "id": "ct_456", "name": "John Doe" }
}
}Eventos de contactos▼
contact.created / contact.updated
Se dispara cuando se crea, actualiza o elimina un contacto. Los tres eventos comparten la misma estructura de payload.
{
"id": "evt_b4c5d6e7f8a90123",
"type": "contact.created",
"created_at": "2026-03-05T10:29:00Z",
"tenant_id": "tenant_abc123",
"data": {
"contact": {
"id": "ct_456",
"name": "John Doe",
"email": "john@example.com",
"phone": "+1234567890",
"contact_methods": [
{ "method_type": "phone", "value": "+1234567890", "is_primary": true },
{ "method_type": "email", "value": "john@example.com", "is_primary": true }
]
}
}
}contact.updated y contact.deleted usan la misma estructura. El campo type del evento distingue entre ellos.
Eventos de seguimiento de enlaces▼
link.clicked
Se dispara cuando se hace clic en un enlace rastreado. Incluye los detalles del enlace original, metadatos del clic (IP, tipo de dispositivo, marca de tiempo) y el contacto asociado.
{
"id": "evt_d6e7f8a9b0c12345",
"type": "link.clicked",
"created_at": "2026-03-05T10:50:00Z",
"tenant_id": "tenant_abc123",
"data": {
"link": {
"id": "lnk_abc123",
"short_code": "abc123",
"original_url": "https://example.com/offer"
},
"click": {
"ip_address": "203.0.113.42",
"device_type": "mobile",
"clicked_at": "2026-03-05T10:50:00Z"
},
"contact": { "id": "ct_456", "name": "John Doe" }
}
}Verificar Firmas de Webhook
Cada solicitud de webhook incluye un encabezado X-SendSeven-Signature. Esta es una firma HMAC-SHA256 del cuerpo de la solicitud usando su secreto de webhook.
Pasos de Verificación:
- Obtenga el cuerpo de la solicitud sin procesar (antes de analizar JSON)
- Calcule HMAC-SHA256 usando su secreto de webhook
- Compare con el encabezado X-SendSeven-Signature
- Use comparación de tiempo seguro para prevenir ataques de temporización
Mejor Práctica de Seguridad
Política de Reintentos
Si su endpoint no responde con un código de estado 2xx en 10 segundos, reintentamos la entrega. Programa predeterminado con retroceso exponencial:
| Intento | Retraso | Tiempo desde el Primer Intento |
|---|---|---|
| Intento 2 | 5 s | 5 s |
| Intento 3 | 10 s | 15 s |
| Intento 4 | 30 s | 45 s |
| Intento 5 | 2 min | 2 min 45 s |
| Intento 6 | 5 min | 7 min 45 s |
| Intento 7 | 10 min | 17 min 45 s |
| Intento 8 | 30 min | ~48 min |
Webhooks Fallidos
Cortacircuitos (Circuit Breaker)
Opciones configurables
Probar su Webhook
Pruebe su endpoint de webhook localmente usando cURL:
# Test your webhook endpoint
curl -X POST https://your-server.com/webhooks/sendseven \
-H "Content-Type: application/json" \
-H "X-Webhook-Signature: sha256=test-signature" \
-d '{
"id": "evt_test123",
"type": "message.received",
"created_at": "2026-03-05T10:30:00Z",
"tenant_id": "tenant_test",
"event_id": "msg_test123",
"data": {
"message": {
"id": "msg_test123",
"conversation_id": "conv_test456",
"platform": "whatsapp",
"direction": "inbound",
"message_type": "text",
"text": "Test message",
"status": "received",
"from_id": "+1234567890"
},
"contact": {
"id": "ct_test",
"name": "Test User",
"phone": "+1234567890"
}
}
}'Solución de Problemas
El webhook no recibe eventos▼
Verifique que:
- Su URL sea accesible públicamente (no localhost)
- Su certificado SSL sea válido (no autofirmado)
- Su servidor permita solicitudes POST
- No haya un firewall bloqueando las IPs de SendSeven
Verificación de firma fallando▼
Problemas comunes:
- Usando JSON analizado en lugar del cuerpo sin procesar
- Secreto de webhook incorrecto (copie nuevamente desde configuración)
- Middleware modificando el cuerpo de la solicitud
- Problemas de codificación (asegúrese de usar UTF-8)
Recibiendo eventos duplicados▼
Esto puede suceder si su servidor responde lentamente. Para manejar duplicados:
- Almacene el ID del evento y verifique duplicados antes de procesar
- Haga que sus manejadores de eventos sean idempotentes
- Responda con 200 lo más rápido posible (procese de forma asíncrona)
Qué puede hacer
Eventos en tiempo real
Notificaciones HTTP instantáneas cuando llegan mensajes, se cierran conversaciones o cambian contactos.
Firmado con HMAC-SHA256
Cada solicitud de webhook está firmada criptográficamente para que pueda verificar que proviene de SendSeven.
Reintento automático
Las entregas fallidas se reintentan automáticamente con retroceso exponencial: hasta 8 intentos en unos 48 minutos.
Registros de entrega
Historial completo de entregas con códigos de estado, marcas de tiempo y detalles de reintentos para cada evento de webhook.
Preguntas frecuentes
¿A qué eventos puedo suscribirme?
¿Cómo funciona el reintento de webhooks?
¿Cómo verifico las firmas de webhook?
¿Cuál es el formato del payload de webhook?
¿Puedo configurar múltiples endpoints de webhook?
¿Cómo pruebo mi endpoint de webhook?
¿Qué pasa si mi endpoint no está disponible temporalmente?
Guías relacionadas
¿Listo para comenzar?
Comienza con 100 mensajes de prueba. Acceso completo durante la prueba. No se requiere tarjeta de crédito.