# Consultando um Boleto

## Consultando um Boleto

A consulta de um boleto na API do Pagou permite recuperar detalhes de um boleto existente, como status, valor, código de barras e data de pagamento, usando seu ID único.&#x20;

### Visão Geral Técnica

O endpoint <mark style="color:purple;">`GET`</mark>` ``/v1/charges/{id}` retorna os detalhes completos de um boleto, incluindo informações do pagador, multas, juros, descontos e status. A operação é síncrona e ideal para verificar o estado de um boleto sem depender de webhooks, embora o uso de webhooks (ex.: evento `ChargePaid`) seja recomendado para atualizações automáticas.

<mark style="color:purple;">`GET`</mark> /v1/charges/{id}

### Cabeçalhos

| Cabeçalho      | Valor                    | Descrição                                                    |
| -------------- | ------------------------ | ------------------------------------------------------------ |
| `X-API-KEY`    | `sua_chave_api`          | Chave de autenticação (encontrada em *Configurações > API*). |
| `Content-Type` | `application/json`       | Formato JSON para a requisição.                              |
| `User-Agent`   | `NomeDaSuaAplicacao/1.0` | Identifica sua aplicação (ex.: `MinhaLoja/1.0`).             |

### Parâmetros da URL

| Parâmetro | Tipo   | Obrigatório | Descrição                                                       |
| --------- | ------ | ----------- | --------------------------------------------------------------- |
| `id`      | string | Sim         | ID único do boleto (ex.: 8325a4b3-579c-45df-b475-0ce57df2478d). |

**Validações**:

* `id`: Deve ser um ID válido retornado pelo endpoint de criação (<mark style="color:green;">`POST`</mark>` ``/v1/charges`).

### Resposta

* **Status**: `200 OK`
* **Corpo**: JSON com os detalhes do boleto.

**Exemplo de Resposta**:

```json
{
  "id": "8325a4b3-579c-45df-b475-0ce57df2478d",
  "status": 2,
  "due_date": "2024-12-31",
  "grace_period": 15,
  "amount": 100.50,
  "description": "Payment for services rendered",
  "metadata": [
    {
      "key": "order_id",
      "value": "ORD-2024-001"
    },
    {
      "key": "reference",
      "value": "REF-12345"
    }
  ],
  "payer": {
    "name": "João Silva",
    "document": "12345678901",
    "zip": "01234567",
    "street": "Rua das Flores",
    "city": "São Paulo",
    "state": "SP",
    "number": "123",
    "neighborhood": "Centro"
  },
  "fine": 2.5,
  "interest": 1.0,
  "discount": {
    "type": "fixed",
    "amount": 10.00,
    "limit_date": "2024-12-25"
  },
  "notification_url": "https://your-webhook.com/notifications",
  "customer_code": "CUST-001",
  "created_at": "2025-07-23T09:30:00-03:00",
  "paid_at": null
}
```

**Campos da Resposta**:

| Campo                 | Tipo   | Descrição                                                                   |
| --------------------- | ------ | --------------------------------------------------------------------------- |
| `id`                  | string | ID único do boleto (ex.: 8325a4b3-579c-45df-b475-0ce57df2478d).             |
| `status`              | number | Status do boleto (`1, 2, 3, 4, 5`).                                         |
| `due_date`            | string | Data de vencimento (formato `YYYY-MM-DD`).                                  |
| `grace_period`        | number | Dias de tolerância após o vencimento (ex.: 15).                             |
| `amount`              | number | Valor do boleto em reais (ex.: 100.50 para R$ 100,50).                      |
| `description`         | string | Descrição do boleto (máx. 255 caracteres).                                  |
| `metadata`            | array  | Pares chave-valor para dados adicionais (ex.: ID do pedido).                |
| `metadata[].key`      | string | Chave do metadado (ex.: `order_id`).                                        |
| `metadata[].value`    | string | Valor do metadado (ex.: `ORD-2024-001`).                                    |
| `payer`               | object | Dados do pagador.                                                           |
| `payer.name`          | string | Nome completo do pagador (máx. 100 caracteres).                             |
| `payer.document`      | string | CPF (11 dígitos) ou CNPJ (14 dígitos).                                      |
| `payer.zip`           | string | CEP (8 dígitos, sem hífen).                                                 |
| `payer.street`        | string | Rua ou avenida (máx. 200 caracteres).                                       |
| `payer.city`          | string | Cidade (máx. 100 caracteres).                                               |
| `payer.state`         | string | UF (2 letras, ex.: `SP`).                                                   |
| `payer.number`        | string | Número do endereço (máx. 20 caracteres).                                    |
| `payer.neighborhood`  | string | Bairro (máx. 100 caracteres).                                               |
| `fine`                | number | Multa por atraso em percentual (ex.: 2.5 para 2,5%).                        |
| `interest`            | number | Juros por dia de atraso em percentual (ex.: 1.0 para 1%).                   |
| `discount`            | object | Desconto para pagamento antecipado.                                         |
| `discount.type`       | string | Tipo de desconto (`fixed` ou `percentage`).                                 |
| `discount.amount`     | number | Valor do desconto (em reais para `fixed`, ou percentual para `percentage`). |
| `discount.limit_date` | string | Data limite para o desconto (formato `YYYY-MM-DD`).                         |
| `notification_url`    | string | URL HTTPS para webhooks (ex.: `https://your-webhook.com/notifications`).    |
| `customer_code`       | string | Código interno do cliente (máx. 50 caracteres).                             |
| `created_at`          | string | Data de criação do boleto (ISO 8601).                                       |
| `paid_at`             | string | Data de pagamento do boleto (ISO 8601, ou `null` se não pago).              |

### Exemplos de Código

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X GET https://sandbox.api.pagou.com.br/v1/charges/8325a4b3-579c-45df-b475-0ce57df2478d \
  -H "X-API-KEY: sua_chave_api" \
  -H "Content-Type: application/json" \
  -H "User-Agent: MinhaLoja/1.0"
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
const fetch = require('node-fetch');
const { validate } = require('jsonschema');

// Esquema de validação da resposta
const schema = {
    type: 'object',
    required: ['id', 'status', 'due_date', 'amount', 'description', 'payer'],
    properties: {
        id: { type: 'string' },
        status: { type: 'number', enum: [1, 2, 3, 4, 5] },
        due_date: { type: 'string', pattern: '^\\d{4}-\\d{2}-\\d{2}$' },
        grace_period: { type: 'integer', minimum: 0 },
        amount: { type: 'number', minimum: 1.00 },
        description: { type: 'string', maxLength: 255 },
        metadata: {
            type: 'array',
            items: {
                type: 'object',
                required: ['key', 'value'],
                properties: {
                    key: { type: 'string' },
                    value: { type: 'string' }
                }
            }
        },
        payer: {
            type: 'object',
            required: ['name', 'document', 'zip', 'street', 'city', 'state', 'number', 'neighborhood'],
            properties: {
                name: { type: 'string', maxLength: 100 },
                document: { type: 'string', pattern: '^\\d{11}|\\d{14}$' },
                zip: { type: 'string', pattern: '^\\d{8}$' },
                street: { type: 'string', maxLength: 200 },
                city: { type: 'string', maxLength: 100 },
                state: { type: 'string', pattern: '^[A-Z]{2}$' },
                number: { type: 'string', maxLength: 20 },
                neighborhood: { type: 'string', maxLength: 100 }
            }
        },
        fine: { type: 'number', minimum: 0, maximum: 100 },
        interest: { type: 'number', minimum: 0, maximum: 100 },
        discount: {
            type: 'object',
            required: ['type', 'amount', 'limit_date'],
            properties: {
                type: { type: 'string', enum: ['fixed', 'percentage'] },
                amount: { type: 'number', minimum: 0 },
                limit_date: { type: 'string', pattern: '^\\d{4}-\\d{2}-\\d{2}$' }
            }
        },
        notification_url: { type: 'string', format: 'uri' },
        customer_code: { type: 'string', maxLength: 50 },
        barcode: { type: 'string' },
        pdf_url: { type: 'string', format: 'uri' },
        created_at: { type: 'string', format: 'date-time' },
        paid_at: { type: ['string', 'null'], format: 'date-time' }
    }
};

// Consultar boleto
const boletoId = '8325a4b3-579c-45df-b475-0ce57df2478d';
fetch(`https://sandbox.api.pagou.com.br/v1/charges/${boletoId}`, {
    method: 'GET',
    headers: {
        'X-API-KEY': 'sua_chave_api',
        'Content-Type': 'application/json',
        'User-Agent': 'MinhaLoja/1.0'
    }
})
    .then(response => {
        if (!response.ok) {
            throw new Error(`Erro ${response.status}: ${response.statusText}`);
        }
        return response.json();
    })
    .then(data => {
        // Validar resposta
        const validation = validate(data, schema);
        if (!validation.valid) {
            throw new Error(`Erro de validação: ${validation.errors}`);
        }
        
        console.log(`Boleto ID: ${data.id}`);
        console.log(`Status: ${data.status}`);
    })
    .catch(error => console.error('Erro na requisição:', error));
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
from jsonschema import validate, ValidationError

# Esquema de validação da resposta
schema = {
    "type": "object",
    "required": ["id", "status", "due_date", "amount", "description", "payer"],
    "properties": {
        "id": {"type": "string"},
        "status": {"type": "number", "enum": [1, 2, 3, 4, 5]},
        "due_date": {"type": "string", "pattern": "^\\d{4}-\\d{2}-\\d{2}$"},
        "grace_period": {"type": "integer", "minimum": 1},
        "amount": {"type": "number", "minimum": 1.00},
        "description": {"type": "string", "maxLength": 255},
        "metadata": {
            "type": "array",
            "items": {
                "type": "object",
                "required": ["key", "value"],
                "properties": {
                    "key": {"type": "string"},
                    "value": {"type": "string"}
                }
            }
        },
        "payer": {
            "type": "object",
            "required": ["name", "document", "zip", "street", "city", "state", "number", "neighborhood"],
            "properties": {
                "name": {"type": "string", "maxLength": 100},
                "document": {"type": "string", "pattern": "^\\d{11}|\\d{14}$"},
                "zip": {"type": "string", "pattern": "^\\d{8}$"},
                "street": {"type": "string", "maxLength": 200},
                "city": {"type": "string", "maxLength": 100},
                "state": {"type": "string", "pattern": "^[A-Z]{2}$"},
                "number": {"type": "string", "maxLength": 20},
                "neighborhood": {"type": "string", "maxLength": 100}
            }
        },
        "fine": {"type": "number", "minimum": 0, "maximum": 100},
        "interest": {"type": "number", "minimum": 0, "maximum": 100},
        "discount": {
            "type": "object",
            "required": ["type", "amount", "limit_date"],
            "properties": {
                "type": {"type": "string", "enum": ["fixed", "percentage"]},
                "amount": {"type": "number", "minimum": 0},
                "limit_date": {"type": "string", "pattern": "^\\d{4}-\\d{2}-\\d{2}$"}
            }
        },
        "notification_url": {"type": "string", "format": "uri"},
        "customer_code": {"type": "string", "maxLength": 50},
        "barcode": {"type": "string"},
        "pdf_url": {"type": "string", "format": "uri"},
        "created_at": {"type": "string", "format": "date-time"},
        "paid_at": {"type": ["string", "null"], "format": "date-time"}
    }
}

# Consultar boleto
boleto_id = "8325a4b3-579c-45df-b475-0ce57df2478d"
url = f"https://sandbox.api.pagou.com.br/v1/charges/{boleto_id}"
headers = {
    "X-API-KEY": "sua_chave_api",
    "Content-Type": "application/json",
    "User-Agent": "MinhaLoja/1.0"
}

try:
    response = requests.get(url, headers=headers)
    response.raise_for_status()
    data = response.json()
    
    # Validar resposta
    try:
        validate(instance=data, schema=schema)
    except ValidationError as e:
        print(f"Erro de validação na resposta: {e}")
        exit(1)
    
    print(f"Boleto ID: {data['id']}")
    print(f"Status: {data['status']}")
except requests.RequestException as e:
    print(f"Erro na requisição: {e}")
```

{% endtab %}
{% endtabs %}

### Tratamento de Erros

| Código HTTP | Descrição             | Possível Causa                   | Solução                                   |
| ----------- | --------------------- | -------------------------------- | ----------------------------------------- |
| `400`       | Bad Request           | ID do boleto malformado.         | Verificar formato do `id`.                |
| `401`       | Unauthorized          | `X-API-KEY` inválido ou ausente. | Verificar chave..                         |
| `404`       | Not Found             | Boleto não existe.               | Confirmar ID do boleto.                   |
| `429`       | Too Many Requests     | Limite de requisições excedido.  | Implementar rate limiting e retentativas. |
| `500`       | Internal Server Error | Erro interno da API.             | Tentar novamente e contatar suporte.      |

**Exemplo de Resposta de Erro**:

```json
{
  "error": "Boleto not found"
}
```

### Boas Práticas Técnicas

* **Segurança**: Armazene `X-API-KEY` em variáveis de ambiente e use HTTPS para todas as requisições.
* **Webhooks como Alternativa**: Para atualizações em tempo real, configure o evento `ChargePaid` em vez de consultas frequentes. Veja Webhooks para Interações com Boleto.
* **Testes no Sandbox**: Use `https://sandbox.api.pagou.com.br/v1/charges/{id}` para simular consultas sem custos reais.
* **Monitoramento**: Registre todas as requisições e respostas em logs, incluindo `id`, `status` e `paid_at`, para auditoria e depuração.
* **Cache**: Considere armazenar respostas em cache (ex.: Redis, com TTL de 5 minutos) para reduzir chamadas à API em sistemas de alto tráfego.

## Get a Charge

> This endpoint return a charge.

```json
{"openapi":"3.1.1","info":{"title":"Pagou API","version":"0.0.1"},"servers":[{"url":"https://sandbox-api.pagou.com.br"}],"security":[{"XApiKeyAuth":[]}],"components":{"securitySchemes":{"XApiKeyAuth":{"type":"apiKey","name":"X-API-KEY","in":"header"}},"schemas":{"models.ErrorResponse":{"type":"object","properties":{"error":{"type":"string"},"errors":{"type":"array","items":{"type":"string"}}}}}},"paths":{"/v1/charges/{chargeID}":{"get":{"description":"This endpoint return a charge.","tags":["charges"],"summary":"Get a Charge","parameters":[{"type":"string","description":"Client Identifier","name":"User-Agent","in":"header"},{"type":"string","description":"Charge ID","name":"chargeID","in":"path","required":true}],"responses":{"200":{"description":"OK","content":{"application/json":{"schema":{"type":"string"}}}},"400":{"description":"Bad Request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/models.ErrorResponse"}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/models.ErrorResponse"}}}},"404":{"description":"Not Found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/models.ErrorResponse"}}}},"500":{"description":"Internal Server Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/models.ErrorResponse"}}}}}}}}}
```


---

# 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.pagou.com.br/integracao-com-a-api/meio-de-pagamento-boleto/consultando-um-boleto.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.
