> For the complete documentation index, see [llms.txt](https://docs.leadlinks.app/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.leadlinks.app/api-desenvolvedores/webhooks.md).

# Webhooks

O Lead Links pode **enviar eventos** (HTTP `POST`) para uma URL sua sempre que algo acontece — uma negociação criada, um estágio alterado, um contato atualizado, etc.

## Configuração

No painel, em **Configurações → Webhooks**, cadastre:

* **URL de destino** — o endpoint que receberá os `POST`.
* **Eventos** — quais eventos disparam a entrega.
* **Secret** *(opcional, recomendado)* — usado para **assinar** cada entrega (HMAC). Veja [Verificação de assinatura](#verificacao-de-assinatura).

## Formato do payload

Cada entrega é um `POST` com `Content-Type: application/json`:

```json
{
  "event": {
    "type": "deal.stage_changed",
    "timestamp": "2024-06-15T13:45:00Z",
    "description": "Etapa alterada para \"Proposta\""
  },
  "account_id": "880e8400-e29b-41d4-a716-446655440003",
  "entity_id": "aa0e8400-e29b-41d4-a716-446655440010",
  "metadata": { "old_stage_id": "...", "new_stage_id": "..." },
  "deal": { /* dados atuais da entidade */ }
}
```

* `event.type` — o evento (veja a lista abaixo).
* `entity_id` — o ID da entidade afetada (presente inclusive em `*.deleted`).
* `metadata` — contexto do evento (ex.: estágio antigo/novo).
* Os **dados da entidade** (avaliados) são incluídos no payload.

## Eventos disponíveis

| Evento                  | Quando dispara                                                       |
| ----------------------- | -------------------------------------------------------------------- |
| `contact.created`       | Contato criado.                                                      |
| `contact.updated`       | Contato atualizado.                                                  |
| `company.created`       | Empresa criada.                                                      |
| `company.updated`       | Empresa atualizada.                                                  |
| `company.deleted`       | Empresa excluída.                                                    |
| `deal.created`          | Negociação criada.                                                   |
| `deal.updated`          | Negociação atualizada (genérico).                                    |
| `deal.stage_changed`    | Mudou de **etapa** (metadata: `old_stage_id`, `new_stage_id`).       |
| `deal.pipeline_changed` | Mudou de **funil** (metadata: `old_pipeline_id`, `new_pipeline_id`). |
| `deal.status_changed`   | Mudou de **status** (`open`/`won`/`lost`).                           |
| `deal.value_changed`    | Mudou o **valor**.                                                   |
| `deal.assignee_changed` | Mudou o **responsável**.                                             |

{% hint style="info" %}
Numa única atualização de negociação, vários eventos podem ser emitidos (ex.: `deal.updated` + `deal.stage_changed`). Trate cada entrega de forma idempotente.
{% endhint %}

## Verificação de assinatura

Se você definir um **secret**, cada entrega traz o header:

```
X-Webhook-Signature: <hex>
```

Esse valor é o **HMAC-SHA256 do corpo bruto** da requisição, usando o seu secret. Verifique no seu servidor para garantir que a chamada veio do Lead Links:

```javascript
import { createHmac, timingSafeEqual } from "node:crypto";

function verify(rawBody, signatureHeader, secret) {
  const expected = createHmac("sha256", secret).update(rawBody, "utf8").digest("hex");
  const a = Buffer.from(expected), b = Buffer.from(signatureHeader || "");
  return a.length === b.length && timingSafeEqual(a, b);
}
```

{% hint style="warning" %}
Calcule o HMAC sobre o **corpo exatamente como recebido** (raw), antes de qualquer parse de JSON.
{% endhint %}

## Entrega e retentativas

* Timeout de **10 segundos** por entrega.
* Responda **`2xx`** rapidamente para confirmar o recebimento; processe de forma assíncrona se precisar.
* As entregas (e falhas) ficam registradas no painel, em **Webhooks → Entregas**.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.leadlinks.app/api-desenvolvedores/webhooks.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
