# Webhooks and events

Fonte: https://lunahia.com.br/en/docs/reference/webhooks-and-events

Where Luna delivers what arrives at your number, the secret that signs those deliveries, and the event types, each with its schema and an example.

### List webhook endpoints

`GET /v1/webhooks/endpoints`

The endpoints registered for this customer, newest first, with the endpoint limit and whether another can still be registered (limit and canCreate). Each endpoint carries deliveryStatus.

Authentication: API key. Required scope: `webhooks:read`

Topic guide: https://lunahia.com.br/en/docs/receive-events#rota-get-v1-webhooks-endpoints

#### Code examples

```bash
curl -X GET "https://api.lunahia.com.br/v1/webhooks/endpoints" \
  -H "Authorization: Bearer $LUNA_API_KEY"
```

#### Responses

**200**: Os endpoints cadastrados neste cliente, do mais recente para o mais antigo, com o limite de endpoints e se ainda dá para cadastrar outro (limit e canCreate).

```json
{
  "data": [
    {
      "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
      "url": "https://exemplo.com.br/arquivo",
      "createdAt": "YOUR_CREATEDAT",
      "updatedAt": "YOUR_UPDATEDAT",
      "previousSecretExpiresAt": "YOUR_PREVIOUSSECRETEXPIRESAT",
      "paused": true,
      "pausedAt": "YOUR_PAUSEDAT",
      "eventTypes": [
        "YOUR_EVENTTYPES"
      ],
      "externalIds": [
        "YOUR_EXTERNALIDS"
      ],
      "phoneNumberIds": [
        "YOUR_PHONENUMBERIDS"
      ],
      "headerNames": [
        "YOUR_HEADERNAMES"
      ],
      "lastDeliveryAt": "YOUR_LASTDELIVERYAT",
      "lastFailureAt": "YOUR_LASTFAILUREAT",
      "lastHttpStatus": 1,
      "deliveryStatus": "ok"
    }
  ],
  "limit": 1,
  "canCreate": true
}
```

**401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which.

```json
{
  "error": "unauthorized",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Credencial ausente ou inválida."
}
```

**403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed.

```json
{
  "error": "forbidden",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.",
  "requiredScope": "numbers:read"
}
```

**429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key.

```json
{
  "error": "rate_limited",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Requisições demais. Tente novamente em instantes."
}
```

**503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one.

```json
{
  "error": "unavailable",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Não foi possível concluir a operação agora. Tente novamente em instantes."
}
```

### Register the webhook endpoint

`POST /v1/webhooks/endpoints`

Registers your server's URL and returns the secret that signs the deliveries. headers, optional, carries up to 5 own HTTP headers that Luna sends on every delivery (for a gateway that requires a fixed token); the values are secret and no response returns them.

Authentication: API key. Required scope: `webhooks:write`

Topic guide: https://lunahia.com.br/en/docs/receive-events#rota-post-v1-webhooks-endpoints

#### Request body

`application/json`

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `url` | `string` | yes | A URL do seu servidor que vai receber os eventos. Precisa ser https e precisa resolver para um endereço público. · up to 2048 characters |
| `eventTypes` | `array<string>` | no | Os tipos de evento que este endpoint recebe, por exemplo ["message.received", "message.status"]. Ausente ou vazio quer dizer todos, inclusive os tipos que a Luna criar depois. Com a lista preenchida, o endpoint só recebe esses tipos, e um tipo novo não chega até você incluí-lo. O filtro é só por tipo. O evento webhook.test não é filtrável: ele só sai quando você o pede. Os tipos estão no guia Receber eventos. · up to 30 items |
| `externalIds` | `array<string>` | no | Os clientes seus (externalId) de que este endpoint recebe eventos, por exemplo ["cliente-42"]. Ausente ou vazio quer dizer todos. Com a lista preenchida, o endpoint só recebe eventos de números com um destes externalId, inclusive os conectados depois, e dos links de conexão com ele. Eventos que não falam de um cliente (os de template, por exemplo) só chegam se a conta do template tem um número dele. O filtro é só por identificador. · up to 100 items |
| `phoneNumberIds` | `array<string>` | no | Os números de que este endpoint recebe eventos: o UUID da Luna (o id de GET /v1/numbers) ou o id da Meta (metaPhoneNumberId), em qualquer mistura. A resposta devolve os ids da Meta, os mesmos que os eventos trazem em phone_number_id. Ausente ou vazio quer dizer todos. Um número que não é da conta responde 400. Para cobrir números que ainda serão conectados, use externalIds. · up to 100 items |
| `headers` | `object` | no | Cabeçalhos HTTP que a Luna envia em cada entrega a este endpoint, como { "X-Token": "valor" }, até 5. Para quem tem um gateway que exige um token fixo. Os valores são segredo: ficam cifrados, e nenhuma resposta os devolve, só os nomes (headerNames). Não valem os de transporte (content-type, host, content-length e afins) nem os x-luna-*. O valor tem até 1024 caracteres ASCII visíveis. No PATCH, o objeto enviado substitui o anterior, e {} remove todos. |

#### Code examples

```bash
curl -X POST "https://api.lunahia.com.br/v1/webhooks/endpoints" \
  -H "Authorization: Bearer $LUNA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
  "url": "https://exemplo.com.br/arquivo"
}'
```

#### Responses

**201**: O endpoint recém-criado, com o segredo de assinatura.

```json
{
  "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
  "url": "https://exemplo.com.br/arquivo",
  "createdAt": "YOUR_CREATEDAT",
  "updatedAt": "YOUR_UPDATEDAT",
  "previousSecretExpiresAt": "YOUR_PREVIOUSSECRETEXPIRESAT",
  "paused": true,
  "pausedAt": "YOUR_PAUSEDAT",
  "eventTypes": [
    "YOUR_EVENTTYPES"
  ],
  "externalIds": [
    "YOUR_EXTERNALIDS"
  ],
  "phoneNumberIds": [
    "YOUR_PHONENUMBERIDS"
  ],
  "headerNames": [
    "YOUR_HEADERNAMES"
  ],
  "lastDeliveryAt": "YOUR_LASTDELIVERYAT",
  "lastFailureAt": "YOUR_LASTFAILUREAT",
  "lastHttpStatus": 1,
  "deliveryStatus": "ok",
  "secret": "YOUR_SECRET"
}
```

**400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal.

```json
{
  "error": "invalid_request",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Requisição inválida.",
  "campos": [
    {
      "campo": "text.body",
      "motivo": "Não pode ficar vazio."
    }
  ]
}
```

**401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which.

```json
{
  "error": "unauthorized",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Credencial ausente ou inválida."
}
```

**403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed.

```json
{
  "error": "forbidden",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.",
  "requiredScope": "numbers:read"
}
```

**409**: The request is well formed, but the resource state does not allow it. The error field says which case it is.

```json
{
  "error": "webhook_endpoint_limit",
  "docsUrl": "https://lunahia.com.br/docs/receber-eventos",
  "message": "Este cliente já tem o máximo de endpoints de webhook, e o limite é o mesmo para todos. Remova um endpoint com DELETE /v1/webhooks/endpoints/{id} para liberar a vaga.",
  "limit": 25
}
```

**415**: The body came with a content-type the route does not read. Send application/json, or multipart/form-data on the file routes.

```json
{
  "error": "unsupported_media_type",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Envie o corpo como application/json."
}
```

**429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key.

```json
{
  "error": "rate_limited",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Requisições demais. Tente novamente em instantes."
}
```

**503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one.

```json
{
  "error": "unavailable",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Não foi possível concluir a operação agora. Tente novamente em instantes."
}
```

### List the event types

`GET /v1/webhooks/event-types`

The event types Luna delivers, which eventTypes accepts when you register or update an endpoint. Each item carries the type, which is the value to send, a sentence that says what the event is, and the group it belongs to (group and groupLabel).

Authentication: API key. Required scope: `webhooks:read`

Topic guide: https://lunahia.com.br/en/docs/receive-events#rota-get-v1-webhooks-event-types

#### Code examples

```bash
curl -X GET "https://api.lunahia.com.br/v1/webhooks/event-types" \
  -H "Authorization: Bearer $LUNA_API_KEY"
```

#### Responses

**200**: Os tipos de evento que a Luna entrega, na ordem do contrato. O evento webhook.test não está na lista: ele só sai quando você o pede.

```json
{
  "data": [
    {
      "type": "YOUR_TYPE",
      "summary": "YOUR_SUMMARY",
      "group": "messages",
      "groupLabel": "YOUR_GROUPLABEL"
    }
  ]
}
```

**401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which.

```json
{
  "error": "unauthorized",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Credencial ausente ou inválida."
}
```

**403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed.

```json
{
  "error": "forbidden",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.",
  "requiredScope": "numbers:read"
}
```

**429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key.

```json
{
  "error": "rate_limited",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Requisições demais. Tente novamente em instantes."
}
```

**503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one.

```json
{
  "error": "unavailable",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Não foi possível concluir a operação agora. Tente novamente em instantes."
}
```

### Read the webhook endpoint

`GET /v1/webhooks/endpoints/{id}`

The endpoint's configuration.

Authentication: API key. Required scope: `webhooks:read`

Topic guide: https://lunahia.com.br/en/docs/receive-events#rota-get-v1-webhooks-endpoints-id

#### Path parameters

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `id` | `string` | yes | O identificador do endpoint, devolvido no cadastro. |

#### Code examples

```bash
curl -X GET "https://api.lunahia.com.br/v1/webhooks/endpoints/YOUR_ID" \
  -H "Authorization: Bearer $LUNA_API_KEY"
```

#### Responses

**200**: A configuração do endpoint. O segredo NÃO vem aqui: ele sai uma vez, no cadastro e na rotação.

```json
{
  "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
  "url": "https://exemplo.com.br/arquivo",
  "createdAt": "YOUR_CREATEDAT",
  "updatedAt": "YOUR_UPDATEDAT",
  "previousSecretExpiresAt": "YOUR_PREVIOUSSECRETEXPIRESAT",
  "paused": true,
  "pausedAt": "YOUR_PAUSEDAT",
  "eventTypes": [
    "YOUR_EVENTTYPES"
  ],
  "externalIds": [
    "YOUR_EXTERNALIDS"
  ],
  "phoneNumberIds": [
    "YOUR_PHONENUMBERIDS"
  ],
  "headerNames": [
    "YOUR_HEADERNAMES"
  ],
  "lastDeliveryAt": "YOUR_LASTDELIVERYAT",
  "lastFailureAt": "YOUR_LASTFAILUREAT",
  "lastHttpStatus": 1,
  "deliveryStatus": "ok"
}
```

**400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal.

```json
{
  "error": "invalid_request",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Requisição inválida.",
  "campos": [
    {
      "campo": "text.body",
      "motivo": "Não pode ficar vazio."
    }
  ]
}
```

**401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which.

```json
{
  "error": "unauthorized",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Credencial ausente ou inválida."
}
```

**403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed.

```json
{
  "error": "forbidden",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.",
  "requiredScope": "numbers:read"
}
```

**404**: The resource does not exist, or is not yours. The two answers are identical, byte for byte.

```json
{
  "error": "not_found",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Recurso não encontrado."
}
```

**429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key.

```json
{
  "error": "rate_limited",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Requisições demais. Tente novamente em instantes."
}
```

**503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one.

```json
{
  "error": "unavailable",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Não foi possível concluir a operação agora. Tente novamente em instantes."
}
```

### Update the webhook endpoint

`PATCH /v1/webhooks/endpoints/{id}`

Changes the URL, pauses or resumes the endpoint, or changes the event types it receives. Send url, paused, eventTypes, externalIds, phoneNumberIds, headers or any combination: a body with none of them answers 400.

Authentication: API key. Required scope: `webhooks:write`

Topic guide: https://lunahia.com.br/en/docs/receive-events#rota-patch-v1-webhooks-endpoints-id

#### Path parameters

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `id` | `string` | yes | O identificador do endpoint, devolvido no cadastro. |

#### Request body

`application/json`

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `url` | `string` | no | A URL nova. Passa pela mesma validação do cadastro: https e endereço público. O segredo de assinatura continua o mesmo. · up to 2048 characters |
| `paused` | `boolean` | no | true pausa o endpoint: os eventos que ocorrerem enquanto ele estiver pausado não são entregues, nem depois. false o retoma, e ele passa a receber os eventos a partir desse momento. |
| `eventTypes` | `array<string>` | no | Troca a lista de tipos que o endpoint recebe: a lista enviada substitui a anterior. Lista vazia volta a receber todos. O que ocorreu antes da troca e foi filtrado não é entregue depois. · up to 30 items |
| `externalIds` | `array<string>` | no | Troca a lista de clientes de que o endpoint recebe eventos: a lista enviada substitui a anterior, e lista vazia volta a receber de todos. Vale daí em diante. · up to 100 items |
| `phoneNumberIds` | `array<string>` | no | Troca a lista de números de que o endpoint recebe eventos: a lista enviada substitui a anterior, e lista vazia volta a receber de todos. Aceita o UUID da Luna ou o id da Meta. · up to 100 items |
| `headers` | `object` | no | Cabeçalhos HTTP que a Luna envia em cada entrega a este endpoint, como { "X-Token": "valor" }, até 5. Para quem tem um gateway que exige um token fixo. Os valores são segredo: ficam cifrados, e nenhuma resposta os devolve, só os nomes (headerNames). Não valem os de transporte (content-type, host, content-length e afins) nem os x-luna-*. O valor tem até 1024 caracteres ASCII visíveis. No PATCH, o objeto enviado substitui o anterior, e {} remove todos. |

#### Code examples

```bash
curl -X PATCH "https://api.lunahia.com.br/v1/webhooks/endpoints/YOUR_ID" \
  -H "Authorization: Bearer $LUNA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
  "url": "https://exemplo.com.br/arquivo",
  "paused": true,
  "eventTypes": [
    "message.received"
  ]
}'
```

#### Responses

**200**: A configuração do endpoint. O segredo NÃO vem aqui: ele sai uma vez, no cadastro e na rotação.

```json
{
  "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
  "url": "https://exemplo.com.br/arquivo",
  "createdAt": "YOUR_CREATEDAT",
  "updatedAt": "YOUR_UPDATEDAT",
  "previousSecretExpiresAt": "YOUR_PREVIOUSSECRETEXPIRESAT",
  "paused": true,
  "pausedAt": "YOUR_PAUSEDAT",
  "eventTypes": [
    "YOUR_EVENTTYPES"
  ],
  "externalIds": [
    "YOUR_EXTERNALIDS"
  ],
  "phoneNumberIds": [
    "YOUR_PHONENUMBERIDS"
  ],
  "headerNames": [
    "YOUR_HEADERNAMES"
  ],
  "lastDeliveryAt": "YOUR_LASTDELIVERYAT",
  "lastFailureAt": "YOUR_LASTFAILUREAT",
  "lastHttpStatus": 1,
  "deliveryStatus": "ok"
}
```

**400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal.

```json
{
  "error": "invalid_request",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Requisição inválida.",
  "campos": [
    {
      "campo": "text.body",
      "motivo": "Não pode ficar vazio."
    }
  ]
}
```

**401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which.

```json
{
  "error": "unauthorized",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Credencial ausente ou inválida."
}
```

**403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed.

```json
{
  "error": "forbidden",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.",
  "requiredScope": "numbers:read"
}
```

**404**: The resource does not exist, or is not yours. The two answers are identical, byte for byte.

```json
{
  "error": "not_found",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Recurso não encontrado."
}
```

**415**: The body came with a content-type the route does not read. Send application/json, or multipart/form-data on the file routes.

```json
{
  "error": "unsupported_media_type",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Envie o corpo como application/json."
}
```

**429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key.

```json
{
  "error": "rate_limited",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Requisições demais. Tente novamente em instantes."
}
```

**503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one.

```json
{
  "error": "unavailable",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Não foi possível concluir a operação agora. Tente novamente em instantes."
}
```

### Remove the webhook endpoint

`DELETE /v1/webhooks/endpoints/{id}`

Removes the endpoint. The response is 204, and the endpoint stops receiving events.

Authentication: API key. Required scope: `webhooks:write`

Topic guide: https://lunahia.com.br/en/docs/receive-events#rota-delete-v1-webhooks-endpoints-id

#### Path parameters

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `id` | `string` | yes | O identificador do endpoint, devolvido no cadastro. |

#### Code examples

```bash
curl -X DELETE "https://api.lunahia.com.br/v1/webhooks/endpoints/YOUR_ID" \
  -H "Authorization: Bearer $LUNA_API_KEY"
```

#### Responses

**204**: No content: the operation was done and the response has no body.

**400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal.

```json
{
  "error": "invalid_request",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Requisição inválida.",
  "campos": [
    {
      "campo": "text.body",
      "motivo": "Não pode ficar vazio."
    }
  ]
}
```

**401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which.

```json
{
  "error": "unauthorized",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Credencial ausente ou inválida."
}
```

**403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed.

```json
{
  "error": "forbidden",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.",
  "requiredScope": "numbers:read"
}
```

**404**: The resource does not exist, or is not yours. The two answers are identical, byte for byte.

```json
{
  "error": "not_found",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Recurso não encontrado."
}
```

**429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key.

```json
{
  "error": "rate_limited",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Requisições demais. Tente novamente em instantes."
}
```

**503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one.

```json
{
  "error": "unavailable",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Não foi possível concluir a operação agora. Tente novamente em instantes."
}
```

### List the endpoint's deliveries

`GET /v1/webhooks/endpoints/{id}/deliveries`

The delivery attempts to the endpoint over the last 7 days, newest first: eventId, eventType, status, httpStatus (null when your server did not answer), durationMs, attempt and at. Filters: status (success or failed), eventType and since. It does not carry the body sent or what your server answered.

Authentication: API key. Required scope: `webhooks:read`

Topic guide: https://lunahia.com.br/en/docs/receive-events#rota-get-v1-webhooks-endpoints-id-deliveries

#### Path parameters

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `id` | `string` | yes | O identificador do endpoint, devolvido no cadastro. |

#### Query parameters

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `limit` | `integer` | no | Quantos itens trazer. Padrão 50, máximo 100, igual para todos. |
| `status` | `string` | no | success: só as tentativas que o seu servidor aceitou (2xx). failed: só as que falharam, com outro status ou sem resposta. |
| `eventType` | `string` | no | Só as tentativas de eventos deste tipo (um valor de GET /v1/webhooks/event-types). |
| `since` | `any` | no | Só as tentativas deste instante em diante (ISO 8601, ou a data pura, que vale meia-noite UTC). O histórico guarda 7 dias. |
| `cursor` | `string` | no | O nextCursor da página anterior. Omita na primeira. |

#### Code examples

```bash
curl -X GET "https://api.lunahia.com.br/v1/webhooks/endpoints/YOUR_ID/deliveries" \
  -H "Authorization: Bearer $LUNA_API_KEY"
```

#### Responses

**200**: O histórico de entregas do endpoint nos últimos 7 dias, uma linha por tentativa. Não traz o corpo enviado nem o que o seu servidor respondeu: só o status.

```json
{
  "data": [
    {
      "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
      "eventId": "YOUR_EVENTID",
      "eventType": "YOUR_EVENTTYPE",
      "status": "success",
      "httpStatus": 1,
      "durationMs": 1,
      "attempt": 1,
      "at": "YOUR_AT"
    }
  ],
  "nextCursor": "YOUR_NEXTCURSOR"
}
```

**400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal.

```json
{
  "error": "invalid_request",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Requisição inválida.",
  "campos": [
    {
      "campo": "text.body",
      "motivo": "Não pode ficar vazio."
    }
  ]
}
```

**401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which.

```json
{
  "error": "unauthorized",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Credencial ausente ou inválida."
}
```

**403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed.

```json
{
  "error": "forbidden",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.",
  "requiredScope": "numbers:read"
}
```

**404**: The resource does not exist, or is not yours. The two answers are identical, byte for byte.

```json
{
  "error": "not_found",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Recurso não encontrado."
}
```

**429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key.

```json
{
  "error": "rate_limited",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Requisições demais. Tente novamente em instantes."
}
```

**503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one.

```json
{
  "error": "unavailable",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Não foi possível concluir a operação agora. Tente novamente em instantes."
}
```

### Send a test event

`POST /v1/webhooks/endpoints/{id}/test`

Sends ONE webhook.test event to the endpoint, now, and returns the result in the response itself. The event goes out signed, with the same headers, the same signature and the same destination defenses as a real delivery, so a test that passes proves that the URL and signature verification work. With eventType in the body, the event is an example of that type, with a made-up body and test: true in the envelope.

Authentication: API key. Required scope: `webhooks:write`

Topic guide: https://lunahia.com.br/en/docs/receive-events#rota-post-v1-webhooks-endpoints-id-test

#### Path parameters

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `id` | `string` | yes | O identificador do endpoint, devolvido no cadastro. |

#### Request body

`application/json`

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `eventType` | `string` | no | Um tipo de GET /v1/webhooks/event-types. A Luna entrega ao endpoint um exemplo desse tipo, com corpo de mentira (identificadores que não existem) e test: true no envelope, para você exercitar o seu código sem esperar o evento de verdade. Ausente, o teste é o webhook.test de sempre. O exemplo não passa por nenhum número seu. · Values: message.received, message.status, contact.identity_changed, contact.preferences_changed, backlog.dropped, history_sync.deadline_approaching, message.echo, template.status, number.connected, number.payment_required, number.payment_resolved, account.restricted, account.violation, account.disabled, account.reinstated, account.update, account.limit_changed, number.disconnected, number.quality_changed, number.display_name_reviewed, number.credential_expiring, account.alert, number.action_required, number.action_resolved, onboarding.link.completed, onboarding.link.opened, onboarding.link.failed, onboarding.link.expired, template.category, template.quality |

#### Code examples

```bash
curl -X POST "https://api.lunahia.com.br/v1/webhooks/endpoints/YOUR_ID/test" \
  -H "Authorization: Bearer $LUNA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
  "eventType": "message.received"
}'
```

#### Responses

**200**: O resultado do evento de teste. O corpo que o seu servidor respondeu não volta aqui, de propósito.

```json
{
  "delivered": true,
  "statusCode": 1,
  "durationMs": 1,
  "failure": "timeout"
}
```

**400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal.

```json
{
  "error": "invalid_request",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Requisição inválida.",
  "campos": [
    {
      "campo": "text.body",
      "motivo": "Não pode ficar vazio."
    }
  ]
}
```

**401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which.

```json
{
  "error": "unauthorized",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Credencial ausente ou inválida."
}
```

**403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed.

```json
{
  "error": "forbidden",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.",
  "requiredScope": "numbers:read"
}
```

**404**: The resource does not exist, or is not yours. The two answers are identical, byte for byte.

```json
{
  "error": "not_found",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Recurso não encontrado."
}
```

**415**: The body came with a content-type the route does not read. Send application/json, or multipart/form-data on the file routes.

```json
{
  "error": "unsupported_media_type",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Envie o corpo como application/json."
}
```

**429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key.

```json
{
  "error": "rate_limited",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Requisições demais. Tente novamente em instantes."
}
```

**503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one.

```json
{
  "error": "unavailable",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Não foi possível concluir a operação agora. Tente novamente em instantes."
}
```

### Rotate the signing secret

`POST /v1/webhooks/endpoints/{id}/rotacionar`

Mints a new secret and returns it once. Store it now, as on registration.

Authentication: API key. Required scope: `webhooks:write`

Topic guide: https://lunahia.com.br/en/docs/receive-events#rota-post-v1-webhooks-endpoints-id-rotacionar

#### Path parameters

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `id` | `string` | yes | O identificador do endpoint, devolvido no cadastro. |

#### Request body

`application/json`

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `revokePrevious` | `boolean` | no | Com true, o segredo anterior deixa de valer no mesmo instante, em vez de seguir válido por sete dias. Use quando o segredo anterior vazou. As entregas que já saíram assinadas só com ele falham na verificação do seu lado. |

#### Code examples

```bash
curl -X POST "https://api.lunahia.com.br/v1/webhooks/endpoints/YOUR_ID/rotacionar" \
  -H "Authorization: Bearer $LUNA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
  "revokePrevious": true
}'
```

#### Responses

**200**: O endpoint com o segredo novo. O anterior continua válido até previousSecretExpiresAt, então você pode trocar a configuração do seu lado sem pressa e sem perder entrega.

```json
{
  "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
  "url": "https://exemplo.com.br/arquivo",
  "createdAt": "YOUR_CREATEDAT",
  "updatedAt": "YOUR_UPDATEDAT",
  "previousSecretExpiresAt": "YOUR_PREVIOUSSECRETEXPIRESAT",
  "paused": true,
  "pausedAt": "YOUR_PAUSEDAT",
  "eventTypes": [
    "YOUR_EVENTTYPES"
  ],
  "externalIds": [
    "YOUR_EXTERNALIDS"
  ],
  "phoneNumberIds": [
    "YOUR_PHONENUMBERIDS"
  ],
  "headerNames": [
    "YOUR_HEADERNAMES"
  ],
  "lastDeliveryAt": "YOUR_LASTDELIVERYAT",
  "lastFailureAt": "YOUR_LASTFAILUREAT",
  "lastHttpStatus": 1,
  "deliveryStatus": "ok",
  "secret": "YOUR_SECRET"
}
```

**400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal.

```json
{
  "error": "invalid_request",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Requisição inválida.",
  "campos": [
    {
      "campo": "text.body",
      "motivo": "Não pode ficar vazio."
    }
  ]
}
```

**401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which.

```json
{
  "error": "unauthorized",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Credencial ausente ou inválida."
}
```

**403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed.

```json
{
  "error": "forbidden",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.",
  "requiredScope": "numbers:read"
}
```

**404**: The resource does not exist, or is not yours. The two answers are identical, byte for byte.

```json
{
  "error": "not_found",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Recurso não encontrado."
}
```

**415**: The body came with a content-type the route does not read. Send application/json, or multipart/form-data on the file routes.

```json
{
  "error": "unsupported_media_type",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Envie o corpo como application/json."
}
```

**429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key.

```json
{
  "error": "rate_limited",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Requisições demais. Tente novamente em instantes."
}
```

**503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one.

```json
{
  "error": "unavailable",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Não foi possível concluir a operação agora. Tente novamente em instantes."
}
```

### List deliveries that failed for good

`GET /v1/webhooks/dlq`

The events Luna tried to deliver to your endpoint and gave up on, newest first, each with the number, the customer label, the attempts, the last HTTP status and what can be done with it (allowedActions). Filters: endpointId, externalId and requeued.

Authentication: API key. Required scope: `webhooks:read`

Topic guide: https://lunahia.com.br/en/docs/receive-events#rota-get-v1-webhooks-dlq

#### Query parameters

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `cursor` | `string` | no | O cursor devolvido em nextCursor pela chamada anterior. Omita na primeira página. |
| `limit` | `integer` | no | Quantos itens trazer nesta página. Máximo 100, igual para todos. |
| `endpointId` | `string` | no | Só os itens deste endpoint. |
| `externalId` | `string` | no | Só os itens dos números deste cliente seu (externalId do número). Igualdade exata; um rótulo sem item devolve lista vazia. |
| `requeued` | `string` | no | true: só os já re-enfileirados. false: só os que ainda podem ser (os que têm requeue em allowedActions). |

#### Code examples

```bash
curl -X GET "https://api.lunahia.com.br/v1/webhooks/dlq" \
  -H "Authorization: Bearer $LUNA_API_KEY"
```

#### Responses

**200**: Uma página da fila de rejeitados. Sem total e sem contagem: a Luna não soma entregas, e nenhum número desta resposta alimenta cobrança. attempts e lastHttpStatus descrevem UMA entrega que falhou, e não um agregado.

```json
{
  "items": [
    {
      "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
      "endpointId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
      "eventType": "message.received",
      "wamid": "YOUR_WAMID",
      "rejectedAt": "YOUR_REJECTEDAT",
      "failureReason": "http_4xx",
      "requeuedAt": "YOUR_REQUEUEDAT",
      "numberId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
      "externalId": "YOUR_EXTERNALID",
      "attempts": 1,
      "lastHttpStatus": 1,
      "allowedActions": [
        "requeue"
      ]
    }
  ],
  "nextCursor": "YOUR_NEXTCURSOR"
}
```

**400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal.

```json
{
  "error": "invalid_request",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Requisição inválida.",
  "campos": [
    {
      "campo": "text.body",
      "motivo": "Não pode ficar vazio."
    }
  ]
}
```

**401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which.

```json
{
  "error": "unauthorized",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Credencial ausente ou inválida."
}
```

**403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed.

```json
{
  "error": "forbidden",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.",
  "requiredScope": "numbers:read"
}
```

**429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key.

```json
{
  "error": "rate_limited",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Requisições demais. Tente novamente em instantes."
}
```

**503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one.

```json
{
  "error": "unavailable",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Não foi possível concluir a operação agora. Tente novamente em instantes."
}
```

### Requeue a failed delivery

`POST /v1/webhooks/dlq/{id}/reenfileirar`

Puts the event back on the delivery queue. The response is 202: the request was recorded, and delivery happens asynchronously.

Authentication: API key. Required scope: `webhooks:write`

Topic guide: https://lunahia.com.br/en/docs/receive-events#rota-post-v1-webhooks-dlq-id-reenfileirar

#### Path parameters

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `id` | `string` | yes | O identificador deste item na fila de rejeitados. |

#### Code examples

```bash
curl -X POST "https://api.lunahia.com.br/v1/webhooks/dlq/YOUR_ID/reenfileirar" \
  -H "Authorization: Bearer $LUNA_API_KEY"
```

#### Responses

**202**: O item foi recolocado na fila de entrega. A entrega em si é assíncrona, como qualquer outra: se o seu endpoint ainda estiver fora do ar, ela será adiada e retentada pela mesma política de sempre.

```json
{
  "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
  "requeuedAt": "YOUR_REQUEUEDAT"
}
```

**400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal.

```json
{
  "error": "invalid_request",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Requisição inválida.",
  "campos": [
    {
      "campo": "text.body",
      "motivo": "Não pode ficar vazio."
    }
  ]
}
```

**401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which.

```json
{
  "error": "unauthorized",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Credencial ausente ou inválida."
}
```

**403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed.

```json
{
  "error": "forbidden",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.",
  "requiredScope": "numbers:read"
}
```

**404**: The resource does not exist, or is not yours. The two answers are identical, byte for byte.

```json
{
  "error": "not_found",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Recurso não encontrado."
}
```

**409**: The request is well formed, but the resource state does not allow it. The error field says which case it is.

```json
{
  "error": "already_requeued",
  "docsUrl": "https://lunahia.com.br/docs/receber-eventos",
  "message": "Este item já foi re-enfileirado.",
  "reenfileiradoEm": "2026-10-06T12:00:00.000Z"
}
```

**429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key.

```json
{
  "error": "rate_limited",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Requisições demais. Tente novamente em instantes."
}
```

**503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one.

```json
{
  "error": "unavailable",
  "docsUrl": "https://lunahia.com.br/docs/erros",
  "message": "Não foi possível concluir a operação agora. Tente novamente em instantes."
}
```
