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

# Webhooks de Saída

> Notifique sistemas externos sobre eventos

## Visão Geral

Webhooks de saída enviam dados para sistemas externos quando eventos específicos ocorrem no Leavo.

## Criar Webhook de Saída

<Card>
  <strong>POST</strong> `/backend/webhooks`
</Card>

### Request Body

<ParamField body="name" type="string" required>
  Nome do webhook
</ParamField>

<ParamField body="description" type="string">
  Descrição do webhook
</ParamField>

<ParamField body="type" type="string" required>
  Deve ser `"outbound"`
</ParamField>

<ParamField body="is_active" type="boolean" default="true">
  Se o webhook está ativo
</ParamField>

<ParamField body="target_url" type="string" required>
  URL de destino para enviar os dados
</ParamField>

<ParamField body="trigger_events" type="array" required>
  Eventos que disparam o webhook: `lead_created`, `lead_updated`, `status_changed`
</ParamField>

<ParamField body="trigger_status_ids" type="array">
  Para `status_changed`: filtrar por status específicos
</ParamField>

<ParamField body="output_field_mapping" type="object">
  Mapeamento de campos do lead para o payload de saída
</ParamField>

<ParamField body="output_custom_field_mapping" type="object">
  Mapeamento de campos personalizados
</ParamField>

### Exemplo

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST "https://api.leavo.ai/backend/webhooks" \
    -H "Authorization: Bearer sua_chave_aqui" \
    -H "Content-Type: application/json" \
    -d '{
      "name": "Notificar CRM",
      "description": "Envia leads qualificados para o CRM",
      "type": "outbound",
      "is_active": true,
      "target_url": "https://seu-crm.com/api/leads",
      "trigger_events": ["lead_created", "status_changed"],
      "trigger_status_ids": ["uuid-status-qualificado"],
      "output_field_mapping": {
        "customer_name": "name",
        "customer_email": "email",
        "customer_phone": "phone"
      },
      "output_custom_field_mapping": {
        "external_field": "custom_field_key"
      }
    }'
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch('https://api.leavo.ai/backend/webhooks', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer sua_chave_aqui',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      name: 'Notificar CRM',
      description: 'Envia leads qualificados para o CRM',
      type: 'outbound',
      is_active: true,
      target_url: 'https://seu-crm.com/api/leads',
      trigger_events: ['lead_created', 'status_changed'],
      trigger_status_ids: ['uuid-status-qualificado'],
      output_field_mapping: {
        customer_name: 'name',
        customer_email: 'email',
        customer_phone: 'phone'
      }
    })
  });
  ```
</CodeGroup>

***

## Eventos de Disparo

<AccordionGroup>
  <Accordion title="lead_created" icon="user-plus">
    Dispara quando um novo lead é criado no sistema.

    Útil para sincronizar leads com CRM ou ferramentas de marketing.
  </Accordion>

  <Accordion title="lead_updated" icon="user-pen">
    Dispara quando os dados de um lead são atualizados.

    Inclui mudanças em nome, email, telefone, empresa, etc.
  </Accordion>

  <Accordion title="status_changed" icon="flag">
    Dispara quando o status de um lead muda.

    Pode ser filtrado por status específicos usando `trigger_status_ids`.
  </Accordion>
</AccordionGroup>

***

## Payload Enviado

Quando um evento é disparado, o seguinte payload é enviado para a URL de destino:

```json theme={null}
{
  "event": "lead_created",
  "timestamp": "2024-01-15T10:30:00Z",
  "lead_id": "uuid",
  "customer_name": "João Silva",
  "customer_email": "joao@exemplo.com",
  "customer_phone": "+5511999999999"
}
```

### Headers Enviados

```http theme={null}
Content-Type: application/json
User-Agent: Leavo-Webhook/1.0
X-Webhook-Event: lead_created
X-Webhook-ID: uuid-do-webhook
```

***

## Tratamento no Servidor de Destino

<Info>
  Seu servidor deve responder com status 2xx dentro de 30 segundos, caso contrário a requisição será considerada falha.
</Info>

### Exemplo de Servidor (Node.js)

```javascript theme={null}
app.post('/api/webhook', (req, res) => {
  const { event, lead_id, customer_name } = req.body;

  // Processe o evento de forma assíncrona
  processWebhook(req.body).catch(console.error);

  // Responda rapidamente
  res.status(200).json({ received: true });
});

async function processWebhook(data) {
  switch (data.event) {
    case 'lead_created':
      await syncWithCRM(data);
      break;
    case 'status_changed':
      await notifyTeam(data);
      break;
  }
}
```

***

## Retry Policy

Se o webhook falhar, o sistema tentará novamente:

* **3 tentativas** com backoff exponencial
* Intervalos: 1 min, 5 min, 30 min
* Após 3 falhas, o webhook é marcado como erro

<Warning>
  Monitore as falhas de webhook no dashboard. Muitas falhas podem indicar problemas com o servidor de destino.
</Warning>
