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

# Webhooks

> Recibe notificaciones en tiempo real sobre mensajes, eventos de entrega y cambios de estado de instancias.

# Webhooks

Los webhooks te permiten recibir callbacks HTTP en tiempo real cuando ocurren eventos en tus instancias de WhatsApp. En lugar de consultar la API periodicamente, Wappfy envia los eventos a tu servidor a medida que ocurren.

## Eventos soportados

Wappfy soporta 12 tipos de eventos de webhook:

<AccordionGroup>
  <Accordion title="Eventos de mensaje">
    | Evento              | Descripcion                                                                     |
    | ------------------- | ------------------------------------------------------------------------------- |
    | `message.received`  | Se recibio un nuevo mensaje entrante.                                           |
    | `message.sent`      | Un mensaje saliente fue enviado exitosamente.                                   |
    | `message.delivered` | Un mensaje enviado fue entregado al dispositivo del destinatario (doble check). |
    | `message.read`      | Un mensaje enviado fue leido por el destinatario (checks azules).               |
    | `message.failed`    | Un mensaje saliente fallo al enviarse.                                          |
    | `message.reaction`  | Alguien reacciono a un mensaje con un emoji.                                    |
  </Accordion>

  <Accordion title="Eventos de instancia">
    | Evento                  | Descripcion                                       |
    | ----------------------- | ------------------------------------------------- |
    | `instance.connected`    | Una instancia se conecto exitosamente a WhatsApp. |
    | `instance.disconnected` | Una instancia perdio su conexion con WhatsApp.    |
    | `instance.qr`           | Un nuevo codigo QR esta disponible para escanear. |
  </Accordion>

  <Accordion title="Eventos de grupo y contacto">
    | Evento            | Descripcion                                                   |
    | ----------------- | ------------------------------------------------------------- |
    | `group.joined`    | Un participante se unio a un grupo (incluyendo el bot mismo). |
    | `group.left`      | Un participante salio de un grupo.                            |
    | `contact.created` | Se guardo o detecto un nuevo contacto.                        |
  </Accordion>
</AccordionGroup>

***

## Crear un webhook

Registra un endpoint de webhook para comenzar a recibir eventos.

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST https://api.wappfy.io/api/webhooks \
    -H "X-Api-Key: YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "url": "https://your-server.com/webhooks/wappfy",
      "events": ["message.received", "message.sent", "message.delivered"],
      "instance_id": "inst_abc123",
      "secret": "whsec_my_signing_secret",
      "retry_count": 3,
      "timeout_ms": 10000
    }'
  ```

  ```javascript Node.js theme={null}
  const response = await fetch("https://api.wappfy.io/api/webhooks", {
    method: "POST",
    headers: {
      "X-Api-Key": "YOUR_API_KEY",
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      url: "https://your-server.com/webhooks/wappfy",
      events: ["message.received", "message.sent", "message.delivered"],
      instance_id: "inst_abc123",
      secret: "whsec_my_signing_secret",
      retry_count: 3,
      timeout_ms: 10000,
    }),
  });

  const webhook = await response.json();
  console.log(webhook.data.id);
  ```
</CodeGroup>

**Respuesta:**

```json theme={null}
{
  "data": {
    "id": "wh_xyz789",
    "url": "https://your-server.com/webhooks/wappfy",
    "events": ["message.received", "message.sent", "message.delivered"],
    "instance_id": "inst_abc123",
    "is_active": true,
    "retry_count": 3,
    "timeout_ms": 10000,
    "created_at": "2026-02-10T12:00:00Z"
  }
}
```

### Opciones de configuracion

| Campo         | Tipo      | Predeterminado  | Descripcion                                                                                       |
| ------------- | --------- | --------------- | ------------------------------------------------------------------------------------------------- |
| `url`         | string    | **obligatorio** | La URL HTTPS que recibira las solicitudes POST del webhook.                                       |
| `events`      | string\[] | **obligatorio** | Array de tipos de eventos a los que suscribirse.                                                  |
| `instance_id` | string    | `null`          | Limita el webhook a una instancia especifica. Si es null, recibe eventos de todas las instancias. |
| `secret`      | string    | `null`          | Secreto utilizado para generar firmas HMAC para verificacion del payload.                         |
| `retry_count` | number    | `3`             | Numero de intentos de reintento en caso de fallo de entrega (0-5).                                |
| `timeout_ms`  | number    | `10000`         | Tiempo de espera de la solicitud en milisegundos (1000-30000).                                    |

<Note>
  El campo `instance_id` es opcional. Si se omite, el webhook recibira eventos de **todas** las instancias de tu cuenta.
</Note>

***

## Listar webhooks

```bash theme={null}
curl https://api.wappfy.io/api/webhooks \
  -H "X-Api-Key: YOUR_API_KEY"
```

**Respuesta:**

```json theme={null}
{
  "data": [
    {
      "id": "wh_xyz789",
      "url": "https://your-server.com/webhooks/wappfy",
      "events": ["message.received", "message.sent", "message.delivered"],
      "instance_id": "inst_abc123",
      "is_active": true,
      "retry_count": 3,
      "timeout_ms": 10000
    }
  ]
}
```

***

## Actualizar un webhook

Actualiza la URL, los eventos o la configuracion de un webhook existente.

```bash theme={null}
curl -X PATCH https://api.wappfy.io/api/webhooks/wh_xyz789 \
  -H "X-Api-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "events": ["message.received", "message.sent", "message.delivered", "message.read"],
    "is_active": true
  }'
```

***

## Eliminar un webhook

```bash theme={null}
curl -X DELETE https://api.wappfy.io/api/webhooks/wh_xyz789 \
  -H "X-Api-Key: YOUR_API_KEY"
```

***

## Formato del payload de entrega

Cuando ocurre un evento, Wappfy envia una solicitud POST a la URL de tu webhook con la siguiente estructura:

```json theme={null}
{
  "id": "dlv_abc123def456",
  "event": "message.received",
  "instance_id": "inst_abc123",
  "timestamp": "2026-02-10T14:30:00Z",
  "data": {
    "message_id": "BAE5F2C4D3B2A1",
    "chat_id": "5511999998888@s.whatsapp.net",
    "from": "5511999998888@s.whatsapp.net",
    "type": "text",
    "text": "Hello!",
    "timestamp": "2026-02-10T14:30:00Z"
  }
}
```

### Campos del payload

| Campo         | Descripcion                                                                |
| ------------- | -------------------------------------------------------------------------- |
| `id`          | ID unico de entrega. Usalo para deduplicacion.                             |
| `event`       | El tipo de evento que disparo esta entrega.                                |
| `instance_id` | La instancia que genero el evento.                                         |
| `timestamp`   | Marca de tiempo ISO 8601 de cuando ocurrio el evento.                      |
| `data`        | Payload especifico del evento. El contenido varia segun el tipo de evento. |

***

## Verificacion de firma HMAC

Si proporcionas un `secret` al crear un webhook, cada entrega incluira un header `X-Wappfy-Signature` con una firma HMAC-SHA256 del cuerpo de la solicitud.

**Verifica siempre esta firma** para asegurar que la solicitud proviene de Wappfy y no fue alterada.

### Ejemplos de verificacion

<CodeGroup>
  ```javascript Node.js (Express) theme={null}
  const crypto = require("crypto");

  function verifyWebhookSignature(req, secret) {
    const signature = req.headers["x-wappfy-signature"];
    if (!signature) return false;

    const expectedSignature = crypto
      .createHmac("sha256", secret)
      .update(JSON.stringify(req.body))
      .digest("hex");

    return crypto.timingSafeEqual(
      Buffer.from(signature),
      Buffer.from(expectedSignature)
    );
  }

  // Express middleware
  app.post("/webhooks/wappfy", (req, res) => {
    const isValid = verifyWebhookSignature(req, "whsec_my_signing_secret");

    if (!isValid) {
      return res.status(401).json({ error: "Invalid signature" });
    }

    const { event, data } = req.body;
    console.log(`Received event: ${event}`, data);

    // Always respond with 200 quickly to prevent retries
    res.status(200).json({ received: true });
  });
  ```

  ```python Python (Flask) theme={null}
  import hmac
  import hashlib
  import json
  from flask import Flask, request, jsonify

  app = Flask(__name__)
  WEBHOOK_SECRET = "whsec_my_signing_secret"

  def verify_signature(payload, signature):
      expected = hmac.new(
          WEBHOOK_SECRET.encode(),
          json.dumps(payload).encode(),
          hashlib.sha256
      ).hexdigest()
      return hmac.compare_digest(expected, signature)

  @app.route("/webhooks/wappfy", methods=["POST"])
  def handle_webhook():
      signature = request.headers.get("X-Wappfy-Signature", "")
      if not verify_signature(request.json, signature):
          return jsonify({"error": "Invalid signature"}), 401

      event = request.json["event"]
      data = request.json["data"]
      print(f"Received event: {event}", data)

      return jsonify({"received": True}), 200
  ```
</CodeGroup>

<Warning>
  Usa siempre comparacion en tiempo constante (como `timingSafeEqual` o `hmac.compare_digest`) al verificar firmas para prevenir ataques de temporizado.
</Warning>

***

## Comportamiento de reintentos

Si tu servidor no responde con un codigo de estado `2xx` dentro del `timeout_ms` configurado, Wappfy reintentara la entrega.

| Intento       | Retraso     |
| ------------- | ----------- |
| 1er reintento | 10 segundos |
| 2do reintento | 60 segundos |
| 3er reintento | 5 minutos   |
| 4to reintento | 30 minutos  |
| 5to reintento | 2 horas     |

<Note>
  Los reintentos se detienen cuando se recibe una respuesta `2xx` o se agota el `retry_count`. El conteo de reintentos predeterminado es 3.
</Note>

### Ver historial de entregas

Consulta el registro de entregas de un webhook para ver los intentos de entrega pasados y sus resultados.

```bash theme={null}
curl https://api.wappfy.io/api/webhooks/wh_xyz789/deliveries \
  -H "X-Api-Key: YOUR_API_KEY"
```

**Respuesta:**

```json theme={null}
{
  "data": [
    {
      "id": "dlv_abc123def456",
      "event": "message.received",
      "status": "delivered",
      "http_status": 200,
      "attempts": 1,
      "created_at": "2026-02-10T14:30:00Z",
      "delivered_at": "2026-02-10T14:30:01Z"
    },
    {
      "id": "dlv_ghi789jkl012",
      "event": "message.sent",
      "status": "failed",
      "http_status": 500,
      "attempts": 3,
      "created_at": "2026-02-10T14:31:00Z",
      "last_error": "Server returned 500 Internal Server Error"
    }
  ]
}
```

***

## Ejemplos de payload por evento

<AccordionGroup>
  <Accordion title="message.received">
    ```json theme={null}
    {
      "id": "dlv_abc123",
      "event": "message.received",
      "instance_id": "inst_abc123",
      "timestamp": "2026-02-10T14:30:00Z",
      "data": {
        "message_id": "BAE5F2C4D3B2A1",
        "chat_id": "5511999998888@s.whatsapp.net",
        "from": "5511999998888@s.whatsapp.net",
        "type": "text",
        "text": "Hello, I need help with my order",
        "timestamp": "2026-02-10T14:30:00Z"
      }
    }
    ```
  </Accordion>

  <Accordion title="message.delivered">
    ```json theme={null}
    {
      "id": "dlv_def456",
      "event": "message.delivered",
      "instance_id": "inst_abc123",
      "timestamp": "2026-02-10T14:30:05Z",
      "data": {
        "message_id": "BAE5A1B2C3D4E5",
        "chat_id": "5511999998888@s.whatsapp.net",
        "status": "delivered"
      }
    }
    ```
  </Accordion>

  <Accordion title="message.read">
    ```json theme={null}
    {
      "id": "dlv_ghi789",
      "event": "message.read",
      "instance_id": "inst_abc123",
      "timestamp": "2026-02-10T14:31:00Z",
      "data": {
        "message_id": "BAE5A1B2C3D4E5",
        "chat_id": "5511999998888@s.whatsapp.net",
        "status": "read"
      }
    }
    ```
  </Accordion>

  <Accordion title="message.reaction">
    ```json theme={null}
    {
      "id": "dlv_jkl012",
      "event": "message.reaction",
      "instance_id": "inst_abc123",
      "timestamp": "2026-02-10T14:32:00Z",
      "data": {
        "message_id": "BAE5F2C4D3B2A1",
        "chat_id": "5511999998888@s.whatsapp.net",
        "from": "5511999998888@s.whatsapp.net",
        "reaction": "\u2764\ufe0f"
      }
    }
    ```
  </Accordion>

  <Accordion title="instance.connected">
    ```json theme={null}
    {
      "id": "dlv_mno345",
      "event": "instance.connected",
      "instance_id": "inst_abc123",
      "timestamp": "2026-02-10T12:00:00Z",
      "data": {
        "instance_id": "inst_abc123",
        "status": "connected",
        "phone_number": "5511999998888"
      }
    }
    ```
  </Accordion>

  <Accordion title="instance.qr">
    ```json theme={null}
    {
      "id": "dlv_pqr678",
      "event": "instance.qr",
      "instance_id": "inst_abc123",
      "timestamp": "2026-02-10T11:59:00Z",
      "data": {
        "instance_id": "inst_abc123",
        "qr": "data:image/png;base64,iVBORw0KGgo..."
      }
    }
    ```
  </Accordion>

  <Accordion title="group.joined">
    ```json theme={null}
    {
      "id": "dlv_stu901",
      "event": "group.joined",
      "instance_id": "inst_abc123",
      "timestamp": "2026-02-10T15:00:00Z",
      "data": {
        "group_id": "120363012345678901@g.us",
        "participant": "5511888887777@s.whatsapp.net"
      }
    }
    ```
  </Accordion>
</AccordionGroup>

***

## Buenas practicas

<CardGroup cols={2}>
  <Card title="Responder rapidamente" icon="bolt">
    Devuelve un estado `200` dentro de 5 segundos. Procesa el evento de forma asincrona para evitar tiempos de espera.
  </Card>

  <Card title="Deduplicar" icon="clone">
    Usa el `id` de entrega para detectar y omitir entregas duplicadas causadas por reintentos.
  </Card>

  <Card title="Verificar firmas" icon="shield-halved">
    Valida siempre el header `X-Wappfy-Signature` si configuraste un secreto.
  </Card>

  <Card title="Usar HTTPS" icon="lock">
    Las URLs de webhook deben usar HTTPS. Los endpoints HTTP seran rechazados.
  </Card>
</CardGroup>
