> ## Documentation Index
> Fetch the complete documentation index at: https://docs.play2sell.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Webhooks

> Configura webhooks para recibir notificaciones en tiempo real sobre eventos que ocurren en SalesOS.

# Webhooks

Los webhooks te permiten recibir notificaciones HTTP en tiempo real cuando ocurren eventos en SalesOS. En lugar de consultar la API periódicamente, SalesOS envía los datos directamente a tu endpoint.

## ¿Cómo funcionan?

<Steps>
  <Step title="Registra tu endpoint">
    Configura la URL que recibirá las notificaciones.
  </Step>

  <Step title="Selecciona los eventos">
    Elige qué eventos deseas recibir.
  </Step>

  <Step title="Recibe las notificaciones">
    SalesOS envía una solicitud POST a tu endpoint cada vez que ocurre un evento suscrito.
  </Step>

  <Step title="Confirma la recepción">
    Tu endpoint debe responder con un código `200` para confirmar que recibió la notificación.
  </Step>
</Steps>

## Eventos disponibles

<Tabs>
  <Tab title="Leads">
    | Evento               | Descripción                 |
    | -------------------- | --------------------------- |
    | `lead.created`       | Nuevo lead creado           |
    | `lead.updated`       | Lead actualizado            |
    | `lead.deleted`       | Lead eliminado              |
    | `lead.stage_changed` | Lead cambió de etapa        |
    | `lead.assigned`      | Lead asignado a un vendedor |
  </Tab>

  <Tab title="Oportunidades">
    | Evento                      | Descripción                      |
    | --------------------------- | -------------------------------- |
    | `opportunity.created`       | Nueva oportunidad creada         |
    | `opportunity.updated`       | Oportunidad actualizada          |
    | `opportunity.stage_changed` | Oportunidad cambió de etapa      |
    | `opportunity.won`           | Oportunidad cerrada como ganada  |
    | `opportunity.lost`          | Oportunidad cerrada como perdida |
  </Tab>

  <Tab title="Usuarios">
    | Evento             | Descripción          |
    | ------------------ | -------------------- |
    | `user.created`     | Nuevo usuario creado |
    | `user.updated`     | Usuario actualizado  |
    | `user.deactivated` | Usuario desactivado  |
  </Tab>

  <Tab title="Gamificación">
    | Evento                | Descripción           |
    | --------------------- | --------------------- |
    | `badge.earned`        | Usuario ganó un badge |
    | `challenge.completed` | Desafío completado    |
    | `ranking.updated`     | Ranking actualizado   |
  </Tab>
</Tabs>

## Registro de un webhook

```bash theme={null}
POST /v1/webhooks
```

```json theme={null}
{
  "url": "https://tu-servidor.com/webhook/salesos",
  "events": ["lead.created", "opportunity.won"],
  "secret": "tu_secreto_de_verificación",
  "active": true
}
```

## Formato del payload

Cada notificación de webhook tiene el siguiente formato:

```json theme={null}
{
  "id": "evt_abc123",
  "event": "lead.created",
  "timestamp": "2026-03-15T10:30:00Z",
  "data": {
    "id": "lead_xyz789",
    "name": "Juan Pérez",
    "email": "juan@empresa.com",
    "stage": "prospecting"
  }
}
```

## Verificación de firma

Cada solicitud incluye un header `X-SalesOS-Signature` con una firma HMAC-SHA256 del payload. Verifica la firma para asegurar que la solicitud proviene de SalesOS:

```python theme={null}
import hmac
import hashlib

def verify_signature(payload, signature, secret):
    expected = hmac.new(
        secret.encode(),
        payload.encode(),
        hashlib.sha256
    ).hexdigest()
    return hmac.compare_digest(expected, signature)
```

## Reintentos

Si tu endpoint no responde con un código `200`, SalesOS reintentará la entrega:

| Intento | Espera     |
| ------- | ---------- |
| 1       | Inmediato  |
| 2       | 1 minuto   |
| 3       | 5 minutos  |
| 4       | 30 minutos |
| 5       | 2 horas    |

<Warning>
  Después de 5 intentos fallidos, el webhook se desactivará automáticamente. Revisa tus logs y reactívalo manualmente.
</Warning>

<Tip>
  Procesa los webhooks de forma asíncrona. Responde con `200` inmediatamente y procesa los datos en segundo plano para evitar timeouts.
</Tip>

## Próximos pasos

<CardGroup cols={2}>
  <Card title="Integración n8n" icon="plug" href="/es/api/integrations/n8n">
    Usa webhooks con SalesOS Connect.
  </Card>

  <Card title="Integraciones personalizadas" icon="puzzle-piece" href="/es/api/integrations/custom">
    Construye integraciones a medida.
  </Card>
</CardGroup>
