> ## 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.

# Webhook

> Terima notifikasi real-time untuk pesan, event pengiriman, dan perubahan status instance.

# Webhook

Webhook memungkinkan Anda menerima callback HTTP secara real-time saat event terjadi pada instance WhatsApp Anda. Daripada polling API, Wappfy mendorong event ke server Anda saat terjadi.

## Event yang Didukung

Wappfy mendukung 12 jenis event webhook:

<AccordionGroup>
  <Accordion title="Event Pesan">
    | Event               | Deskripsi                                                                    |
    | ------------------- | ---------------------------------------------------------------------------- |
    | `message.received`  | Pesan masuk baru telah diterima.                                             |
    | `message.sent`      | Pesan keluar berhasil dikirim.                                               |
    | `message.delivered` | Pesan terkirim telah diterima oleh perangkat penerima (tanda centang ganda). |
    | `message.read`      | Pesan terkirim telah dibaca oleh penerima (tanda centang biru).              |
    | `message.failed`    | Pesan keluar gagal dikirim.                                                  |
    | `message.reaction`  | Seseorang bereaksi terhadap pesan dengan emoji.                              |
  </Accordion>

  <Accordion title="Event Instance">
    | Event                   | Deskripsi                                |
    | ----------------------- | ---------------------------------------- |
    | `instance.connected`    | Instance berhasil terhubung ke WhatsApp. |
    | `instance.disconnected` | Instance kehilangan koneksi WhatsApp.    |
    | `instance.qr`           | Kode QR baru tersedia untuk dipindai.    |
  </Accordion>

  <Accordion title="Event Grup & Kontak">
    | Event             | Deskripsi                                             |
    | ----------------- | ----------------------------------------------------- |
    | `group.joined`    | Peserta bergabung ke grup (termasuk bot itu sendiri). |
    | `group.left`      | Peserta meninggalkan grup.                            |
    | `contact.created` | Kontak baru disimpan atau terdeteksi.                 |
  </Accordion>
</AccordionGroup>

***

## Membuat Webhook

Daftarkan endpoint webhook untuk mulai menerima event.

<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>

**Respons:**

```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"
  }
}
```

### Opsi Konfigurasi

| Field         | Tipe      | Default   | Deskripsi                                                                            |
| ------------- | --------- | --------- | ------------------------------------------------------------------------------------ |
| `url`         | string    | **wajib** | URL HTTPS yang akan menerima permintaan POST webhook.                                |
| `events`      | string\[] | **wajib** | Array jenis event yang ingin di-subscribe.                                           |
| `instance_id` | string    | `null`    | Batasi webhook ke instance tertentu. Jika null, menerima event dari semua instance.  |
| `secret`      | string    | `null`    | Secret yang digunakan untuk menghasilkan tanda tangan HMAC untuk verifikasi payload. |
| `retry_count` | number    | `3`       | Jumlah percobaan ulang jika pengiriman gagal (0-5).                                  |
| `timeout_ms`  | number    | `10000`   | Timeout permintaan dalam milidetik (1000-30000).                                     |

<Note>
  Field `instance_id` bersifat opsional. Jika tidak diisi, webhook akan menerima event dari **semua** instance di akun Anda.
</Note>

***

## Melihat Daftar Webhook

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

**Respons:**

```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
    }
  ]
}
```

***

## Memperbarui Webhook

Perbarui URL, event, atau konfigurasi webhook yang sudah ada.

```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
  }'
```

***

## Menghapus Webhook

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

***

## Format Payload Pengiriman

Saat event terjadi, Wappfy mengirim permintaan POST ke URL webhook Anda dengan struktur berikut:

```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"
  }
}
```

### Field Payload

| Field         | Deskripsi                                                          |
| ------------- | ------------------------------------------------------------------ |
| `id`          | ID pengiriman unik. Gunakan ini untuk deduplikasi.                 |
| `event`       | Jenis event yang memicu pengiriman ini.                            |
| `instance_id` | Instance yang menghasilkan event.                                  |
| `timestamp`   | Timestamp ISO 8601 kapan event terjadi.                            |
| `data`        | Payload spesifik event. Konten bervariasi berdasarkan jenis event. |

***

## Verifikasi Tanda Tangan HMAC

Jika Anda menyediakan `secret` saat membuat webhook, setiap pengiriman akan menyertakan header `X-Wappfy-Signature` yang berisi tanda tangan HMAC-SHA256 dari body permintaan.

**Selalu verifikasi tanda tangan ini** untuk memastikan permintaan berasal dari Wappfy dan tidak diubah.

### Contoh Verifikasi

<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>
  Selalu gunakan perbandingan waktu konstan (seperti `timingSafeEqual` atau `hmac.compare_digest`) saat memverifikasi tanda tangan untuk mencegah serangan timing.
</Warning>

***

## Perilaku Percobaan Ulang

Jika server Anda tidak merespons dengan kode status `2xx` dalam waktu `timeout_ms` yang dikonfigurasi, Wappfy akan mencoba ulang pengiriman.

| Percobaan            | Jeda     |
| -------------------- | -------- |
| Percobaan ulang ke-1 | 10 detik |
| Percobaan ulang ke-2 | 60 detik |
| Percobaan ulang ke-3 | 5 menit  |
| Percobaan ulang ke-4 | 30 menit |
| Percobaan ulang ke-5 | 2 jam    |

<Note>
  Percobaan ulang berhenti saat respons `2xx` diterima atau `retry_count` habis. Jumlah percobaan ulang default adalah 3.
</Note>

### Melihat Riwayat Pengiriman

Periksa log pengiriman untuk webhook guna melihat percobaan pengiriman sebelumnya dan hasilnya.

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

**Respons:**

```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"
    }
  ]
}
```

***

## Contoh Payload Event

<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>

***

## Praktik Terbaik

<CardGroup cols={2}>
  <Card title="Respons dengan cepat" icon="bolt">
    Kembalikan status `200` dalam waktu 5 detik. Proses event secara asinkron untuk menghindari timeout.
  </Card>

  <Card title="Deduplikasi" icon="clone">
    Gunakan `id` pengiriman untuk mendeteksi dan melewati pengiriman duplikat yang disebabkan oleh percobaan ulang.
  </Card>

  <Card title="Verifikasi tanda tangan" icon="shield-halved">
    Selalu validasi header `X-Wappfy-Signature` jika Anda mengonfigurasi secret.
  </Card>

  <Card title="Gunakan HTTPS" icon="lock">
    URL webhook harus menggunakan HTTPS. Endpoint HTTP akan ditolak.
  </Card>
</CardGroup>
