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

# Gerenciar Webhooks

> Cadastrar, listar, atualizar e deletar webhooks

## Visão Geral

Endpoints para gerenciar as configurações de webhooks dos estabelecimentos.

## POST /webhooks - Cadastrar Webhook

Cadastra uma nova URL de webhook para receber notificações.

### Request

```bash cURL theme={null}
curl --request POST \
  --url https://api.econpay.com.br/webhooks \
  --header 'Authorization: Bearer SEU_TOKEN_JWT' \
  --header 'Content-Type: application/json' \
  --data '{
    "url": "https://seusite.com.br/webhooks/econpay",
    "company_id": 1,
    "events": ["payment.approved", "payment.failed", "payment.refunded"]
  }'
```

### Response

```json theme={null}
{
  "id": 1,
  "url": "https://seusite.com.br/webhooks/econpay",
  "company_id": 1,
  "active": true,
  "created_at": "2024-01-22T10:00:00Z"
}
```

## GET /webhooks - Listar Webhooks

Lista todos os webhooks cadastrados.

### Request

```bash cURL theme={null}
curl --request GET \
  --url https://api.econpay.com.br/webhooks \
  --header 'Authorization: Bearer SEU_TOKEN_JWT'
```

### Response

```json theme={null}
{
  "data": [
    {
      "id": 1,
      "url": "https://seusite.com.br/webhooks/econpay",
      "company_id": 1,
      "active": true,
      "created_at": "2024-01-22T10:00:00Z"
    }
  ]
}
```

## GET /webhooks/:id - Buscar Webhook

Busca um webhook específico por ID.

### Request

```bash cURL theme={null}
curl --request GET \
  --url https://api.econpay.com.br/webhooks/1 \
  --header 'Authorization: Bearer SEU_TOKEN_JWT'
```

### Response

```json theme={null}
{
  "id": 1,
  "url": "https://seusite.com.br/webhooks/econpay",
  "company_id": 1,
  "active": true,
  "events": ["payment.approved", "payment.failed"],
  "created_at": "2024-01-22T10:00:00Z"
}
```

## PATCH /webhooks/:id - Atualizar Webhook

Atualiza a configuração de um webhook.

### Request

```bash cURL theme={null}
curl --request PATCH \
  --url https://api.econpay.com.br/webhooks/1 \
  --header 'Authorization: Bearer SEU_TOKEN_JWT' \
  --header 'Content-Type: application/json' \
  --data '{
    "url": "https://novaurl.com.br/webhooks",
    "active": true
  }'
```

### Response

```json theme={null}
{
  "id": 1,
  "url": "https://novaurl.com.br/webhooks",
  "company_id": 1,
  "active": true,
  "updated_at": "2024-01-22T11:00:00Z"
}
```

## DELETE /webhooks/:id - Deletar Webhook

Remove um webhook cadastrado.

### Request

```bash cURL theme={null}
curl --request DELETE \
  --url https://api.econpay.com.br/webhooks/1 \
  --header 'Authorization: Bearer SEU_TOKEN_JWT'
```

### Response

```json theme={null}
{
  "message": "Webhook deletado com sucesso"
}
```

## POST /webhooks/:paymentId/retry - Reenviar Webhook

Reenvia o webhook de uma transação específica.

### Request

```bash cURL theme={null}
curl --request POST \
  --url https://api.econpay.com.br/webhooks/123/retry \
  --header 'Authorization: Bearer SEU_TOKEN_JWT'
```

### Response

```json theme={null}
{
  "message": "Webhook sent"
}
```

## Exemplos em JavaScript

### Cadastrar Webhook

```javascript theme={null}
async function createWebhook(url, companyId) {
  const response = await fetch('https://api.econpay.com.br/webhooks', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      url,
      company_id: companyId,
      events: ['payment.approved', 'payment.failed', 'payment.refunded']
    })
  });
  
  return await response.json();
}

const webhook = await createWebhook('https://seusite.com.br/webhooks', 1);
console.log('Webhook cadastrado:', webhook.id);
```

### Listar Webhooks

```javascript theme={null}
async function listWebhooks() {
  const response = await fetch('https://api.econpay.com.br/webhooks', {
    headers: { 'Authorization': `Bearer ${token}` }
  });
  
  const { data } = await response.json();
  return data;
}

const webhooks = await listWebhooks();
webhooks.forEach(wh => {
  console.log(`${wh.id}: ${wh.url} - ${wh.active ? 'Ativo' : 'Inativo'}`);
});
```

### Atualizar Webhook

```javascript theme={null}
async function updateWebhook(id, updates) {
  const response = await fetch(`https://api.econpay.com.br/webhooks/${id}`, {
    method: 'PATCH',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(updates)
  });
  
  return await response.json();
}

await updateWebhook(1, { 
  url: 'https://novaurl.com.br/webhooks',
  active: true 
});
```

### Deletar Webhook

```javascript theme={null}
async function deleteWebhook(id) {
  const response = await fetch(`https://api.econpay.com.br/webhooks/${id}`, {
    method: 'DELETE',
    headers: { 'Authorization': `Bearer ${token}` }
  });
  
  return await response.json();
}

await deleteWebhook(1);
console.log('Webhook deletado');
```

### Reenviar Webhook

```javascript theme={null}
async function retryWebhook(paymentId) {
  const response = await fetch(
    `https://api.econpay.com.br/webhooks/${paymentId}/retry`,
    {
      method: 'POST',
      headers: { 'Authorization': `Bearer ${token}` }
    }
  );
  
  return await response.json();
}

await retryWebhook(123);
console.log('Webhook reenviado');
```

## Boas Práticas

<AccordionGroup>
  <Accordion title="Use HTTPS">
    Sempre use URLs HTTPS para receber webhooks. URLs HTTP não são seguras e podem ser rejeitadas.
  </Accordion>

  <Accordion title="Valide os Webhooks">
    Sempre valide que o webhook veio realmente da EconPay consultando a API.
  </Accordion>

  <Accordion title="Responda Rapidamente">
    Retorne status 200 em menos de 5 segundos. Processe tarefas pesadas de forma assíncrona.
  </Accordion>

  <Accordion title="Implemente Idempotência">
    Webhooks podem ser enviados mais de uma vez. Implemente lógica para evitar processamento duplicado.
  </Accordion>
</AccordionGroup>

## Próximos Passos

<CardGroup cols={2}>
  <Card title="Guia de Webhooks" icon="book" href="/guides/webhooks">
    Implementação completa de webhooks
  </Card>

  <Card title="Criar Pagamento" icon="credit-card" href="/api-reference/payments/create-payment">
    Processar pagamentos
  </Card>
</CardGroup>
