# Webhooks

> Receive real-time message, session, and WhatsApp account events from Sendable.

Source: https://wav1.recrav.com/docs/webhooks

## How Webhooks Work [#how-webhooks-work]

1. You configure a webhook URL in your session settings.
2. Sendable sends HTTP POST requests to your URL when subscribed events occur.
3. Your application verifies the signature, processes the event, and returns HTTP 200 quickly.

## Setting Up Webhooks [#setting-up-webhooks]

### 1. Create an Endpoint [#1-create-an-endpoint]

Your endpoint must:

* Accept POST requests
* Preserve the raw request body for signature verification
* Return HTTP 200 quickly, ideally in under 5 seconds
* Handle duplicate events because delivery is at-least-once

Example in Express:

```typescript
import express from 'express'
import { Sendable } from '@sendable-dev/sdk'

const sendable = new Sendable({
  apiKey: process.env.SENDABLE_API_KEY!,
  apiKeyScope: 'session',
  webhookSecret: process.env.SENDABLE_WEBHOOK_SECRET,
})

app.post('/webhook', express.raw({ type: 'application/json' }), async (req, res) => {
  const payload = req.body.toString()

  let event
  try {
    event = await sendable.webhooks.verifyAndParse(payload, req.headers)
  } catch {
    return res.status(401).send('Invalid signature')
  }

  processEvent(event).catch(console.error)
  res.sendStatus(200)
})
```

### 2. Configure in Dashboard or via the API [#2-configure-in-dashboard-or-via-the-api]

1. Go to your session
2. Navigate to `Webhooks`
3. Click `Add Webhook`
4. Enter your URL
5. Select event types
6. Save

Or create it with a session API key (`GET /webhooks/event-types` lists every type):

```typescript
const webhook = await sendable.webhooks.create({
  https_url: 'https://your-app.com/webhook',
  event_types: ['message.received', 'message.delivered', 'group.join-request'],
})
// webhook.webhook_secret -> SENDABLE_WEBHOOK_SECRET
```

`sendable.webhooks` also has `list`, `get`, `update`, `delete`, `rotateSecret`, `listLogs`, and `retryDelivery`.

### 3. Keep the Secret Safe [#3-keep-the-secret-safe]

Each webhook endpoint has a signing secret in the form `whsec_...`. Store it securely and pass it into the SDK as `webhookSecret`.

## Event Types [#event-types]

### Message Events [#message-events]

| Event                       | Description                                                                                              |
| --------------------------- | -------------------------------------------------------------------------------------------------------- |
| `message.sent`              | WhatsApp accepted a message sent through the API                                                         |
| `message.delivered`         | First `SENT`/`DELIVERED` status for an outbound message                                                  |
| `message.read`              | Recipient read the message                                                                               |
| `message.failed`            | A send through the API failed for good before WhatsApp accepted it (once per send, after the last retry) |
| `message.received`          | Incoming direct message received                                                                         |
| `message-personal.received` | Incoming personal-chat message received                                                                  |
| `message-group.received`    | Incoming group or community message received                                                             |

### Session Events [#session-events]

| Event                         | Description                            |
| ----------------------------- | -------------------------------------- |
| `session.socket-connected`    | WhatsApp socket connected successfully |
| `session.socket-disconnected` | WhatsApp socket disconnected           |

### Normalized Events [#normalized-events]

These carry the same `data` as `GET /v1/events`, so anything a webhook missed can be replayed from the feed.

| Area                   | Events                                                                                                            |
| ---------------------- | ----------------------------------------------------------------------------------------------------------------- |
| Messages               | `message.deleted`, `message.edited`, `message.reaction`                                                           |
| Status                 | `status.received` (only when the session opted in to storing received statuses), `status.posted`                  |
| Chats                  | `chat.upsert`, `chat.updated`, `chat.deleted`, `chat.locked`                                                      |
| Groups and communities | `group.upserted`, `group.updated`, `group.participants.updated`, `group.join-request`, `group.member-tag.updated` |
| Contacts               | `contact.upserted`, `contact.updated`                                                                             |
| Business labels        | `label.edited`, `label.association.updated`                                                                       |
| Calls                  | `call.updated`                                                                                                    |
| Channels               | `newsletter.reaction`, `newsletter.view`, `newsletter.participants.updated`, `newsletter.settings.updated`        |
| Account                | `settings.updated`, `message-capping.updated`, `blocklist.set`, `blocklist.updated`                               |
| History sync           | `history.synced`, `history.status`                                                                                |

See [Webhook Events](/docs/webhook-events) for payload examples.

## Security [#security]

### Verify Signatures [#verify-signatures]

Sendable signs webhooks using the [Standard Webhooks](https://www.standardwebhooks.com) scheme. Every request includes:

* `webhook-id`: unique message ID, the same on every retry of that message
* `webhook-timestamp`: Unix time in seconds when the attempt was sent
* `webhook-signature`: `v1,<base64 HMAC-SHA256>` of `{webhook-id}.{webhook-timestamp}.{raw body}`

The SDK also accepts the older `svix-*` header names.

The safest path is to verify and parse in one step:

```typescript
const event = await sendable.webhooks.verifyAndParse(payload, req.headers)
```

If you want to separate verification from parsing, use:

```typescript
await sendable.webhooks.assertSignature(payload, req.headers)
const event = JSON.parse(payload)
```

### Use HTTPS [#use-https]

Webhook URLs must use HTTPS. URLs that point to localhost, private networks, or cloud metadata addresses are rejected, and redirects are not followed.

## Best Practices [#best-practices]

### Respond Quickly [#respond-quickly]

Do the verification work inline, then hand off processing:

```typescript
app.post('/webhook', express.raw({ type: 'application/json' }), async (req, res) => {
  const payload = req.body.toString()
  const event = await sendable.webhooks.verifyAndParse(payload, req.headers)

  queueWebhook(event).catch(console.error)
  res.sendStatus(200)
})
```

### Handle Retries [#handle-retries]

Webhook delivery is at-least-once. Any response other than 2xx, or no response within 15 seconds, counts as a failure. Sendable retries up to the endpoint's **max retries** setting, waiting **retry interval** seconds before the first retry and doubling the wait each time (capped at 10 hours). Retries reuse the same `webhook-id`, so you can use it to deduplicate.

Delivery attempts are kept for 30 days in the webhook logs (`GET /webhooks/:webhookId/logs`). Re-send one delivery now with `POST /webhooks/:webhookId/logs/:deliveryId/retry`; it keeps the same `webhook-id`.

### Use Idempotency [#use-idempotency]

Use a stable key built from the envelope:

```typescript
async function processEvent(event) {
  const id = event.data.id ?? event.data.sessionId
  const idempotencyKey = `${event.type}-${id}-${event.createdAt}`

  if (await alreadyProcessed(idempotencyKey)) {
    return
  }

  await handleEvent(event)
}
```

### Log the Envelope [#log-the-envelope]

```typescript
console.log('webhook', {
  type: event.type,
  createdAt: event.createdAt,
  id: event.data.id ?? event.data.sessionId ?? null,
})
```

## Troubleshooting [#troubleshooting]

### Invalid Signature [#invalid-signature]

* Confirm you are passing the raw request body, not `JSON.stringify(req.body)`
* Confirm `SENDABLE_WEBHOOK_SECRET` matches the endpoint secret from the dashboard
* Confirm your framework has not consumed or transformed the body before verification

### Missing Events [#missing-events]

* Confirm the webhook is active
* Confirm the subscribed event type matches the event you expect
* Check the delivery logs in the dashboard or with `GET /webhooks/:webhookId/logs`
* For `status.received`, confirm the session opted in with `PUT /v1/status/settings` `{ "storeReceived": true }`

### Timeouts [#timeouts]

* Return HTTP 200 immediately after verification
* Move heavy work into a queue or background job
