# Webhooks

A Barte envia notificações via webhook quando há mudanças no status das contas e atualizações sobre pagamentos, saques e depósitos.

## Configuração

A URL de callback é configurada durante o onboarding ou via API (veja [Gerenciamento de Webhooks](#gerenciamento-de-webhooks)). Requisitos:

* HTTPS obrigatório
* Responder com status `2xx` em até 30 segundos
* Suportar retentativas (até 5 tentativas com backoff exponencial)

### Headers

| Header         | Descrição          |
| -------------- | ------------------ |
| `Content-Type` | `application/json` |

## Gerenciamento de Webhooks

### Ciclo de Vida

#### Fluxo de Cadastro

```mermaid
sequenceDiagram
    participant P as Parceiro
    participant B as Banking API

    P->>B: POST /v1/webhooks
    B-->>P: 201 Created (webhook cadastrado)
    P->>B: GET /v1/webhooks
    B-->>P: 200 OK (lista de webhooks)
    P->>B: PUT /v1/webhooks/{id}
    B-->>P: 202 Accepted (webhook atualizado)
```

#### Fluxo de Ativação e Inativação

```mermaid
sequenceDiagram
    participant P as Parceiro
    participant B as Banking API

    P->>B: PATCH /v1/webhooks/{id}/active (isActive: false)
    B-->>P: 200 OK (webhook inativado)
    P->>B: PATCH /v1/webhooks/{id}/active (isActive: true)
    B-->>P: 200 OK (webhook reativado)
    Note over B: Somente webhooks ativos recebem notificações
```

#### Fluxo de Notificação

```mermaid
sequenceDiagram
    participant P as Parceiro
    participant B as Banking API

    P->>B: POST /v1/webhooks (eventType: cash_in.update)
    B-->>P: 201 Created
    Note over B: PIX recebido na conta
    B-->>P: Notificação cash_in.update (SUCCESS)
```

### POST /v1/webhooks

Cadastra um ou mais webhooks para receber notificações de eventos da instituição financeira autenticada.

**Request:**

```bash
curl --request POST \
  --url 'https://api-banking.barte.com/v1/webhooks' \
  --cert client.pem \
  --key client-key.pem \
  --header 'Authorization: Bearer {token}' \
  --header 'Content-Type: application/json' \
  --data '[
    {
      "url": "https://meu-sistema.com.br/webhooks/pix",
      "eventType": "cash_in.update",
      "description": "Notificações de PIX recebido"
    },
    {
      "url": "https://meu-sistema.com.br/webhooks/kyc",
      "eventType": "account_status.update",
      "description": "Notificações de status de conta"
    }
  ]'
```

#### Campos — Request

| Campo         | Tipo   | Obrigatório | Validação                                                                             |
| ------------- | ------ | ----------- | ------------------------------------------------------------------------------------- |
| `url`         | String | Sim         | Deve usar HTTPS. Ex: `https://meu-sistema.com.br/webhook`                             |
| `eventType`   | String | Sim         | Enum: `cash_in.update`, `cash_out.update`, `cash_out.refund`, `account_status.update` |
| `description` | String | Não         | Descrição do webhook                                                                  |

> O corpo da requisição é uma **lista** de webhooks. É possível cadastrar múltiplos webhooks em uma única chamada.

**Response — 201 Created:**

```json
[
  {
    "id": 1,
    "url": "https://meu-sistema.com.br/webhooks/pix",
    "eventType": "cash_in.update",
    "description": "Notificações de PIX recebido",
    "isActive": true
  },
  {
    "id": 2,
    "url": "https://meu-sistema.com.br/webhooks/kyc",
    "eventType": "account_status.update",
    "description": "Notificações de status de conta",
    "isActive": true
  }
]
```

#### Campos — Response

| Campo         | Tipo    | Descrição                                                                                       |
| ------------- | ------- | ----------------------------------------------------------------------------------------------- |
| `id`          | Int     | Identificador único do webhook                                                                  |
| `url`         | String  | URL de destino das notificações                                                                 |
| `eventType`   | String  | Tipo de evento: `cash_in.update`, `cash_out.update`, `cash_out.refund`, `account_status.update` |
| `description` | String  | Descrição do webhook (pode ser `null`)                                                          |
| `isActive`    | Boolean | Indica se o webhook está ativo                                                                  |

**Response — 400 Bad Request (URL sem HTTPS):**

```json
{
  "errors": [
    {
      "code": "BNK-0501",
      "title": "Invalid request params",
      "description": "Error in request url - Webhook URL must use HTTPS"
    }
  ],
  "metadata": {
    "totalRecords": 1,
    "totalPages": 1,
    "requestDatetime": "2026-01-30T15:30:00Z"
  }
}
```

**Response — 404 Not Found (instituição financeira não encontrada):**

```json
{
  "errors": [
    {
      "code": "BNK-0402",
      "title": "Webhook flow error",
      "description": "Financial institution for webhook not found"
    }
  ],
  "metadata": {
    "totalRecords": 1,
    "totalPages": 1,
    "requestDatetime": "2026-01-30T15:30:00Z"
  }
}
```

**Status Codes:**

| Status             | Descrição                             |
| ------------------ | ------------------------------------- |
| `201 Created`      | Webhook(s) cadastrado(s) com sucesso  |
| `400 Bad Request`  | Dados inválidos ou URL sem HTTPS      |
| `401 Unauthorized` | Token inválido ou expirado            |
| `403 Forbidden`    | Autoridade `PAYFAC` necessária        |
| `404 Not Found`    | Instituição financeira não encontrada |

***

### GET /v1/webhooks

Lista todos os webhooks cadastrados para a instituição financeira autenticada.

**Request:**

```bash
curl --request GET \
  --url 'https://api-banking.barte.com/v1/webhooks' \
  --cert client.pem \
  --key client-key.pem \
  --header 'Authorization: Bearer {token}'
```

**Response — 200 OK:**

```json
[
  {
    "id": 1,
    "url": "https://meu-sistema.com.br/webhooks/pix",
    "eventType": "cash_in.update",
    "description": "Notificações de PIX recebido",
    "isActive": true
  },
  {
    "id": 2,
    "url": "https://meu-sistema.com.br/webhooks/kyc",
    "eventType": "account_status.update",
    "description": "Notificações de status de conta",
    "isActive": false
  }
]
```

**Response — 404 Not Found (instituição financeira não encontrada):**

```json
{
  "errors": [
    {
      "code": "BNK-0050",
      "title": "Banking flow error",
      "description": "Financial institution not found"
    }
  ],
  "metadata": {
    "totalRecords": 1,
    "totalPages": 1,
    "requestDatetime": "2026-01-30T15:30:00Z"
  }
}
```

**Status Codes:**

| Status             | Descrição                             |
| ------------------ | ------------------------------------- |
| `200 OK`           | Lista de webhooks retornada           |
| `401 Unauthorized` | Token inválido ou expirado            |
| `403 Forbidden`    | Autoridade `PAYFAC` necessária        |
| `404 Not Found`    | Instituição financeira não encontrada |

***

### PUT /v1/webhooks/{idWebhook}

Atualiza a URL, o tipo de evento e a descrição de um webhook existente.

**Path Parameters:**

| Parâmetro   | Tipo | Descrição                |
| ----------- | ---- | ------------------------ |
| `idWebhook` | Int  | Identificador do webhook |

**Request:**

```bash
curl --request PUT \
  --url 'https://api-banking.barte.com/v1/webhooks/1' \
  --cert client.pem \
  --key client-key.pem \
  --header 'Authorization: Bearer {token}' \
  --header 'Content-Type: application/json' \
  --data '{
    "url": "https://meu-sistema.com.br/webhooks/pix-v2",
    "eventType": "CASH_IN",
    "description": "Notificações de PIX recebido - v2"
  }'
```

#### Campos — Request

| Campo         | Tipo   | Obrigatório | Validação                                                        |
| ------------- | ------ | ----------- | ---------------------------------------------------------------- |
| `url`         | String | Sim         | URL de destino. Ex: `https://meu-sistema.com.br/webhook`         |
| `eventType`   | String | Sim         | Enum: `CASH_IN`, `CASH_OUT`, `CASH_OUT_REFUND`, `ACCOUNT_STATUS` |
| `description` | String | Não         | Nova descrição do webhook                                        |

**Response — 202 Accepted:**

```json
{
  "id": 1,
  "url": "https://meu-sistema.com.br/webhooks/pix-v2",
  "eventType": "cash_in.update",
  "description": "Notificações de PIX recebido - v2",
  "isActive": true
}
```

**Response — 404 Not Found (webhook não encontrado):**

```json
{
  "errors": [
    {
      "code": "BNK-0401",
      "title": "Webhook flow error",
      "description": "Account webhook not found for id: 1"
    }
  ],
  "metadata": {
    "totalRecords": 1,
    "totalPages": 1,
    "requestDatetime": "2026-01-30T15:30:00Z"
  }
}
```

**Status Codes:**

| Status             | Descrição                      |
| ------------------ | ------------------------------ |
| `202 Accepted`     | Webhook atualizado com sucesso |
| `400 Bad Request`  | Dados inválidos                |
| `401 Unauthorized` | Token inválido ou expirado     |
| `403 Forbidden`    | Autoridade `PAYFAC` necessária |
| `404 Not Found`    | Webhook não encontrado         |

***

### PATCH /v1/webhooks/{idWebhook}/active

Ativa ou inativa um webhook. Somente webhooks ativos recebem notificações.

**Path Parameters:**

| Parâmetro   | Tipo | Descrição                |
| ----------- | ---- | ------------------------ |
| `idWebhook` | Int  | Identificador do webhook |

**Headers adicionais:**

| Header     | Obrigatório | Descrição                                 |
| ---------- | ----------- | ----------------------------------------- |
| `isActive` | Sim         | `true` para ativar, `false` para inativar |

**Request:**

```bash
curl --request PATCH \
  --url 'https://api-banking.barte.com/v1/webhooks/1/active' \
  --cert client.pem \
  --key client-key.pem \
  --header 'Authorization: Bearer {token}' \
  --header 'isActive: false'
```

**Response — 200 OK:**

Sem corpo de resposta.

**Response — 404 Not Found (webhook não encontrado):**

```json
{
  "errors": [
    {
      "code": "BNK-0401",
      "title": "Webhook flow error",
      "description": "Account webhook not found for id: 1"
    }
  ],
  "metadata": {
    "totalRecords": 1,
    "totalPages": 1,
    "requestDatetime": "2026-01-30T15:30:00Z"
  }
}
```

**Status Codes:**

| Status             | Descrição                                |
| ------------------ | ---------------------------------------- |
| `200 OK`           | Status do webhook atualizado com sucesso |
| `401 Unauthorized` | Token inválido ou expirado               |
| `403 Forbidden`    | Autoridade `PAYFAC` necessária           |
| `404 Not Found`    | Webhook não encontrado                   |

## Tipos de Evento

| Evento                  | Quando                              | Descrição                                               |
| ----------------------- | ----------------------------------- | ------------------------------------------------------- |
| `account_status.update` | Qualquer mudança de status da conta | Notifica mudança de status da conta                     |
| `cash_in.update`        | Depósito na conta                   | Notifica qualquer depósito feito para a conta           |
| `cash_out.update`       | Saque ou pagamento                  | Notifica qualquer saque ou pagamento feito pela a conta |
| `cash_out.refund`       | Estorno na conta                    | Notifica qualquer estorno que houver na conta           |

## Status da Conta (KYC)

| Status         | Descrição            | Ação recomendada         |
| -------------- | -------------------- | ------------------------ |
| `PENDING`      | KYC em processamento | Aguardar                 |
| `KYC_APPROVED` | KYC aprovado         | Chamar `POST /activate`  |
| `KYC_REPROVED` | KYC rejeitado        | Corrigir dados via `PUT` |

## Status de Pagamento

| Status     | Descrição                  | Ação recomendada                                       |
| ---------- | -------------------------- | ------------------------------------------------------ |
| `SUCCESS`  | Pagamento em processamento | Aguardar a conclusão do processamento.                 |
| `FAILED`   | Pagamento falhou           | Verificar o motivo da falha e tomar a ação apropriada. |
| `REFUNDED` | Pagamento Estornado        | Verificar o estorno e tomar a ação apropriada          |

## Exemplos de Payload

### Status da Conta (KYC)

#### KYC Aprovado

```json
{
  "event": "account_status.update",
  "processedAt": "2026-01-30T16:00:00Z",
  "data": {
    "accountId": "f47ac10b-58cc-4372-a567-0e02b2c3d479",
    "accountType": "business",
    "status": "KYC_APPROVED",
    "reasons": []
  }
}
```

### KYC Rejeitado

```json
{
  "event": "account_status.update",
  "timestamp": "2026-01-30T16:00:00Z",
  "data": {
    "accountId": "f47ac10b-58cc-4372-a567-0e02b2c3d479",
    "accountType": "business",
    "status": "KYC_REPROVED",
    "reasons": ["name_mismatch, partners_are_missing"]
  }
}
```

### KYC Pendente

```json
{
  "event": "account_status.update",
  "timestamp": "2026-01-30T16:00:00Z",
  "data": {
    "accountId": "f47ac10b-58cc-4372-a567-0e02b2c3d479",
    "accountType": "business",
    "status": "PENDING",
    "reasons": []
  }
}
```

### Eventos de cash-in | cash-out

#### Pagamento efetuado ou Saque

```json
{
  "id": "488cfff1-7b81-47cc-a68f-fcf6d0246a3e",
  "eventType": "cash_out.update",
  "amount": 0.01,
  "initiationType": "static_qrcode",
  "endToEndId": "E3168015120251236210953SF2OT9BB8",
  "status": "SUCCESS",
  "operationDate": "2025-08-27T00:00:00",
  "description": "",
  "errorReason": null,
  "creditParty": {
    "pixKey": "33439146812",
    "name": "Empresa Recebedora LTDA",
    "document": "12345678000199",
    "accountNumber": "987654",
    "accountType": "CACC",
    "branch": "0001"
  },
  "debitParty": {
    "accountNumber": "123456",
    "accountType": "CACC",
    "bankIspb": "87654321",
    "branch": "0001",
    "document": "98765432100",
    "name": "Cliente Pagador"
  }
}
```

#### Depósito

```json
{
  "id": "8b8baece-7da7-4441-8826-fb507a481106",
  "eventType": "cash_in.update",
  "amount": 1000000,
  "initiationType": "static_qrcode",
  "endToEndId": "E3168015120251236210953SF2OT9BB8",
  "status": "SUCCESS",
  "operationDate": "2026-02-20T00:00:00",
  "description": "Payment simulation",
  "errorReason": null,
  "creditParty": {
    "pixKey": "d46fe074-c77c-4ef5-8831-7a6833cd2781",
    "name": "Cliente Recebedor",
    "document": "36186677000103",
    "accountNumber": "118802",
    "accountType": "TRAN",
    "branch": "1"
  },
  "debitParty": {
    "accountNumber": "4370771",
    "accountType": "CACC",
    "bankIspb": "30306294",
    "branch": "30",
    "document": "31680151000161",
    "name": "Cliente Pagador"
  }
}
```

#### Estorno

```json
{
  "id": "804",
  "eventType": "cash_out.refund",
  "amount": 0.01,
  "initiationType": "static_qrcode",
  "endToEndId": "E3168015120251236210953SF2OT9BB8",
  "status": "REFUNDED",
  "operationDate": "2025-12-05T11:50:47",
  "description": null,
  "errorReason": "devolução solicitada pelo destinatário final",
  "creditParty": {
    "pixKey": "33541533854",
    "name": "Cliente Pagador",
    "document": "98765432100",
    "accountNumber": "123456",
    "accountType": "CACC",
    "branch": "0001"
  },
  "debitParty": {
    "accountNumber": "987654",
    "accountType": "CACC",
    "bankIspb": "12345678",
    "branch": "0001",
    "document": "12345678000199",
    "name": "Empresa Recebedora LTDA"
  }
}
```


---

# Agent Instructions: 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:

```
GET https://docs.barte.com/banking/api/webhooks.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
