> ## Documentation Index
> Fetch the complete documentation index at: https://scaleup-c34c4386.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# API Reference

> Referência completa da API REST da Chargefy

A API da Chargefy permite que você integre pagamentos, assinaturas, checkout e gestão de clientes diretamente na sua aplicação.

## URLs Base

| Ambiente | URL |
| - | - |
| **Produção** | `https://api.chargefy.io` |
| **Sandbox** | `https://sandbox-api.chargefy.io` |

Todas as requisições devem usar HTTPS. Requisições HTTP serão rejeitadas.

## Autenticação

A API suporta dois métodos de autenticação:

| Método | Prefixo | Caso de Uso |
| - | - | - |
| **Supabase JWT** | `eyJhbGciOiJIUzI1NiIs...` | Integrações server-side, automações, backend |
| **Customer Session Token (CST)** | `chargefy_cst_` | Portal do cliente, operações self-service |

Inclua o token no header `Authorization`:

```bash cURL theme={null}
curl -X GET https://api.chargefy.io/api/v1/products/ \
  -H "Authorization: Bearer <supabase_jwt>"
```

```typescript SDK theme={null}
import { Chargefy } from '@chargefy/sdk';

const chargefy = new Chargefy({
  accessToken: process.env.CHARGEFY_ACCESS_TOKEN, // <supabase_jwt>...
});

const products = await chargefy.products.list();
```

> [!NOTE]
>
> Obtenha o JWT via `supabase.auth.getSession()`. Consulte o guia de [Autenticação](https://scaleup-c34c4386.mintlify.site/integrate/authentication.md) para detalhes.
> Consulte o guia de [Autenticação](https://scaleup-c34c4386.mintlify.site/integrate/authentication.md) para detalhes sobre todos os métodos.

## Core API vs Customer Portal API

A API da Chargefy é dividida em duas camadas:

| API | Base Path | Autenticação | Descrição |
| - | - | - | - |
| **Core API** | `/api/v1/` | JWT | API principal para gerenciar recursos da organização |
| **Customer Portal API** | `/api/v1/customer-portal/` | CST | API self-service para operações do cliente |

### Core API — Endpoints Principais

| Recurso | Endpoints | Descrição |
| - | - | - |
| [Checkouts](https://scaleup-c34c4386.mintlify.site/api-reference/checkouts/list.md) | `GET/POST/PATCH /checkouts/` | Criar e gerenciar sessões de checkout |
| [Checkout Links](https://scaleup-c34c4386.mintlify.site/api-reference/checkout-links/list.md) | `GET/POST/PATCH/DELETE /checkout-links/` | Links de checkout compartilháveis |
| [Products](https://scaleup-c34c4386.mintlify.site/api-reference/products/list.md) | `GET/POST/PATCH/DELETE /products/` | Produtos e preços |
| [Customers](https://scaleup-c34c4386.mintlify.site/api-reference/customers/list.md) | `GET/POST/PATCH/DELETE /customers/` | Gestão de clientes |
| [Subscriptions](https://scaleup-c34c4386.mintlify.site/api-reference/subscriptions/list.md) | `GET/PATCH /subscriptions/` | Assinaturas e recorrência |
| [Sales](https://scaleup-c34c4386.mintlify.site/api-reference/sales/list.md) | `GET /sales/` | Vendas e transações Zoop |
| [Discounts](https://scaleup-c34c4386.mintlify.site/api-reference/discounts/list.md) | `GET/POST/PATCH/DELETE /discounts/` | Cupons e descontos |
| [Files](https://scaleup-c34c4386.mintlify.site/api-reference/files/list.md) | `GET/POST/DELETE /files/` | Upload e gestão de arquivos |
| [Webhooks](https://scaleup-c34c4386.mintlify.site/api-reference/webhooks/list) | `GET/POST/PATCH/DELETE /webhooks/` | Configuração de webhooks |
| [Metrics](https://scaleup-c34c4386.mintlify.site/api-reference/metrics/get.md) | `GET /metrics/` | Métricas e analytics |
| [Events](https://scaleup-c34c4386.mintlify.site/api-reference/events/list) | `GET /events/` | Log de eventos |
| [Organizations](https://scaleup-c34c4386.mintlify.site/api-reference/organizations/get.md) | `GET/PATCH /organizations/` | Configuração da organização |

### Customer Portal API

| Recurso | Endpoints | Descrição |
| - | - | - |
| Customer Session | `POST /customer-portal/sessions/` | Criar sessão do cliente |
| Subscriptions | `GET/PATCH /customer-portal/subscriptions/` | Gerenciar assinaturas |

## Paginação

Endpoints de listagem retornam resultados paginados. Use os parâmetros `page` e `limit` para navegar:

```bash theme={null}
GET /api/v1/products/?page=1&limit=20
```

### Resposta Paginada

```json theme={null}
{
  "items": [
    { "id": "prod_123", "name": "Plano Pro", "..." : "..." }
  ],
  "pagination": {
    "total_count": 45,
    "max_page": 3
  }
}
```

| Parâmetro | Tipo | Default | Descrição |
| - | - | - | - |
| `page` | `integer` | `1` | Número da página |
| `limit` | `integer` | `10` | Itens por página (máx: 100) |

## Ordenação e Filtros

A maioria dos endpoints de listagem suporta ordenação e filtros:

```bash theme={null}
# Ordenar por data de criação (mais recente primeiro)
GET /api/v1/products/?sorting=-created_at

# Filtrar por tipo
GET /api/v1/products/?type=recurring

# Combinar filtros e ordenação
GET /api/v1/subscriptions/?product_id=prod_123&sorting=-created_at&limit=50
```

## Rate Limits

Para garantir estabilidade, a API aplica limites de taxa de requisição:

| Plano | Limite | Período |
| - | - | - |
| **Sandbox** | 100 req | por minuto |
| **Produção** | 1.000 req | por minuto |

Quando o limite é atingido, a API retorna `429 Too Many Requests` com o header `Retry-After`.

## Formato de Erros

Erros seguem um formato consistente:

```json theme={null}
{
  "error": "Descrição do erro",
  "detail": "Informações adicionais quando disponíveis"
}
```

### Códigos de Status

| Código | Descrição |
| - | - |
| `200` | Sucesso |
| `201` | Recurso criado |
| `204` | Sucesso sem conteúdo (ex: DELETE) |
| `400` | Requisição inválida (parâmetros faltando ou incorretos) |
| `401` | Não autenticado (token ausente ou inválido) |
| `403` | Sem permissão (escopo insuficiente) |
| `404` | Recurso não encontrado |
| `422` | Erro de validação |
| `429` | Rate limit excedido |
| `500` | Erro interno do servidor |

## Idempotência

Para operações `POST`, você pode incluir o header `Idempotency-Key` para garantir que a operação seja executada apenas uma vez:

```bash theme={null}
curl -X POST https://api.chargefy.io/api/v1/checkouts/ \
  -H "Authorization: Bearer <supabase_jwt>..." \
  -H "Idempotency-Key: unique-request-id-123" \
  -H "Content-Type: application/json" \
  -d '{"product_id": "prod_123"}'
```

## Próximos Passos

> [card] [Autenticação](https://scaleup-c34c4386.mintlify.site/integrate/authentication.md)
>
> Configurar tokens de acesso

> [card] [Sandbox](https://scaleup-c34c4386.mintlify.site/integrate/sandbox.md)
>
> Testar no ambiente de desenvolvimento

> [card] [SDK TypeScript](https://scaleup-c34c4386.mintlify.site/integrate/sdk/typescript.md)
>
> Instalar o SDK oficial

> [card] [Webhooks](https://scaleup-c34c4386.mintlify.site/integrate/webhooks/endpoints.md)
>
> Configurar notificações em tempo real


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.