# Confirmar Sessão de Checkout
Source: https://docs.upag.io/pages/checkout-sessions/confirm
POST /api/v1/checkout-sessions/{checkoutSessionId}/confirm
Confirma e processa o pagamento de uma sessão de checkout
Confirma a sessão e processa o pagamento com o cliente e método de pagamento informados. O ID da sessão vai na URL (`checkoutSessionId`); o `accountId` é resolvido pelo servidor a partir da autenticação.
## Endpoint
```bash cURL theme={null}
curl -X POST https://api.upag.io/v1/checkout-sessions/cs_abc123xyz/confirm \
-H "Authorization: Bearer {token}" \
-H "Content-Type: application/json" \
-d '{
"customer": "cus_ahwDXrgYvur89iPs",
"paymentMethod": "pm_abc123xyz",
"installments": 1,
"bumps": []
}'
```
## Parâmetros
ID da sessão (`cs_...`), mesmo valor usado na URL do checkout.
ID do cliente (`cus_...`) que está concluindo o pagamento.
ID do método de pagamento (`pm_...`) utilizado na cobrança.
Número de parcelas (mínimo `1`).
Opcional. Lista de IDs de bumps/order bumps aceitos pelo fluxo. Padrão: `[]`.
## Resposta
`200 OK` com JSON que inclui todos os campos da sessão de checkout (como em [Buscar sessão](./get)) no nível raiz, mais as chaves `invoice`, `customer` e `paymentMethod` com os objetos completos retornados pela API após a confirmação. Consulte as páginas de referência de [Faturas](../invoices/reference), [Clientes](../customers/reference) e [Métodos de pagamento](../payment-methods/reference) para o formato desses objetos.
# Criar uma Sessão de Checkout
Source: https://docs.upag.io/pages/checkout-sessions/create
POST /api/v1/checkout-sessions
Crie uma nova sessão de checkout para um cliente
Cria uma nova sessão de checkout com pelo menos um item (preço + quantidade). Retorna a URL da página de pagamento para redirecionar o cliente.
## Endpoint
```bash cURL theme={null}
curl -X POST https://api.upag.io/v1/checkout-sessions \
-H "Authorization: Bearer {token}" \
-H "Content-Type: application/json" \
-d '{
"customerId": "cus_ahwDXrgYvur89iPs",
"items": [
{
"priceId": "price_def456ghi",
"quantity": 1
}
],
"paymentMethods": ["credit_card", "pix"],
"billingAddressCollection": "auto",
"successUrl": "https://seusite.com/sucesso",
"cancelUrl": "https://seusite.com/cancelado"
}'
```
## Parâmetros
Lista de linhas do checkout. Cada item precisa de `priceId` (string) e `quantity` (número, mínimo `1`). É obrigatório pelo menos um item.
Opcional. ID do cliente (`cus_...`) para associar à sessão.
Opcional. Métodos aceitos na sessão. Valores do enum da API: `credit_card`, `pix`.
Opcional. Um de: `auto`, `required`, `none`.
Opcional. URL válida para redirecionar após pagamento bem-sucedido.
Opcional. URL válida se o cliente cancelar o fluxo.
## Resposta
```json Response theme={null}
{
"id": "cs_abc123xyz",
"status": "open",
"customerId": "cus_ahwDXrgYvur89iPs",
"url": "https://checkout.upag.io/cs_abc123xyz",
"billingAddressCollection": false,
"successUrl": "https://example.com/success",
"cancelUrl": "https://example.com/cancel",
"latitude": null,
"longitude": null,
"country": null,
"region": null,
"city": null,
"expiresAt": "2024-11-16T10:00:00.000Z",
"createdAt": "2024-11-15T10:00:00.000Z",
"updatedAt": "2024-11-15T10:00:00.000Z",
"items": []
}
```
# Excluir Sessão de Checkout
Source: https://docs.upag.io/pages/checkout-sessions/delete
DELETE /api/v1/checkout-sessions/{id}
Exclui uma sessão de checkout
Exclui uma sessão de checkout. Somente sessões com status `open` podem ser excluídas.
## Endpoint
```bash cURL theme={null}
curl -X DELETE https://api.upag.io/v1/checkout-sessions/cs_abc123xyz \
-H "Authorization: Bearer {token}"
```
## Parâmetros
ID único da sessão de checkout, começando com `cs_`.
## Resposta
Sem corpo. HTTP `204 No Content` em caso de sucesso.
# Buscar Sessão de Checkout por ID
Source: https://docs.upag.io/pages/checkout-sessions/get
GET /api/v1/checkout-sessions/{id}
Retorna os detalhes de uma sessão de checkout específica
Retorna as informações completas de uma sessão de checkout específica pelo seu ID.
## Endpoint
```bash cURL theme={null}
curl https://api.upag.io/v1/checkout-sessions/cs_abc123xyz \
-H "Authorization: Bearer {token}"
```
## Parâmetros
ID único da sessão de checkout, começando com `cs_`.
## Resposta
```json Response theme={null}
{
"id": "cs_abc123xyz",
"status": "open",
"customerId": "cus_ahwDXrgYvur89iPs",
"url": "https://checkout.upag.io/cs_abc123xyz",
"billingAddressCollection": false,
"successUrl": "https://example.com/success",
"cancelUrl": "https://example.com/cancel",
"latitude": null,
"longitude": null,
"country": null,
"region": null,
"city": null,
"expiresAt": "2024-11-16T10:00:00.000Z",
"createdAt": "2024-11-15T10:00:00.000Z",
"updatedAt": "2024-11-15T10:00:00.000Z",
"items": [
{
"id": "csi_abc123xyz",
"priceId": "price_def456ghi",
"quantity": 1,
"price": {
"id": "price_def456ghi",
"name": "Plano Pro Mensal",
"billingType": "recurring",
"interval": "month",
"intervalCount": 1,
"currency": "BRL",
"amount": 9900,
"product": {
"id": "prod_xyz789abc",
"name": "Plano Pro",
"description": null,
"image": null
}
}
}
]
}
```
# Listar Sessões de Checkout
Source: https://docs.upag.io/pages/checkout-sessions/list
GET /api/v1/checkout-sessions
Retorna uma lista de todas as sessões de checkout
Retorna uma lista paginada de todas as sessões de checkout.
## Endpoint
```bash cURL theme={null}
curl -G https://api.upag.io/v1/checkout-sessions \
-H "Authorization: Bearer {token}" \
-d page=1 \
-d limit=10
```
## Parâmetros
Limita o número de sessões retornadas. Padrão: `10`, máximo: `100`.
Número da página a ser retornada. Padrão: `1`.
## Resposta
```json Response theme={null}
{
"data": [
{
"id": "cs_abc123xyz",
"status": "open",
"customerId": "cus_ahwDXrgYvur89iPs",
"url": "https://checkout.upag.io/cs_abc123xyz",
"billingAddressCollection": false,
"successUrl": "https://example.com/success",
"cancelUrl": "https://example.com/cancel",
"latitude": null,
"longitude": null,
"country": null,
"region": null,
"city": null,
"expiresAt": "2024-11-16T10:00:00.000Z",
"createdAt": "2024-11-15T10:00:00.000Z",
"updatedAt": "2024-11-15T10:00:00.000Z",
"items": []
}
],
"total": 1
}
```
# Referência
Source: https://docs.upag.io/pages/checkout-sessions/reference
Crie e gerencie sessões de checkout para seus clientes
Uma sessão de checkout representa uma instância de uma página de pagamento criada para um cliente. Ela contém todas as informações necessárias para concluir uma compra.
## Estrutura
Uma sessão de checkout é representada em nossa API pela seguinte estrutura:
```json theme={null}
{
"id": "cs_abc123xyz",
"status": "open",
"customerId": "cus_ahwDXrgYvur89iPs",
"url": "https://checkout.upag.io/cs_abc123xyz",
"billingAddressCollection": false,
"successUrl": "https://example.com/success",
"cancelUrl": "https://example.com/cancel",
"latitude": null,
"longitude": null,
"country": null,
"region": null,
"city": null,
"expiresAt": "2024-11-16T10:00:00.000Z",
"createdAt": "2024-11-15T10:00:00.000Z",
"updatedAt": "2024-11-15T10:00:00.000Z",
"items": [
{
"id": "csi_abc123xyz",
"priceId": "price_def456ghi",
"quantity": 1,
"price": {
"id": "price_def456ghi",
"name": "Plano Pro Mensal",
"billingType": "recurring",
"interval": "month",
"intervalCount": 1,
"currency": "BRL",
"amount": 9900,
"product": {
"id": "prod_xyz789abc",
"name": "Plano Pro",
"description": null,
"image": null
}
}
}
]
}
```
## Atributos:
```json {2} theme={null}
{
"id": "cs_abc123xyz",
}
```
`id` : string.
Identificador único da sessão de checkout, começando com `cs_`
```json {2} theme={null}
{
"status": "open",
}
```
`status` : string.
Status atual da sessão de checkout
| Status | Descrição |
| ---------- | ----------------------------------------------- |
| `open` | **A sessão está aberta e aguardando pagamento** |
| `complete` | **A sessão foi concluída com sucesso** |
| `expired` | **A sessão expirou sem pagamento** |
```json {2} theme={null}
{
"customerId": "cus_ahwDXrgYvur89iPs",
}
```
`customerId` : string | null.
ID do cliente associado à sessão. Veja a referência completa aqui
```json {2} theme={null}
{
"url": "https://checkout.upag.io/cs_abc123xyz",
}
```
`url` : string.
URL da página de checkout para redirecionar o cliente
```json {2} theme={null}
{
"billingAddressCollection": false,
}
```
`billingAddressCollection` : boolean.
Indica se o endereço de cobrança deve ser coletado durante o checkout
```json {2} theme={null}
{
"successUrl": "https://example.com/success",
}
```
`successUrl` : string | null.
URL para redirecionar o cliente após a conclusão bem-sucedida do pagamento
```json {2} theme={null}
{
"cancelUrl": "https://example.com/cancel",
}
```
`cancelUrl` : string | null.
URL para redirecionar o cliente ao cancelar ou abandonar o checkout
```json {2-3} theme={null}
{
"latitude": null,
"longitude": null,
}
```
`latitude` / `longitude` : string | null.
Coordenadas geográficas detectadas do cliente durante o checkout
```json {2-4} theme={null}
{
"country": null,
"region": null,
"city": null,
}
```
`country` / `region` / `city` : string | null.
Localização geográfica detectada do cliente durante o checkout
```json {2} theme={null}
{
"expiresAt": "2024-11-16T10:00:00.000Z",
}
```
`expiresAt` : string | null.
Data de expiração da sessão em formato ISO 8601
```json {2-14} theme={null}
{
"items": [
{
"id": "csi_abc123xyz",
"priceId": "price_def456ghi",
"quantity": 1,
"price": {
"id": "price_def456ghi",
"name": "Plano Pro Mensal",
"billingType": "recurring",
"interval": "month",
"intervalCount": 1,
"currency": "BRL",
"amount": 9900
}
}
]
}
```
`items` : array.
Lista de itens da sessão de checkout. Cada item contém `id`, `priceId`, `quantity` e o objeto `price` expandido com detalhes do preço e produto
```json {2} theme={null}
{
"createdAt": "2024-11-15T10:00:00.000Z",
}
```
`createdAt` : string.
Data de criação da sessão em formato ISO 8601
```json {2} theme={null}
{
"updatedAt": "2024-11-15T10:00:00.000Z",
}
```
`updatedAt` : string.
Data da última atualização da sessão em formato ISO 8601
# Atualizar Sessão de Checkout
Source: https://docs.upag.io/pages/checkout-sessions/update
PUT /api/v1/checkout-sessions/{id}
Atualiza os dados de uma sessão de checkout existente
Atualiza uma sessão de checkout aberta. Todos os campos do body são opcionais no schema; envie apenas o que deseja alterar.
## Endpoint
```bash cURL theme={null}
curl -X PUT https://api.upag.io/v1/checkout-sessions/cs_abc123xyz \
-H "Authorization: Bearer {token}" \
-H "Content-Type: application/json" \
-d '{
"customerId": "cus_ahwDXrgYvur89iPs",
"items": [
{
"priceId": "price_def456ghi",
"quantity": 2
}
],
"paymentMethods": ["credit_card", "pix"],
"successUrl": "https://seusite.com/sucesso",
"cancelUrl": "https://seusite.com/cancelado"
}'
```
## Parâmetros
ID único da sessão de checkout, começando com `cs_`.
Opcional. ID do cliente (`cus_...`).
Opcional. Se enviado, deve ter pelo menos um item com `priceId` e `quantity` (mínimo `1`).
Opcional. `credit_card`, `pix`.
Opcional. URL válida de sucesso.
Opcional. URL válida de cancelamento.
## Resposta
```json Response theme={null}
{
"id": "cs_abc123xyz",
"status": "open",
"customerId": "cus_ahwDXrgYvur89iPs",
"url": "https://checkout.upag.io/cs_abc123xyz",
"billingAddressCollection": false,
"successUrl": "https://example.com/success",
"cancelUrl": "https://example.com/cancel",
"latitude": null,
"longitude": null,
"country": null,
"region": null,
"city": null,
"expiresAt": "2024-11-16T10:00:00.000Z",
"createdAt": "2024-11-15T10:00:00.000Z",
"updatedAt": "2024-11-15T11:00:00.000Z",
"items": []
}
```
# Criar um novo Cliente
Source: https://docs.upag.io/pages/customers/create
POST /api/v1/customers
Crie um cliente para poder cobrar e gerenciar seus pagamentos
Cria um novo cliente na sua conta.
## Endpoint
```bash cURL theme={null}
curl -X POST https://api.upag.io/v1/customers \
-H "Authorization: Bearer {token}" \
-H "Content-Type: application/json" \
-d '{
"name": "John Doe",
"email": "john.doe@example.com",
"phone": "+5511999999999",
"taxId": "12345678900",
"line1": "Rua Example, 123",
"line2": "Apto 45",
"city": "São Paulo",
"state": "SP",
"country": "BR",
"zipCode": "01234567"
}'
```
```javascript SDK theme={null}
import { Upag } from 'upag';
const upag = new Upag('sk_test_your_api_key');
const customer = await upag.customers.create({
name: 'John Doe',
email: 'john.doe@example.com',
phone: '+5511999999999',
taxId: '12345678900',
line1: 'Rua Example, 123',
line2: 'Apto 45',
city: 'São Paulo',
state: 'SP',
country: 'BR',
zipCode: '01234567'
});
```
## Parâmetros
Nome completo do cliente.
E-mail válido do cliente.
Telefone do cliente.
CPF/CNPJ do cliente.
Primeira linha do endereço.
Segunda linha do endereço (complemento).
Cidade do endereço.
Estado do endereço.
País do endereço.
CEP do endereço.
## Resposta
```json Response theme={null}
{
"id": "cus_ahwDXrgYvur89iPs",
"livemode": false,
"name": "John Doe",
"email": "john.doe@example.com",
"phone": "+5511999999999",
"taxId": "12345678900",
"line1": "Rua Example, 123",
"line2": "Apto 45",
"city": "São Paulo",
"state": "SP",
"country": "BR",
"zipCode": "01234567",
"createdAt": 1731622178441,
"updatedAt": 1731622178441
}
```
# Buscar Cliente por ID
Source: https://docs.upag.io/pages/customers/get
GET /api/v1/customers/{id}
Retorna os detalhes de um cliente específico
Retorna as informações completas de um cliente específico pelo seu ID.
## Endpoint
```bash cURL theme={null}
curl https://api.upag.io/v1/customers/cus_ahwDXrgYvur89iPs \
-H "Authorization: Bearer {token}"
```
```javascript SDK theme={null}
import { Upag } from 'upag';
const upag = new Upag('sk_test_your_api_key');
const customer = await upag.customers.retrieve('cus_ahwDXrgYvur89iPs');
```
## Parâmetros
ID único do cliente, começando com `cus_`.
## Resposta
```json Response theme={null}
{
"id": "cus_ahwDXrgYvur89iPs",
"livemode": false,
"name": "John Doe",
"email": "john.doe@example.com",
"phone": "+5511999999999",
"taxId": "12345678900",
"line1": "Rua Example, 123",
"line2": "Apto 45",
"city": "São Paulo",
"state": "SP",
"country": "BR",
"zipCode": "01234567",
"createdAt": 1731622178441,
"updatedAt": 1731622178441
}
```
# Listar Clientes
Source: https://docs.upag.io/pages/customers/list
GET /api/v1/customers
Retorna uma lista de todos os clientes cadastrados
Retorna uma lista paginada de todos os clientes cadastrados na sua conta.
## Endpoint
```bash cURL theme={null}
curl -G https://api.upag.io/v1/customers \
-H "Authorization: Bearer {token}" \
-d page=1 \
-d limit=10
```
```javascript SDK theme={null}
import { Upag } from 'upag';
const upag = new Upag('sk_test_your_api_key');
const customers = await upag.customers.list({
limit: 10,
offset: 0
});
```
## Parâmetros
Limita o número de clientes retornados. Padrão: `10`, máximo: `100`.
Número da página a ser retornada. Padrão: `1`.
## Resposta
```json Response theme={null}
{
"data": [
{
"id": "cus_ahwDXrgYvur89iPs",
"livemode": false,
"name": "John Doe",
"email": "john.doe@example.com",
"phone": "+5511999999999",
"taxId": "12345678900",
"line1": "Rua Example, 123",
"line2": "Apto 45",
"city": "São Paulo",
"state": "SP",
"country": "BR",
"zipCode": "01234567",
"createdAt": 1731622178441,
"updatedAt": 1731622178441
}
],
"total": 1
}
```
# Referência
Source: https://docs.upag.io/pages/customers/reference
Gerencie seus clientes, aqueles que pagam você.
Um cliente é seu usuário final, aquele que você vai cobrar e pagar o seu produto.
## Estrutura
Um cliente é representado em nossa API pela seguinte estrutura:
```json theme={null}
{
"id": "cus_ahwDXrgYvur89iPs",
"livemode": false,
"name": "John Doe",
"email": "john.doe@example.com",
"phone": "+5511999999999",
"taxId": "12345678900",
"line1": "Rua Example, 123",
"line2": "Apto 45",
"city": "São Paulo",
"state": "SP",
"country": "BR",
"zipCode": "01234567",
"createdAt": 1731622178441,
"updatedAt": 1731622178441
}
```
## Atributos
```json {2} theme={null}
{
"id": "cus_ahwDXrgYvur89iPs",
}
```
`id` : string.
Identificador único do cliente, começando com `cus_`
```json {2} theme={null}
{
"livemode": false,
}
```
`livemode` : boolean.
Indica se o cliente está em modo de produção (`true`) ou teste (`false`)
```json {2} theme={null}
{
"name": "John Doe",
}
```
`name` : string.
Nome completo do cliente (obrigatório)
```json {2} theme={null}
{
"email": "john.doe@example.com",
}
```
`email` : string.
E-mail válido do cliente (obrigatório)
```json {2} theme={null}
{
"phone": "+5511999999999",
}
```
`phone` : string | null.
Telefone do cliente (opcional)
```json {2} theme={null}
{
"taxId": "12345678900",
}
```
`taxId` : string | null.
CPF/CNPJ do cliente (opcional)
```json {2} theme={null}
{
"line1": "Rua Example, 123",
}
```
`line1` : string | null.
Primeira linha do endereço (opcional)
```json {2} theme={null}
{
"line2": "Apto 45",
}
```
`line2` : string | null.
Segunda linha do endereço/complemento (opcional)
```json {2} theme={null}
{
"city": "São Paulo",
}
```
`city` : string | null.
Cidade do endereço (opcional)
```json {2} theme={null}
{
"state": "SP",
}
```
`state` : string | null.
Estado do endereço (opcional)
```json {2} theme={null}
{
"country": "BR",
}
```
`country` : string | null.
País do endereço (opcional)
```json {2} theme={null}
{
"zipCode": "01234567",
}
```
`zipCode` : string | null.
CEP do endereço (opcional)
```json {2} theme={null}
{
"createdAt": 1731622178441,
}
```
`createdAt` : number.
Timestamp Unix indicando quando o cliente foi criado
```json {2} theme={null}
{
"updatedAt": 1731622178441,
}
```
`updatedAt` : number.
Timestamp Unix indicando quando o cliente foi atualizado pela última vez
# Atualizar Cliente
Source: https://docs.upag.io/pages/customers/update
PUT /api/v1/customers/{id}
Atualiza os dados de um cliente existente
Atualiza as informações de um cliente existente. Apenas os campos enviados serão atualizados.
## Endpoint
```bash cURL theme={null}
curl -X PUT https://api.upag.io/v1/customers/cus_ahwDXrgYvur89iPs \
-H "Authorization: Bearer {token}" \
-H "Content-Type: application/json" \
-d '{
"name": "Jane Doe",
"email": "jane.doe@example.com",
"phone": "+5511888888888"
}'
```
```javascript SDK theme={null}
import { Upag } from 'upag';
const upag = new Upag('sk_test_your_api_key');
const customer = await upag.customers.update('cus_ahwDXrgYvur89iPs', {
name: 'Jane Doe',
email: 'jane.doe@example.com',
phone: '+5511888888888'
});
```
## Parâmetros
ID único do cliente a ser atualizado.
Nome completo do cliente.
E-mail válido do cliente.
Telefone do cliente.
CPF/CNPJ do cliente.
Primeira linha do endereço.
Segunda linha do endereço (complemento).
Cidade do endereço.
Estado do endereço.
País do endereço.
CEP do endereço.
## Resposta
```json Response theme={null}
{
"id": "cus_ahwDXrgYvur89iPs",
"livemode": false,
"name": "Jane Doe",
"email": "jane.doe@example.com",
"phone": "+5511888888888",
"taxId": "12345678900",
"line1": "Rua Example, 123",
"line2": "Apto 45",
"city": "São Paulo",
"state": "SP",
"country": "BR",
"zipCode": "01234567",
"createdAt": 1731622178441,
"updatedAt": 1731622179870
}
```
# Criar uma Fatura
Source: https://docs.upag.io/pages/invoices/create
POST /api/v1/invoices
Crie uma nova fatura para um cliente
Cria uma nova fatura para um cliente. A fatura é criada com status `draft` e pode ser editada antes de ser emitida. A moeda da fatura é definida automaticamente a partir dos preços dos itens (todos os itens devem usar a mesma moeda).
## Endpoint
```bash cURL theme={null}
curl -X POST https://api.upag.io/v1/invoices \
-H "Authorization: Bearer {token}" \
-H "Content-Type: application/json" \
-d '{
"customerId": "cus_ahwDXrgYvur89iPs",
"paymentMethodId": "pm_abc123xyz",
"items": [
{
"priceId": "price_def456ghi",
"quantity": 1
}
]
}'
```
## Parâmetros
ID do cliente para quem a fatura será emitida.
ID do método de pagamento associado ao cliente.
Lista de itens. Cada item deve conter `priceId` e `quantity` (mínimo 1). É obrigatório pelo menos um item.
## Resposta
```json Response theme={null}
{
"id": "inv_abc123xyz",
"customerId": "cus_ahwDXrgYvur89iPs",
"paymentMethodId": "pm_abc123xyz",
"currency": "BRL",
"status": "draft",
"livemode": false,
"number": null,
"description": null,
"dueDate": null,
"paidAt": null,
"amountDue": 9900,
"amountPaid": 0,
"attemptCount": 0,
"subscriptionId": null,
"items": [
{
"id": "ii_abc123xyz",
"priceId": "price_def456ghi",
"quantity": 1,
"amount": 9900
}
],
"payments": [],
"createdAt": "2024-11-15T10:00:00.000Z",
"updatedAt": "2024-11-15T10:00:00.000Z"
}
```
# Buscar Fatura por ID
Source: https://docs.upag.io/pages/invoices/get
GET /api/v1/invoices/{id}
Retorna os detalhes de uma fatura específica
Retorna as informações completas de uma fatura específica pelo seu ID.
## Endpoint
```bash cURL theme={null}
curl https://api.upag.io/v1/invoices/inv_abc123xyz \
-H "Authorization: Bearer {token}"
```
## Parâmetros
ID único da fatura, começando com `inv_`.
## Resposta
```json Response theme={null}
{
"id": "inv_abc123xyz",
"customerId": "cus_ahwDXrgYvur89iPs",
"paymentMethodId": "pm_abc123xyz",
"currency": "BRL",
"status": "open",
"livemode": false,
"number": "INV-001",
"description": null,
"dueDate": "2024-12-15T00:00:00.000Z",
"paidAt": null,
"amountDue": 9900,
"amountPaid": 0,
"attemptCount": 1,
"subscriptionId": null,
"items": [
{
"id": "ii_abc123xyz",
"priceId": "price_def456ghi",
"quantity": 1,
"amount": 9900
}
],
"payments": [],
"createdAt": "2024-11-15T10:00:00.000Z",
"updatedAt": "2024-11-15T10:00:00.000Z"
}
```
# Itens da Fatura
Source: https://docs.upag.io/pages/invoices/items
Gerencie os itens de uma fatura
Os itens de uma fatura representam os produtos ou serviços cobrados. Você pode adicionar, atualizar e remover itens em faturas com status `draft`.
## Adicionar Item
```bash cURL theme={null}
curl -X POST https://api.upag.io/v1/invoices/inv_abc123xyz/items \
-H "Authorization: Bearer {token}" \
-H "Content-Type: application/json" \
-d '{
"priceId": "price_def456ghi",
"quantity": 1
}'
```
### Parâmetros — Adicionar Item
ID único da fatura, começando com `inv_`.
ID do preço do produto a ser adicionado.
Quantidade do item. Mínimo: `1`.
### Resposta — Adicionar Item
```json Response theme={null}
{
"id": "ii_abc123xyz",
"priceId": "price_def456ghi",
"quantity": 1,
"amount": 9900
}
```
***
## Atualizar Item
```bash cURL theme={null}
curl -X PUT https://api.upag.io/v1/invoices/inv_abc123xyz/items/ii_abc123xyz \
-H "Authorization: Bearer {token}" \
-H "Content-Type: application/json" \
-d '{
"priceId": "price_def456ghi",
"quantity": 2
}'
```
### Parâmetros — Atualizar Item
ID único da fatura, começando com `inv_`.
ID único do item da fatura, começando com `ii_`.
ID do preço do item (obrigatório no body junto com `quantity`).
Nova quantidade do item.
### Resposta — Atualizar Item
```json Response theme={null}
{
"id": "ii_abc123xyz",
"priceId": "price_def456ghi",
"quantity": 2,
"amount": 9900
}
```
***
## Remover Item
```bash cURL theme={null}
curl -X DELETE https://api.upag.io/v1/invoices/inv_abc123xyz/items/ii_abc123xyz \
-H "Authorization: Bearer {token}"
```
### Parâmetros — Remover Item
ID único da fatura, começando com `inv_`.
ID único do item da fatura, começando com `ii_`.
### Resposta — Remover Item
```json Response theme={null}
{
"id": "ii_abc123xyz",
"deleted": true
}
```
# Listar Faturas
Source: https://docs.upag.io/pages/invoices/list
GET /api/v1/invoices
Retorna uma lista de todas as faturas
Retorna uma lista paginada de todas as faturas. Pode ser filtrada por cliente ou status.
## Endpoint
```bash cURL theme={null}
curl -G https://api.upag.io/v1/invoices \
-H "Authorization: Bearer {token}" \
-d page=1 \
-d limit=10 \
-d customer=cus_ahwDXrgYvur89iPs
```
## Parâmetros
Limita o número de faturas retornadas. Padrão: `10`, máximo: `100`.
Número da página a ser retornada. Padrão: `1`.
Filtra por ID da fatura (`inv_...`).
ID do cliente (`cus_...`) para filtrar faturas desse cliente. O parâmetro na query é `customer`, não `customerId`.
Filtra faturas por status: `draft`, `open`, `paid`, `uncollectible`, `void`.
## Resposta
```json Response theme={null}
{
"data": [
{
"id": "inv_abc123xyz",
"customerId": "cus_ahwDXrgYvur89iPs",
"paymentMethodId": "pm_abc123xyz",
"currency": "BRL",
"status": "open",
"livemode": false,
"number": "INV-001",
"description": null,
"dueDate": "2024-12-15T00:00:00.000Z",
"paidAt": null,
"amountDue": 9900,
"amountPaid": 0,
"attemptCount": 1,
"subscriptionId": null,
"items": [
{
"id": "ii_abc123xyz",
"priceId": "price_def456ghi",
"quantity": 1,
"amount": 9900
}
],
"payments": [],
"createdAt": "2024-11-15T10:00:00.000Z",
"updatedAt": "2024-11-15T10:00:00.000Z"
}
],
"total": 1
}
```
# Marcar Fatura como Paga
Source: https://docs.upag.io/pages/invoices/mark-as-paid
POST /api/v1/invoices/{id}/mark-as-paid
Marca manualmente uma fatura como paga
Marca uma fatura como paga manualmente, sem processar um pagamento pelo gateway. Útil para registrar pagamentos realizados fora da plataforma (ex.: transferência bancária).
## Endpoint
```bash cURL theme={null}
curl -X POST https://api.upag.io/v1/invoices/inv_abc123xyz/mark-as-paid \
-H "Authorization: Bearer {token}"
```
## Parâmetros
ID único da fatura, começando com `inv_`.
## Resposta
```json Response theme={null}
{
"id": "inv_abc123xyz",
"customerId": "cus_ahwDXrgYvur89iPs",
"paymentMethodId": "pm_abc123xyz",
"currency": "BRL",
"status": "paid",
"livemode": false,
"number": "INV-001",
"description": null,
"dueDate": "2024-12-15T00:00:00.000Z",
"paidAt": "2024-11-15T11:00:00.000Z",
"amountDue": 9900,
"amountPaid": 9900,
"attemptCount": 0,
"subscriptionId": null,
"items": [
{
"id": "ii_abc123xyz",
"priceId": "price_def456ghi",
"quantity": 1,
"amount": 9900
}
],
"payments": [],
"createdAt": "2024-11-15T10:00:00.000Z",
"updatedAt": "2024-11-15T11:00:00.000Z"
}
```
# Pagar Fatura
Source: https://docs.upag.io/pages/invoices/pay
POST /api/v1/invoices/{id}/pay
Processa o pagamento de uma fatura
Processa o pagamento de uma fatura utilizando o método de pagamento associado. A fatura deve estar com status `open`.
## Endpoint
```bash cURL theme={null}
curl -X POST https://api.upag.io/v1/invoices/inv_abc123xyz/pay \
-H "Authorization: Bearer {token}"
```
## Parâmetros
ID único da fatura, começando com `inv_`.
## Resposta
```json Response theme={null}
{
"id": "inv_abc123xyz",
"customerId": "cus_ahwDXrgYvur89iPs",
"paymentMethodId": "pm_abc123xyz",
"currency": "BRL",
"status": "paid",
"livemode": false,
"number": "INV-001",
"description": null,
"dueDate": "2024-12-15T00:00:00.000Z",
"paidAt": "2024-11-15T11:00:00.000Z",
"amountDue": 9900,
"amountPaid": 9900,
"attemptCount": 1,
"subscriptionId": null,
"items": [
{
"id": "ii_abc123xyz",
"priceId": "price_def456ghi",
"quantity": 1,
"amount": 9900
}
],
"payments": [],
"createdAt": "2024-11-15T10:00:00.000Z",
"updatedAt": "2024-11-15T11:00:00.000Z"
}
```
# Referência
Source: https://docs.upag.io/pages/invoices/reference
Crie e gerencie faturas dos seus clientes
Uma fatura representa uma cobrança emitida para um cliente. Faturas podem ser criadas manualmente ou geradas automaticamente por assinaturas.
## Estrutura
Uma fatura é representada em nossa API pela seguinte estrutura:
```json theme={null}
{
"id": "inv_abc123xyz",
"customerId": "cus_ahwDXrgYvur89iPs",
"paymentMethodId": "pm_abc123xyz",
"currency": "BRL",
"status": "open",
"livemode": false,
"number": "INV-001",
"description": null,
"dueDate": "2024-12-15T00:00:00.000Z",
"paidAt": null,
"amountDue": 9900,
"amountPaid": 0,
"attemptCount": 0,
"subscriptionId": null,
"items": [
{
"id": "ii_abc123xyz",
"priceId": "price_def456ghi",
"quantity": 1,
"amount": 9900
}
],
"payments": [],
"createdAt": "2024-11-15T10:00:00.000Z",
"updatedAt": "2024-11-15T10:00:00.000Z"
}
```
## Atributos:
```json {2} theme={null}
{
"id": "inv_abc123xyz",
}
```
`id` : string.
Identificador único da fatura, começando com `inv_`
```json {2} theme={null}
{
"livemode": false,
}
```
`livemode` : boolean.
Indica se a fatura está em modo de produção (`true`) ou teste (`false`)
```json {2} theme={null}
{
"customerId": "cus_ahwDXrgYvur89iPs",
}
```
`customerId` : string.
ID do cliente associado à fatura. Veja a referência completa aqui
```json {2} theme={null}
{
"paymentMethodId": "pm_abc123xyz",
}
```
`paymentMethodId` : string | null.
ID do método de pagamento utilizado. Veja a referência completa aqui
```json {2} theme={null}
{
"status": "open",
}
```
`status` : string.
Status atual da fatura
| Status | Descrição |
| --------------- | -------------------------------------------- |
| `draft` | **A fatura está em rascunho** |
| `open` | **A fatura foi emitida e aguarda pagamento** |
| `paid` | **A fatura foi paga** |
| `uncollectible` | **A fatura não pode ser cobrada** |
| `void` | **A fatura foi cancelada** |
```json {2} theme={null}
{
"currency": "BRL",
}
```
`currency` : string.
Código da moeda (ex.: `BRL`)
```json {2} theme={null}
{
"number": "INV-001",
}
```
`number` : string | null.
Número sequencial da fatura gerado automaticamente ao ser emitida
```json {2} theme={null}
{
"description": null,
}
```
`description` : string | null.
Descrição interna da fatura
```json {2} theme={null}
{
"dueDate": "2024-12-15T00:00:00.000Z",
}
```
`dueDate` : string | null.
Data de vencimento da fatura em formato ISO 8601
```json {2} theme={null}
{
"paidAt": null,
}
```
`paidAt` : string | null.
Data em que a fatura foi paga. `null` se ainda não paga
```json {2} theme={null}
{
"amountDue": 9900,
}
```
`amountDue` : number.
Valor total a ser cobrado em centavos
```json {2} theme={null}
{
"amountPaid": 0,
}
```
`amountPaid` : number.
Valor já pago em centavos
```json {2} theme={null}
{
"attemptCount": 0,
}
```
`attemptCount` : number.
Número de tentativas de cobrança realizadas
```json {2} theme={null}
{
"subscriptionId": null,
}
```
`subscriptionId` : string | null.
ID da assinatura que gerou esta fatura. `null` para faturas criadas manualmente
```json {2-7} theme={null}
{
"items": [
{
"id": "ii_abc123xyz",
"priceId": "price_def456ghi",
"quantity": 1,
"amount": 9900
}
]
}
```
`items` : array.
Lista de itens da fatura. Cada item contém `id`, `priceId`, `quantity` e `amount` (em centavos)
```json {2} theme={null}
{
"payments": [],
}
```
`payments` : array.
Lista de pagamentos associados a esta fatura
```json {2} theme={null}
{
"createdAt": "2024-11-15T10:00:00.000Z",
}
```
`createdAt` : string.
Data de criação da fatura em formato ISO 8601
```json {2} theme={null}
{
"updatedAt": "2024-11-15T10:00:00.000Z",
}
```
`updatedAt` : string.
Data da última atualização da fatura em formato ISO 8601
# Próxima Fatura
Source: https://docs.upag.io/pages/invoices/upcoming
GET /api/v1/invoices/upcoming
Retorna a prévia da próxima fatura de uma assinatura
Retorna a prévia da próxima cobrança para uma assinatura (período, itens e valor total). Útil para exibir ao cliente o valor da próxima renovação.
## Endpoint
```bash cURL theme={null}
curl -G https://api.upag.io/v1/invoices/upcoming \
-H "Authorization: Bearer {token}" \
-d subscription=sub_abc123xyz
```
## Parâmetros
ID da assinatura (`sub_...`) usado para calcular a próxima fatura.
## Resposta
Objeto de prévia (não é uma fatura persistida). Inclui período de cobrança previsto, cliente, moeda, itens derivados da assinatura e `amountDue` total.
```json Response theme={null}
{
"subscriptionId": "sub_abc123xyz",
"customerId": "cus_ahwDXrgYvur89iPs",
"currency": "BRL",
"periodStart": "2024-12-15T10:00:00.000Z",
"periodEnd": "2025-01-15T10:00:00.000Z",
"amountDue": 9900,
"items": [
{
"productId": "prod_xyz789abc",
"priceId": "price_def456ghi",
"name": "Plano Pro",
"amount": 9900,
"quantity": 1,
"total": 9900
}
]
}
```
# Criar Método de Pagamento
Source: https://docs.upag.io/pages/payment-methods/create
POST /api/v1/customers/{customerId}/payment-methods
Crie um método de pagamento (cartão ou PIX) para um cliente
Cria um novo método de pagamento de cartão de crédito ou PIX para um cliente.
## Criar com Cartão de Crédito
```bash cURL theme={null}
curl -X POST https://api.upag.io/v1/customers/cus_ahwDXrgYvur89iPs/payment-methods \
-H "Authorization: Bearer {token}" \
-H "Content-Type: application/json" \
-d '{
"type": "credit_card",
"card": {
"number": "4111111111111111",
"expiryMonth": "12",
"expiryYear": "2025",
"cvv": "123",
"holderName": "JOHN DOE"
}
}'
```
```javascript SDK theme={null}
import { Upag } from 'upag';
const upag = new Upag('sk_test_your_api_key');
const paymentMethod = await upag.paymentMethods.create({
customerId: 'cus_ahwDXrgYvur89iPs',
type: 'credit_card',
card: {
number: '4111111111111111',
expMonth: 12,
expYear: 2025,
cvc: '123',
holderName: 'JOHN DOE'
}
});
```
### Parâmetros para Cartão
ID do cliente.
Tipo do método de pagamento. Deve ser `credit_card`.
Número do cartão (13 a 19 dígitos).
Mês de expiração (1-2 dígitos).
Ano de expiração (4 dígitos).
Código de segurança (3-4 dígitos).
Nome do portador do cartão (máximo 255 caracteres).
### Resposta
```json Response theme={null}
{
"id": "pm_abc123xyz",
"livemode": false,
"type": "credit_card",
"expiresIn": null,
"expiryMonth": "12",
"expiryYear": "2025",
"firstDigits": "4111",
"lastDigits": "1111",
"brand": "visa",
"holderName": "JOHN DOE",
"createdAt": 1731622178441,
"updatedAt": 1731622178441
}
```
***
## Criar com PIX
```bash cURL theme={null}
curl -X POST https://api.upag.io/v1/customers/cus_ahwDXrgYvur89iPs/payment-methods \
-H "Authorization: Bearer {token}" \
-H "Content-Type: application/json" \
-d '{
"type": "pix",
"pix": {
"expiresIn": 600
}
}'
```
```javascript SDK theme={null}
import { Upag } from 'upag';
const upag = new Upag('sk_test_your_api_key');
const paymentMethod = await upag.paymentMethods.create({
customerId: 'cus_ahwDXrgYvur89iPs',
type: 'pix',
pix: {
expiresIn: 600
}
});
```
### Parâmetros para PIX
ID do cliente.
Tipo do método de pagamento. Deve ser `pix`.
Tempo de expiração em segundos. Padrão: `600` (10 minutos). Mínimo: `60`, Máximo: `2592000` (30 dias).
### Resposta
```json Response theme={null}
{
"id": "pm_pix123xyz",
"livemode": false,
"type": "pix",
"expiresIn": 600,
"expiryMonth": null,
"expiryYear": null,
"firstDigits": null,
"lastDigits": null,
"brand": null,
"holderName": null,
"createdAt": 1731622178441,
"updatedAt": 1731622178441
}
```
# Buscar Método de Pagamento por ID
Source: https://docs.upag.io/pages/payment-methods/get
GET /api/v1/customers/{customerId}/payment-methods/{paymentMethodId}
Retorna os detalhes de um método de pagamento específico
Retorna as informações completas de um método de pagamento específico.
## Endpoint
```bash cURL theme={null}
curl https://api.upag.io/v1/customers/cus_ahwDXrgYvur89iPs/payment-methods/pm_abc123xyz \
-H "Authorization: Bearer {token}"
```
```javascript SDK theme={null}
import { Upag } from 'upag';
const upag = new Upag('sk_test_your_api_key');
const paymentMethod = await upag.paymentMethods.retrieve('pm_abc123xyz');
```
## Parâmetros
ID do cliente.
ID único do método de pagamento, começando com `pm_`.
## Resposta
```json Response theme={null}
{
"id": "pm_abc123xyz",
"livemode": false,
"type": "credit_card",
"expiresIn": null,
"expiryMonth": "12",
"expiryYear": "2025",
"firstDigits": "4111",
"lastDigits": "1111",
"brand": "visa",
"holderName": "JOHN DOE",
"createdAt": 1731622178441,
"updatedAt": 1731622178441
}
```
# Listar Métodos de Pagamento
Source: https://docs.upag.io/pages/payment-methods/list
GET /api/v1/customers/{customerId}/payment-methods
Retorna todos os métodos de pagamento de um cliente
Retorna uma lista de todos os métodos de pagamento cadastrados para um cliente específico.
## Endpoint
```bash cURL theme={null}
curl -G https://api.upag.io/v1/customers/cus_ahwDXrgYvur89iPs/payment-methods \
-H "Authorization: Bearer {token}" \
-d page=1 \
-d limit=10
```
```javascript SDK theme={null}
import { Upag } from 'upag';
const upag = new Upag('sk_test_your_api_key');
const paymentMethods = await upag.paymentMethods.listByCustomer('cus_ahwDXrgYvur89iPs', {
limit: 10,
offset: 0
});
```
## Parâmetros
ID do cliente.
Limita o número de métodos de pagamento retornados. Padrão: `10`, máximo: `100`.
Número da página a ser retornada. Padrão: `1`.
## Resposta
```json Response theme={null}
{
"data": [
{
"id": "pm_abc123xyz",
"livemode": false,
"type": "credit_card",
"expiresIn": null,
"expiryMonth": "12",
"expiryYear": "2025",
"firstDigits": "4111",
"lastDigits": "1111",
"brand": "visa",
"holderName": "JOHN DOE",
"createdAt": 1731622178441,
"updatedAt": 1731622178441
},
{
"id": "pm_pix123xyz",
"livemode": false,
"type": "pix",
"expiresIn": 600,
"expiryMonth": null,
"expiryYear": null,
"firstDigits": null,
"lastDigits": null,
"brand": null,
"holderName": null,
"createdAt": 1731622178441,
"updatedAt": 1731622178441
}
],
"total": 2
}
```
# Referência
Source: https://docs.upag.io/pages/payment-methods/reference
Gerencie os métodos de pagamento dos seus clientes.
Os métodos de pagamento permitem que seus clientes realizem transações através de cartão de crédito ou PIX.
## Estrutura
Um método de pagamento é representado em nossa API pela seguinte estrutura:
```json theme={null}
{
"id": "pm_abc123xyz",
"livemode": false,
"type": "credit_card",
"expiresIn": null,
"expiryMonth": "12",
"expiryYear": "2025",
"firstDigits": "4111",
"lastDigits": "1111",
"brand": "visa",
"holderName": "JOHN DOE",
"createdAt": 1731622178441,
"updatedAt": 1731622178441
}
```
## Atributos
```json {2} theme={null}
{
"id": "pm_abc123xyz",
}
```
`id` : string.
Identificador único do método de pagamento, começando com `pm_`
```json {2} theme={null}
{
"livemode": false,
}
```
`livemode` : boolean.
Indica se o método de pagamento está em modo de produção (`true`) ou teste (`false`)
```json {2} theme={null}
{
"type": "credit_card",
}
```
`type` : string.
Tipo do método de pagamento
| Tipo | Descrição |
| ------------- | --------------------- |
| `credit_card` | **Cartão de crédito** |
| `pix` | **PIX** |
```json {2} theme={null}
{
"expiresIn": 600,
}
```
`expiresIn` : number | null.
Tempo de expiração em segundos (apenas para PIX). Pode ser `null` para cartões
```json {2} theme={null}
{
"expiryMonth": "12",
}
```
`expiryMonth` : string | null.
Mês de expiração do cartão (MM). Pode ser `null` para PIX
```json {2} theme={null}
{
"expiryYear": "2025",
}
```
`expiryYear` : string | null.
Ano de expiração do cartão (YYYY). Pode ser `null` para PIX
```json {2} theme={null}
{
"firstDigits": "4111",
}
```
`firstDigits` : string | null.
Primeiros dígitos do cartão. Pode ser `null` para PIX
```json {2} theme={null}
{
"lastDigits": "1111",
}
```
`lastDigits` : string | null.
Últimos 4 dígitos do cartão. Pode ser `null` para PIX
```json {2} theme={null}
{
"brand": "visa",
}
```
`brand` : string | null.
Bandeira do cartão (ex.: `visa`, `mastercard`). Pode ser `null` para PIX
```json {2} theme={null}
{
"holderName": "JOHN DOE",
}
```
`holderName` : string | null.
Nome do portador do cartão. Pode ser `null` para PIX
```json {2} theme={null}
{
"createdAt": 1731622178441,
}
```
`createdAt` : number.
Timestamp Unix indicando quando o método de pagamento foi criado
```json {2} theme={null}
{
"updatedAt": 1731622178441,
}
```
`updatedAt` : number.
Timestamp Unix indicando quando o método de pagamento foi atualizado pela última vez
# Criar um novo Pagamento
Source: https://docs.upag.io/pages/payments/create
POST /api/v1/payments
Crie um pagamento usando um método de pagamento do cliente
Cria um novo pagamento para um cliente usando um método de pagamento previamente cadastrado.
## Endpoint
```bash cURL theme={null}
curl -X POST https://api.upag.io/v1/payments \
-H "Authorization: Bearer {token}" \
-H "Content-Type: application/json" \
-d '{
"customer": "cus_ahwDXrgYvur89iPs",
"paymentMethod": "pm_abc123xyz",
"amount": 10000,
"currency": "BRL",
"installments": 1
}'
```
```javascript SDK theme={null}
import { Upag } from 'upag';
const upag = new Upag('sk_test_your_api_key');
const payment = await upag.payments.create({
customerId: 'cus_ahwDXrgYvur89iPs',
paymentMethodId: 'pm_abc123xyz',
amount: 10000,
currency: 'brl',
installments: 1
});
```
## Parâmetros
ID do cliente (UUID).
ID do método de pagamento (UUID).
Valor do pagamento em centavos (mínimo: 1).
Código da moeda (ex.: `BRL`).
Número de parcelas. Padrão: `1`, máximo: `12`.
## Resposta
```json Response theme={null}
{
"id": "pay_xyz789abc",
"livemode": false,
"customer": {
"id": "cus_ahwDXrgYvur89iPs",
"name": "John Doe",
"email": "john.doe@example.com"
},
"paymentMethod": {
"id": "pm_abc123xyz",
"type": "credit_card",
"lastDigits": "1111",
"brand": "visa"
},
"amount": 10000,
"gross": 10000,
"mdr": 0,
"net": 10000,
"interest": 0,
"currency": "BRL",
"status": "paid",
"pixQrCode": null,
"refuseReason": null,
"installments": 1,
"createdAt": 1731622178441,
"updatedAt": 1731622178441,
"dueAt": null
}
```
# Buscar Pagamento por ID
Source: https://docs.upag.io/pages/payments/get
GET /api/v1/payments/{paymentId}
Retorna os detalhes de um pagamento específico
Retorna as informações completas de um pagamento específico pelo seu ID.
## Endpoint
```bash cURL theme={null}
curl https://api.upag.io/v1/payments/pay_xyz789abc \
-H "Authorization: Bearer {token}"
```
```javascript SDK theme={null}
import { Upag } from 'upag';
const upag = new Upag('sk_test_your_api_key');
const payment = await upag.payments.retrieve('pay_xyz789abc');
```
## Parâmetros
ID único do pagamento, começando com `pay_`.
## Resposta
```json Response theme={null}
{
"id": "pay_xyz789abc",
"livemode": false,
"customer": {
"id": "cus_ahwDXrgYvur89iPs",
"name": "John Doe",
"email": "john.doe@example.com"
},
"paymentMethod": {
"id": "pm_abc123xyz",
"type": "credit_card",
"lastDigits": "1111",
"brand": "visa"
},
"amount": 10000,
"gross": 10000,
"mdr": 0,
"net": 10000,
"interest": 0,
"currency": "BRL",
"status": "paid",
"pixQrCode": null,
"refuseReason": null,
"installments": 1,
"createdAt": 1731622178441,
"updatedAt": 1731622178441,
"dueAt": null
}
```
# Listar Pagamentos
Source: https://docs.upag.io/pages/payments/list
GET /api/v1/payments
Retorna uma lista de todos os pagamentos
Retorna uma lista paginada de todos os pagamentos. Pode ser filtrado por cliente.
## Endpoint
```bash cURL theme={null}
curl -G https://api.upag.io/v1/payments \
-H "Authorization: Bearer {token}" \
-d page=1 \
-d limit=10 \
-d customer=cus_ahwDXrgYvur89iPs
```
```javascript SDK theme={null}
import { Upag } from 'upag';
const upag = new Upag('sk_test_your_api_key');
const payments = await upag.payments.list({
limit: 10,
offset: 0,
customerId: 'cus_ahwDXrgYvur89iPs'
});
```
## Parâmetros
Limita o número de pagamentos retornados. Padrão: `10`, máximo: `100`.
Número da página a ser retornada. Padrão: `1`.
ID do cliente (UUID) para filtrar pagamentos de um cliente específico.
## Resposta
```json Response theme={null}
{
"data": [
{
"id": "pay_xyz789abc",
"livemode": false,
"customer": {
"id": "cus_ahwDXrgYvur89iPs",
"name": "John Doe",
"email": "john.doe@example.com"
},
"paymentMethod": {
"id": "pm_abc123xyz",
"type": "credit_card",
"lastDigits": "1111",
"brand": "visa"
},
"amount": 10000,
"gross": 10000,
"mdr": 0,
"net": 10000,
"interest": 0,
"currency": "BRL",
"status": "paid",
"pixQrCode": null,
"refuseReason": null,
"installments": 1,
"createdAt": 1731622178441,
"updatedAt": 1731622178441,
"dueAt": null
}
],
"total": 1
}
```
# Referência
Source: https://docs.upag.io/pages/payments/reference
Crie e gerencie pagamentos dos seus clientes
Um pagamento representa uma transação financeira onde seu cliente paga por produtos ou serviços usando um método de pagamento cadastrado.
## Estrutura
Um pagamento é representado em nossa API pela seguinte estrutura:
```json theme={null}
{
"id": "pay_xyz789abc",
"livemode": false,
"customer": {
"id": "cus_ahwDXrgYvur89iPs",
"name": "John Doe",
"email": "john.doe@example.com"
},
"paymentMethod": {
"id": "pm_abc123xyz",
"type": "credit_card",
"lastDigits": "1111",
"brand": "visa"
},
"amount": 10000,
"gross": 10000,
"mdr": 0,
"net": 10000,
"interest": 0,
"currency": "BRL",
"status": "paid",
"pixQrCode": null,
"refuseReason": null,
"installments": 1,
"createdAt": 1731622178441,
"updatedAt": 1731622178441,
"dueAt": null
}
```
## Atributos:
```json {2} theme={null}
{
"id": "pay_xyz789abc",
}
```
`id` : string.
Identificador único do pagamento, começando com `pay_`
```json {2} theme={null}
{
"livemode": false,
}
```
`livemode` : boolean.
Indica se o pagamento está em modo de produção (`true`) ou teste (`false`)
```json {2-6} theme={null}
{
"customer": {
"id": "cus_ahwDXrgYvur89iPs",
"name": "John Doe",
"email": "john.doe@example.com"
}
}
```
`customer` : object
Objeto contendo informações do cliente. Veja a referência completa aqui
```json {2-7} theme={null}
{
"paymentMethod": {
"id": "pm_abc123xyz",
"type": "credit_card",
"lastDigits": "1111",
"brand": "visa"
}
}
```
`paymentMethod` : object
Objeto contendo informações do método de pagamento. Veja a referência completa aqui
```json {2} theme={null}
{
"amount": 10000,
}
```
`amount` : number.
Valor do pagamento em centavos
```json {2} theme={null}
{
"gross": 10000,
}
```
`gross` : number.
Valor bruto do pagamento em centavos (antes das taxas)
```json {2} theme={null}
{
"mdr": 0,
}
```
`mdr` : number.
Taxa MDR (Merchant Discount Rate) em centavos
```json {2} theme={null}
{
"net": 10000,
}
```
`net` : number.
Valor líquido do pagamento em centavos (após taxas)
```json {2} theme={null}
{
"interest": 0,
}
```
`interest` : number.
Valor de juros em centavos (para parcelamentos)
```json {2} theme={null}
{
"currency": "BRL",
}
```
`currency` : string.
Código da moeda (ex.: `BRL`)
```json {2} theme={null}
{
"status": "paid",
}
```
`status` : string.
Status atual do pagamento
| Status | Descrição |
| ---------- | ----------------------------------------- |
| `pending` | **O pagamento está pendente** |
| `paid` | **O pagamento foi realizado com sucesso** |
| `failed` | **O pagamento falhou** |
| `refunded` | **O valor foi devolvido ao cliente** |
```json {2} theme={null}
{
"pixQrCode": null,
}
```
`pixQrCode` : string | null.
Código QR do PIX para pagamento. Pode ser `null` se não for PIX
```json {2} theme={null}
{
"refuseReason": null,
}
```
`refuseReason` : string | null.
Motivo da recusa do pagamento. Pode ser `null` se não foi recusado
```json {2} theme={null}
{
"installments": 1,
}
```
`installments` : number.
Número de parcelas. Padrão: `1`
```json {2} theme={null}
{
"createdAt": 1731622178441,
}
```
`createdAt` : number.
Timestamp Unix indicando quando o pagamento foi criado
```json {2} theme={null}
{
"updatedAt": 1731622178441,
}
```
`updatedAt` : number.
Timestamp Unix indicando quando o pagamento foi atualizado pela última vez
```json {2} theme={null}
{
"dueAt": null,
}
```
`dueAt` : number | null.
Timestamp Unix indicando a data de vencimento do pagamento. Pode ser `null`
# Fluxo completo: Cliente e Pagamento
Source: https://docs.upag.io/pages/quickstart
Exemplo de fluxo completo criando cliente, método de pagamento e pagamento via API REST
Este guia mostra o fluxo completo em sequência: criar um cliente, cadastrar um método de pagamento (cartão) e criar um pagamento. Use uma chave de API de teste e defina `UPAG_API_KEY` no ambiente (ou substitua no código). O exemplo chama a API nesta ordem: **Cliente** → **Método de pagamento** → **Pagamento**; os IDs retornados em cada passo são usados no seguinte.
```mermaid theme={null}
sequenceDiagram
participant App
participant API
App->>API: POST /customers
API-->>App: customer.id
App->>API: POST /customers/:id/payment-methods
API-->>App: paymentMethod.id
App->>API: POST /payments
API-->>App: payment
```
## Exemplo
```javascript SDK theme={null}
import { Upag } from 'upag';
const upag = new Upag('sk_test_your_api_key');
// 1. Criar cliente
const customer = await upag.customers.create({
name: 'John Doe',
email: 'john.doe@example.com',
phone: '+1234567890'
});
// 2. Cadastrar método de pagamento (cartão)
const paymentMethod = await upag.paymentMethods.create({
customerId: customer.id,
type: 'credit_card',
card: {
number: '4242424242424242',
expMonth: 12,
expYear: 2032,
cvc: '123',
holderName: 'JOHN DOE'
}
});
// 3. Criar pagamento
const payment = await upag.payments.create({
customerId: customer.id,
paymentMethodId: paymentMethod.id,
amount: 1000,
currency: 'brl',
installments: 1
});
console.log('Pagamento criado:', payment);
```
Para detalhes dos parâmetros de cada endpoint, consulte: [Criar Cliente](/customers/create), [Criar Método de Pagamento](/payment-methods/create) e [Criar Pagamento](/payments/create).
# Cancelar Assinatura
Source: https://docs.upag.io/pages/subscriptions/cancel
DELETE /api/v1/subscriptions/{id}
Cancela uma assinatura imediatamente
Cancela uma assinatura. O comportamento depende do body opcional: com `cancelAtPeriodEnd: false` (padrão), o cancelamento é imediato; com `cancelAtPeriodEnd: true`, a assinatura segue até o fim do período atual. Também é possível definir `cancelAtPeriodEnd` via [atualização da assinatura](./update) sem chamar delete.
## Endpoint
```bash cURL theme={null}
curl -X DELETE https://api.upag.io/v1/subscriptions/sub_abc123xyz \
-H "Authorization: Bearer {token}" \
-H "Content-Type: application/json" \
-d '{
"cancelAtPeriodEnd": false,
"cancellationReason": "other"
}'
```
## Parâmetros
ID único da assinatura, começando com `sub_`.
Padrão `false`. Se `true`, agenda cancelamento ao fim do período de cobrança atual.
Opcional. Valores alinhados ao enum da API, por exemplo: `low_quality`, `missing_features`, `other`, `switched_service`, `too_complex`, `too_expensive`, `unused`.
## Resposta
```json Response theme={null}
{
"id": "sub_abc123xyz",
"livemode": false,
"customerId": "cus_ahwDXrgYvur89iPs",
"paymentMethodId": "pm_abc123xyz",
"status": "canceled",
"currency": "BRL",
"interval": "month",
"intervalCount": 1,
"cancelAtPeriodEnd": false,
"startDate": "2024-11-15T10:00:00.000Z",
"endDate": "2024-11-15T11:00:00.000Z",
"trialStartDate": null,
"trialEndDate": null,
"currentPeriodStart": "2024-11-15T10:00:00.000Z",
"currentPeriodEnd": "2024-12-15T10:00:00.000Z",
"canceledAt": "2024-11-15T11:00:00.000Z",
"cancellationReason": "other",
"items": [
{
"id": "si_abc123xyz",
"subscriptionId": "sub_abc123xyz",
"productId": "prod_xyz789abc",
"priceId": "price_def456ghi",
"name": "Plano Pro",
"amount": 9900,
"quantity": 1,
"createdAt": "2024-11-15T10:00:00.000Z",
"updatedAt": "2024-11-15T10:00:00.000Z"
}
],
"createdAt": "2024-11-15T10:00:00.000Z",
"updatedAt": "2024-11-15T11:00:00.000Z"
}
```
# Criar uma Assinatura
Source: https://docs.upag.io/pages/subscriptions/create
POST /api/v1/subscriptions
Crie uma nova assinatura recorrente para um cliente
Cria uma nova assinatura recorrente para um cliente. Moeda e intervalo de cobrança vêm dos preços dos itens (todos os preços devem ser recorrentes e compartilhar o mesmo intervalo e moeda). Se `trialEnd` for informado, a assinatura entra em `trialing` e a cobrança inicial não é processada; caso contrário, a primeira fatura é gerada e o pagamento é tentado na hora.
## Endpoint
```bash cURL theme={null}
curl -X POST https://api.upag.io/v1/subscriptions \
-H "Authorization: Bearer {token}" \
-H "Content-Type: application/json" \
-d '{
"customer": "cus_ahwDXrgYvur89iPs",
"paymentMethod": "pm_abc123xyz",
"items": [
{
"price": "price_def456ghi",
"quantity": 1
}
]
}'
```
## Parâmetros
ID do cliente (`cus_...`) para quem a assinatura será criada.
ID do método de pagamento (`pm_...`) usado nas cobranças.
Lista de itens. Cada item deve conter `price` (ID do preço recorrente) e `quantity` (inteiro, mínimo `1`).
Opcional. Timestamp numérico inteiro positivo indicando o fim do período de teste. Quando presente, a assinatura é criada como `trialing` e não há cobrança inicial neste request.
## Resposta
```json Response theme={null}
{
"id": "sub_abc123xyz",
"livemode": false,
"customerId": "cus_ahwDXrgYvur89iPs",
"paymentMethodId": "pm_abc123xyz",
"status": "active",
"currency": "BRL",
"interval": "month",
"intervalCount": 1,
"cancelAtPeriodEnd": false,
"startDate": "2024-11-15T10:00:00.000Z",
"endDate": null,
"trialStartDate": null,
"trialEndDate": null,
"currentPeriodStart": "2024-11-15T10:00:00.000Z",
"currentPeriodEnd": "2024-12-15T10:00:00.000Z",
"canceledAt": null,
"cancellationReason": null,
"items": [
{
"id": "si_abc123xyz",
"subscriptionId": "sub_abc123xyz",
"productId": "prod_xyz789abc",
"priceId": "price_def456ghi",
"name": "Plano Pro",
"amount": 9900,
"quantity": 1,
"createdAt": "2024-11-15T10:00:00.000Z",
"updatedAt": "2024-11-15T10:00:00.000Z"
}
],
"createdAt": "2024-11-15T10:00:00.000Z",
"updatedAt": "2024-11-15T10:00:00.000Z"
}
```
# Buscar Assinatura por ID
Source: https://docs.upag.io/pages/subscriptions/get
GET /api/v1/subscriptions/{id}
Retorna os detalhes de uma assinatura específica
Retorna as informações completas de uma assinatura específica pelo seu ID.
## Endpoint
```bash cURL theme={null}
curl https://api.upag.io/v1/subscriptions/sub_abc123xyz \
-H "Authorization: Bearer {token}"
```
## Parâmetros
ID único da assinatura, começando com `sub_`.
## Resposta
```json Response theme={null}
{
"id": "sub_abc123xyz",
"livemode": false,
"customerId": "cus_ahwDXrgYvur89iPs",
"paymentMethodId": "pm_abc123xyz",
"status": "active",
"currency": "BRL",
"interval": "month",
"intervalCount": 1,
"cancelAtPeriodEnd": false,
"startDate": "2024-11-15T10:00:00.000Z",
"endDate": null,
"trialStartDate": null,
"trialEndDate": null,
"currentPeriodStart": "2024-11-15T10:00:00.000Z",
"currentPeriodEnd": "2024-12-15T10:00:00.000Z",
"canceledAt": null,
"cancellationReason": null,
"items": [
{
"id": "si_abc123xyz",
"subscriptionId": "sub_abc123xyz",
"productId": "prod_xyz789abc",
"priceId": "price_def456ghi",
"name": "Plano Pro",
"amount": 9900,
"quantity": 1,
"createdAt": "2024-11-15T10:00:00.000Z",
"updatedAt": "2024-11-15T10:00:00.000Z"
}
],
"createdAt": "2024-11-15T10:00:00.000Z",
"updatedAt": "2024-11-15T10:00:00.000Z"
}
```
# Itens da Assinatura
Source: https://docs.upag.io/pages/subscriptions/items
Gerencie os itens de uma assinatura
Os itens de uma assinatura representam os produtos ou serviços cobrados recorrentemente. Dependendo de `applyAt`, a alteração pode ser imediata ou virar uma **mudança agendada** (resposta com objeto de scheduled change em vez do item).
## Adicionar Item
```bash cURL theme={null}
curl -X POST https://api.upag.io/v1/subscriptions/sub_abc123xyz/items \
-H "Authorization: Bearer {token}" \
-H "Content-Type: application/json" \
-d '{
"price": "price_def456ghi",
"quantity": 1,
"applyAt": "now"
}'
```
### Parâmetros — Adicionar Item
ID único da assinatura, começando com `sub_`.
ID do preço (`price_...`) a ser adicionado.
Quantidade (inteiro, mínimo `1`).
Opcional. `now` (padrão) ou `period_end` para aplicar na renovação.
### Resposta — Adicionar Item
`201` com o item criado **ou** com uma mudança agendada, conforme a regra de negócio. Quando for o item, o formato segue o recurso de item da assinatura (ex.: `id`, `subscriptionId`, `productId`, `priceId`, `quantity`, etc.).
***
## Atualizar Item
```bash cURL theme={null}
curl -X PUT https://api.upag.io/v1/subscriptions/sub_abc123xyz/items/si_abc123xyz \
-H "Authorization: Bearer {token}" \
-H "Content-Type: application/json" \
-d '{
"quantity": 2,
"applyAt": "now"
}'
```
É obrigatório enviar **pelo menos um** de `price` ou `quantity`.
### Parâmetros — Atualizar Item
ID único da assinatura, começando com `sub_`.
ID único do item da assinatura, começando com `si_`.
Nova quantidade (opcional se `price` for enviado).
Novo ID de preço (opcional se `quantity` for enviado).
Opcional. `now` ou `period_end`.
### Resposta — Atualizar Item
`200` com o item atualizado ou com mudança agendada, no mesmo sentido do POST.
***
## Remover Item
`applyAt` é lido da **query string** (`req.query`), não do body.
```bash cURL theme={null}
curl -X DELETE "https://api.upag.io/v1/subscriptions/sub_abc123xyz/items/si_abc123xyz?applyAt=now" \
-H "Authorization: Bearer {token}"
```
### Parâmetros — Remover Item
ID único da assinatura, começando com `sub_`.
ID único do item da assinatura, começando com `si_`.
Opcional. `now` (padrão) ou `period_end`.
### Resposta — Remover Item
`204 No Content` quando a remoção é imediata, ou `200` com objeto de mudança agendada quando aplicável.
# Listar Assinaturas
Source: https://docs.upag.io/pages/subscriptions/list
GET /api/v1/subscriptions
Retorna uma lista de todas as assinaturas
Retorna uma lista paginada de todas as assinaturas. Pode ser filtrada por cliente ou status.
## Endpoint
```bash cURL theme={null}
curl -G https://api.upag.io/v1/subscriptions \
-H "Authorization: Bearer {token}" \
-d page=1 \
-d limit=10 \
-d customer=cus_ahwDXrgYvur89iPs
```
## Parâmetros
Limita o número de assinaturas retornadas. Padrão: `10`, máximo: `100`.
Número da página a ser retornada. Padrão: `1`.
Filtra por ID da assinatura (`sub_...`).
ID do cliente (`cus_...`) para filtrar assinaturas desse cliente. O nome do parâmetro na query é `customer`.
Filtra assinaturas por status: `active`, `trialing`, `past_due`, `canceled`, `unpaid`, `incomplete`.
Quando `true` ou `false`, filtra assinaturas com esse valor de `cancelAtPeriodEnd`. Envie como string `true` ou `false` na query.
## Resposta
```json Response theme={null}
{
"data": [
{
"id": "sub_abc123xyz",
"livemode": false,
"customerId": "cus_ahwDXrgYvur89iPs",
"paymentMethodId": "pm_abc123xyz",
"status": "active",
"currency": "BRL",
"interval": "month",
"intervalCount": 1,
"cancelAtPeriodEnd": false,
"startDate": "2024-11-15T10:00:00.000Z",
"endDate": null,
"trialStartDate": null,
"trialEndDate": null,
"currentPeriodStart": "2024-11-15T10:00:00.000Z",
"currentPeriodEnd": "2024-12-15T10:00:00.000Z",
"canceledAt": null,
"cancellationReason": null,
"items": [
{
"id": "si_abc123xyz",
"subscriptionId": "sub_abc123xyz",
"productId": "prod_xyz789abc",
"priceId": "price_def456ghi",
"name": "Plano Pro",
"amount": 9900,
"quantity": 1,
"createdAt": "2024-11-15T10:00:00.000Z",
"updatedAt": "2024-11-15T10:00:00.000Z"
}
],
"createdAt": "2024-11-15T10:00:00.000Z",
"updatedAt": "2024-11-15T10:00:00.000Z"
}
],
"total": 1
}
```
# Referência
Source: https://docs.upag.io/pages/subscriptions/reference
Crie e gerencie assinaturas recorrentes dos seus clientes
Uma assinatura representa uma cobrança recorrente de um cliente por um produto ou serviço. Faturas são geradas automaticamente a cada período de renovação.
## Estrutura
Uma assinatura é representada em nossa API pela seguinte estrutura:
```json theme={null}
{
"id": "sub_abc123xyz",
"livemode": false,
"customerId": "cus_ahwDXrgYvur89iPs",
"paymentMethodId": "pm_abc123xyz",
"status": "active",
"currency": "BRL",
"interval": "month",
"intervalCount": 1,
"cancelAtPeriodEnd": false,
"startDate": "2024-11-15T10:00:00.000Z",
"endDate": null,
"trialStartDate": null,
"trialEndDate": null,
"currentPeriodStart": "2024-11-15T10:00:00.000Z",
"currentPeriodEnd": "2024-12-15T10:00:00.000Z",
"canceledAt": null,
"cancellationReason": null,
"items": [
{
"id": "si_abc123xyz",
"subscriptionId": "sub_abc123xyz",
"productId": "prod_xyz789abc",
"priceId": "price_def456ghi",
"name": "Plano Pro",
"amount": 9900,
"quantity": 1,
"createdAt": "2024-11-15T10:00:00.000Z",
"updatedAt": "2024-11-15T10:00:00.000Z"
}
],
"createdAt": "2024-11-15T10:00:00.000Z",
"updatedAt": "2024-11-15T10:00:00.000Z"
}
```
## Atributos:
```json {2} theme={null}
{
"id": "sub_abc123xyz",
}
```
`id` : string.
Identificador único da assinatura, começando com `sub_`
```json {2} theme={null}
{
"livemode": false,
}
```
`livemode` : boolean.
Indica se a assinatura está em modo de produção (`true`) ou teste (`false`)
```json {2} theme={null}
{
"customerId": "cus_ahwDXrgYvur89iPs",
}
```
`customerId` : string.
ID do cliente associado à assinatura. Veja a referência completa aqui
```json {2} theme={null}
{
"paymentMethodId": "pm_abc123xyz",
}
```
`paymentMethodId` : string | null.
ID do método de pagamento utilizado para as cobranças recorrentes. Veja a referência completa aqui
```json {2} theme={null}
{
"status": "active",
}
```
`status` : string.
Status atual da assinatura
| Status | Descrição |
| ------------ | --------------------------------------------- |
| `active` | **A assinatura está ativa e sendo cobrada** |
| `trialing` | **A assinatura está em período de teste** |
| `past_due` | **O pagamento está atrasado** |
| `canceled` | **A assinatura foi cancelada** |
| `unpaid` | **A assinatura está inadimplente** |
| `incomplete` | **A assinatura está pendente de confirmação** |
```json {2} theme={null}
{
"interval": "month",
}
```
`interval` : string.
Intervalo de cobrança: `day`, `week`, `month`, `year`
```json {2} theme={null}
{
"intervalCount": 1,
}
```
`intervalCount` : number.
Quantidade de intervalos entre cada cobrança. Ex.: `intervalCount: 3` com `interval: month` = cobrança a cada 3 meses
```json {2} theme={null}
{
"cancelAtPeriodEnd": false,
}
```
`cancelAtPeriodEnd` : boolean.
Se `true`, a assinatura será cancelada ao final do período atual em vez de renovar
```json {2-3} theme={null}
{
"currentPeriodStart": "2024-11-15T10:00:00.000Z",
"currentPeriodEnd": "2024-12-15T10:00:00.000Z",
}
```
`currentPeriodStart` / `currentPeriodEnd` : string | null.
Datas de início e fim do período de cobrança atual em formato ISO 8601
```json {2-3} theme={null}
{
"trialStartDate": null,
"trialEndDate": null,
}
```
`trialStartDate` / `trialEndDate` : string | null.
Datas do período de teste em formato ISO 8601. `null` se não há período de teste
```json {2} theme={null}
{
"cancellationReason": null,
}
```
`cancellationReason` : string | null.
Motivo do cancelamento. Valores: `low_quality`, `missing_features`, `other`, `switched_service`, `too_complex`, `too_expensive`, `unused`
```json {2-12} theme={null}
{
"items": [
{
"id": "si_abc123xyz",
"subscriptionId": "sub_abc123xyz",
"productId": "prod_xyz789abc",
"priceId": "price_def456ghi",
"name": "Plano Pro",
"amount": 9900,
"quantity": 1,
"createdAt": "2024-11-15T10:00:00.000Z",
"updatedAt": "2024-11-15T10:00:00.000Z"
}
]
}
```
`items` : array.
Lista de itens da assinatura. Cada item contém `id`, `subscriptionId`, `productId`, `priceId`, `name`, `amount` (em centavos), `quantity`, `createdAt` e `updatedAt`
```json {2} theme={null}
{
"canceledAt": null,
}
```
`canceledAt` : string | null.
Data em que a assinatura foi cancelada em formato ISO 8601. `null` se ativa
```json {2} theme={null}
{
"createdAt": "2024-11-15T10:00:00.000Z",
}
```
`createdAt` : string.
Data de criação da assinatura em formato ISO 8601
```json {2} theme={null}
{
"updatedAt": "2024-11-15T10:00:00.000Z",
}
```
`updatedAt` : string.
Data da última atualização da assinatura em formato ISO 8601
# Mudanças Agendadas
Source: https://docs.upag.io/pages/subscriptions/scheduled-changes
Consulte e cancele mudanças agendadas de uma assinatura
Mudanças agendadas representam alterações em itens de uma assinatura que entrarão em vigor no próximo período de cobrança. Por exemplo, ao atualizar o plano de um cliente, a mudança pode ser agendada para não interromper o ciclo atual.
## Listar Mudanças Agendadas
```bash cURL theme={null}
curl https://api.upag.io/v1/subscriptions/sub_abc123xyz/scheduled-changes \
-H "Authorization: Bearer {token}"
```
### Parâmetros — Listar
ID único da assinatura, começando com `sub_`.
### Resposta — Listar
```json Response theme={null}
{
"data": [
{
"id": "sc_abc123xyz",
"subscriptionId": "sub_abc123xyz",
"operation": "add",
"itemId": "si_abc123xyz",
"priceId": "price_ghi789jkl",
"quantity": 1,
"createdAt": "2024-11-15T10:00:00.000Z"
}
],
"total": 1
}
```
***
## Cancelar Mudança Agendada
Remove uma mudança agendada antes que ela entre em vigor.
```bash cURL theme={null}
curl -X DELETE https://api.upag.io/v1/subscriptions/sub_abc123xyz/scheduled-changes/sc_abc123xyz \
-H "Authorization: Bearer {token}"
```
### Parâmetros — Cancelar
ID único da assinatura, começando com `sub_`.
ID único da mudança agendada, começando com `sc_`.
### Resposta — Cancelar
```json Response theme={null}
{
"id": "sc_abc123xyz",
"deleted": true
}
```
# Atualizar Assinatura
Source: https://docs.upag.io/pages/subscriptions/update
PUT /api/v1/subscriptions/{id}
Atualiza os dados de uma assinatura existente
Atualiza os dados de uma assinatura. Apenas `paymentMethod` e `cancelAtPeriodEnd` são aceitos no body. Para alterar itens, use os endpoints de [itens da assinatura](./items).
## Endpoint
```bash cURL theme={null}
curl -X PUT https://api.upag.io/v1/subscriptions/sub_abc123xyz \
-H "Authorization: Bearer {token}" \
-H "Content-Type: application/json" \
-d '{
"paymentMethod": "pm_def456ghi",
"cancelAtPeriodEnd": true
}'
```
## Parâmetros
ID único da assinatura, começando com `sub_`.
Novo ID do método de pagamento a ser utilizado nas cobranças.
Se `true`, a assinatura será cancelada ao final do período atual em vez de renovar.
## Resposta
```json Response theme={null}
{
"id": "sub_abc123xyz",
"livemode": false,
"customerId": "cus_ahwDXrgYvur89iPs",
"paymentMethodId": "pm_def456ghi",
"status": "active",
"currency": "BRL",
"interval": "month",
"intervalCount": 1,
"cancelAtPeriodEnd": true,
"startDate": "2024-11-15T10:00:00.000Z",
"endDate": null,
"trialStartDate": null,
"trialEndDate": null,
"currentPeriodStart": "2024-11-15T10:00:00.000Z",
"currentPeriodEnd": "2024-12-15T10:00:00.000Z",
"canceledAt": null,
"cancellationReason": null,
"items": [
{
"id": "si_abc123xyz",
"subscriptionId": "sub_abc123xyz",
"productId": "prod_xyz789abc",
"priceId": "price_def456ghi",
"name": "Plano Pro",
"amount": 9900,
"quantity": 1,
"createdAt": "2024-11-15T10:00:00.000Z",
"updatedAt": "2024-11-15T10:00:00.000Z"
}
],
"createdAt": "2024-11-15T10:00:00.000Z",
"updatedAt": "2024-11-15T11:00:00.000Z"
}
```
# Webhooks
Source: https://docs.upag.io/pages/webhooks/overview
Configure e consuma webhooks para ser notificado sobre eventos da sua conta
Os webhooks permitem que sua aplicação seja notificada quando algo acontecer no Upag (assinatura criada, pagamento aprovado, fatura paga, etc.). Configure uma URL no painel e selecione os eventos que deseja receber.
## Envelope da requisição
Cada requisição de webhook enviada pelo Upag segue este formato:
```json theme={null}
{
"event": "subscription.created",
"data": { }
}
```
* **event** — Nome do evento (ex.: `subscription.created`, `payment.approved`). Use este valor para decidir como processar o payload.
* **data** — Objeto com os dados do recurso. A estrutura de `data` depende do tipo de evento. Consulte as páginas de referência abaixo para cada payload.
## Tipos de evento
### Assinaturas (subscription)
| Evento | Descrição |
| ------------------------- | ------------------------------ |
| `subscription.created` | Nova assinatura criada |
| `subscription.active` | Assinatura ativa |
| `subscription.canceled` | Assinatura cancelada |
| `subscription.past_due` | Assinatura em atraso |
| `subscription.trialing` | Assinatura em período de trial |
| `subscription.incomplete` | Assinatura incompleta |
| `subscription.paused` | Assinatura pausada |
| `subscription.void` | Assinatura anulada |
Referência do objeto em `data`: Payload Subscription.
### Pagamentos (payment)
| Evento | Descrição |
| -------------------- | --------------------- |
| `payment.created` | Novo pagamento criado |
| `payment.incomplete` | Pagamento incompleto |
| `payment.pending` | Pagamento pendente |
| `payment.approved` | Pagamento aprovado |
| `payment.refunded` | Pagamento reembolsado |
| `payment.refused` | Pagamento recusado |
| `payment.failed` | Pagamento falhou |
Referência do objeto em `data`: Payload Payment.
### Faturas (invoice)
| Evento | Descrição |
| ----------------- | ------------------ |
| `invoice.created` | Nova fatura criada |
| `invoice.opened` | Fatura aberta |
| `invoice.paid` | Fatura paga |
| `invoice.voided` | Fatura anulada |
Referência do objeto em `data`: Payload Invoice.
## Segurança
Para garantir que a requisição foi enviada pelo Upag, verifique a assinatura usando o cabeçalho da requisição (por exemplo `x-Upag-signature` ou o nome configurado no painel) e sua chave secreta de webhook. A assinatura é um HMAC do corpo da requisição. Compare o hash que você calcular com o valor do cabeçalho; se forem iguais, a requisição é autêntica. Mantenha a chave secreta em segurança e nunca a exponha no código ou em repositórios públicos.
# Payload — Invoice
Source: https://docs.upag.io/pages/webhooks/payload-invoice
Estrutura do objeto data nos webhooks de fatura
Quando o evento é do tipo `invoice.*`, o campo `data` da requisição de webhook contém um objeto fatura no formato abaixo.
## Estrutura
```json theme={null}
{
"id": "inv_xyz789abc",
"livemode": false,
"customer": "cus_ahwDXrgYvur89iPs",
"paymentMethod": "pm_abc123xyz",
"status": "open",
"currency": "BRL",
"createdAt": 1731622178441,
"updatedAt": 1731622178441,
"canceledAt": null,
"items": [
{
"id": "ii_abc123",
"product": "prod_xyz",
"price": "pri_xyz",
"name": "Plano Mensal",
"amount": 9900,
"quantity": 1
}
]
}
```
## Atributos
```json {2} theme={null}
{
"id": "inv_xyz789abc",
}
```
`id` : string.
Identificador único da fatura, começando com `inv_`
```json {2} theme={null}
{
"livemode": false,
}
```
`livemode` : boolean.
Indica se a fatura está em modo de produção (`true`) ou teste (`false`)
```json {2} theme={null}
{
"customer": "cus_ahwDXrgYvur89iPs",
}
```
`customer` : string.
ID do cliente, começando com `cus_`
```json {2} theme={null}
{
"paymentMethod": "pm_abc123xyz",
}
```
`paymentMethod` : string.
ID do método de pagamento, começando com `pm_`
```json {2} theme={null}
{
"status": "open",
}
```
`status` : string.
Status atual da fatura (ex.: `draft`, `open`, `paid`, `void`)
```json {2} theme={null}
{
"currency": "BRL",
}
```
`currency` : string.
Código da moeda (ex.: `BRL`)
```json {2} theme={null}
{
"createdAt": 1731622178441,
}
```
`createdAt` : number.
Timestamp Unix de criação da fatura
```json {2} theme={null}
{
"updatedAt": 1731622178441,
}
```
`updatedAt` : number.
Timestamp Unix da última atualização
```json {2} theme={null}
{
"canceledAt": null,
}
```
`canceledAt` : number | null.
Timestamp Unix do cancelamento da fatura. Pode ser `null`
```json {2-12} theme={null}
{
"items": [
{
"id": "ii_abc123",
"product": "prod_xyz",
"price": "pri_xyz",
"name": "Plano Mensal",
"amount": 9900,
"quantity": 1
}
]
}
```
`items` : array.
Lista de itens da fatura. Cada item contém: `id` (string, prefixo `ii_`), `product` (ID do produto), `price` (ID do preço), `name`, `amount` (centavos), `quantity`
# Payload — Payment
Source: https://docs.upag.io/pages/webhooks/payload-payment
Estrutura do objeto data nos webhooks de pagamento
Quando o evento é do tipo `payment.*`, o campo `data` da requisição de webhook contém um objeto pagamento no formato abaixo.
## Estrutura
```json theme={null}
{
"id": "pay_xyz789abc",
"livemode": false,
"customer": "cus_ahwDXrgYvur89iPs",
"paymentMethod": "pm_abc123xyz",
"amount": 10000,
"refundedAmount": 0,
"gross": 10000,
"mdr": 0,
"net": 10000,
"interest": 0,
"currency": "BRL",
"status": "approved",
"description": null,
"pixQrCode": null,
"refuseReason": null,
"installments": 1,
"createdAt": 1731622178441,
"updatedAt": 1731622178441,
"dueAt": null
}
```
## Atributos
```json {2} theme={null}
{
"id": "pay_xyz789abc",
}
```
`id` : string.
Identificador único do pagamento, começando com `pay_`
```json {2} theme={null}
{
"livemode": false,
}
```
`livemode` : boolean.
Indica se o pagamento está em modo de produção (`true`) ou teste (`false`)
```json {2} theme={null}
{
"customer": "cus_ahwDXrgYvur89iPs",
}
```
`customer` : string.
ID do cliente, começando com `cus_`
```json {2} theme={null}
{
"paymentMethod": "pm_abc123xyz",
}
```
`paymentMethod` : string.
ID do método de pagamento, começando com `pm_`
```json {2} theme={null}
{
"amount": 10000,
}
```
`amount` : number.
Valor do pagamento em centavos
```json {2} theme={null}
{
"refundedAmount": 0,
}
```
`refundedAmount` : number.
Valor já reembolsado em centavos
```json {2} theme={null}
{
"gross": 10000,
}
```
`gross` : number.
Valor bruto do pagamento em centavos (antes das taxas)
```json {2} theme={null}
{
"mdr": 0,
}
```
`mdr` : number.
Taxa MDR (Merchant Discount Rate) em centavos
```json {2} theme={null}
{
"net": 10000,
}
```
`net` : number.
Valor líquido do pagamento em centavos (após taxas)
```json {2} theme={null}
{
"interest": 0,
}
```
`interest` : number.
Valor de juros em centavos (para parcelamentos)
```json {2} theme={null}
{
"currency": "BRL",
}
```
`currency` : string.
Código da moeda (ex.: `BRL`)
```json {2} theme={null}
{
"status": "approved",
}
```
`status` : string.
Status atual do pagamento
| Status | Descrição |
| ------------ | -------------------- |
| `incomplete` | Pagamento incompleto |
| `pending` | Pagamento pendente |
| `approved` | Pagamento aprovado |
| `refused` | Pagamento recusado |
| `refunded` | Valor reembolsado |
| `failed` | Pagamento falhou |
```json {2} theme={null}
{
"description": null,
}
```
`description` : string | null.
Descrição do pagamento. Pode ser `null`
```json {2} theme={null}
{
"pixQrCode": null,
}
```
`pixQrCode` : string | null.
Código QR do PIX para pagamento. Pode ser `null` se não for PIX
```json {2} theme={null}
{
"refuseReason": null,
}
```
`refuseReason` : string | null.
Motivo da recusa do pagamento. Pode ser `null` se não foi recusado
```json {2} theme={null}
{
"installments": 1,
}
```
`installments` : number.
Número de parcelas. Padrão: `1`
```json {2} theme={null}
{
"createdAt": 1731622178441,
}
```
`createdAt` : number.
Timestamp Unix indicando quando o pagamento foi criado
```json {2} theme={null}
{
"updatedAt": 1731622178441,
}
```
`updatedAt` : number.
Timestamp Unix indicando quando o pagamento foi atualizado pela última vez
```json {2} theme={null}
{
"dueAt": null,
}
```
`dueAt` : number | null.
Timestamp Unix indicando a data de vencimento do pagamento. Pode ser `null`
# Payload — Subscription
Source: https://docs.upag.io/pages/webhooks/payload-subscription
Estrutura do objeto data nos webhooks de assinatura
Quando o evento é do tipo `subscription.*`, o campo `data` da requisição de webhook contém um objeto assinatura no formato abaixo.
## Estrutura
```json theme={null}
{
"id": "sub_xyz789abc",
"livemode": false,
"customer": "cus_ahwDXrgYvur89iPs",
"paymentMethod": "pm_abc123xyz",
"status": "active",
"currency": "BRL",
"interval": "month",
"intervalCount": 1,
"cancelAtPeriodEnd": false,
"startDate": 1731622178441,
"endDate": null,
"trialStartDate": null,
"trialEndDate": null,
"currentPeriodStart": 1731622178441,
"currentPeriodEnd": 1734300578441,
"createdAt": 1731622178441,
"updatedAt": 1731622178441,
"canceledAt": null,
"items": [
{
"id": "si_abc123",
"product": "prod_xyz",
"price": "pri_xyz",
"name": "Plano Mensal",
"amount": 9900,
"quantity": 1,
"createdAt": 1731622178441,
"updatedAt": 1731622178441
}
]
}
```
## Atributos
```json {2} theme={null}
{
"id": "sub_xyz789abc",
}
```
`id` : string.
Identificador único da assinatura, começando com `sub_`
```json {2} theme={null}
{
"livemode": false,
}
```
`livemode` : boolean.
Indica se a assinatura está em modo de produção (`true`) ou teste (`false`)
```json {2} theme={null}
{
"customer": "cus_ahwDXrgYvur89iPs",
}
```
`customer` : string.
ID do cliente, começando com `cus_`
```json {2} theme={null}
{
"paymentMethod": "pm_abc123xyz",
}
```
`paymentMethod` : string.
ID do método de pagamento, começando com `pm_`
```json {2} theme={null}
{
"status": "active",
}
```
`status` : string.
Status atual da assinatura (ex.: `active`, `canceled`, `past_due`, `trialing`, `incomplete`, `paused`, `void`)
```json {2} theme={null}
{
"currency": "BRL",
}
```
`currency` : string.
Código da moeda (ex.: `BRL`)
```json {2} theme={null}
{
"interval": "month",
}
```
`interval` : string.
Intervalo de cobrança (ex.: `day`, `month`, `year`)
```json {2} theme={null}
{
"intervalCount": 1,
}
```
`intervalCount` : number.
Quantidade de intervalos entre cada cobrança
```json {2} theme={null}
{
"cancelAtPeriodEnd": false,
}
```
`cancelAtPeriodEnd` : boolean.
Se a assinatura será cancelada ao final do período atual
```json {2} theme={null}
{
"startDate": 1731622178441,
}
```
`startDate` : number.
Timestamp Unix de início da assinatura
```json {2} theme={null}
{
"endDate": null,
}
```
`endDate` : number | null.
Timestamp Unix de fim da assinatura. Pode ser `null`
```json {2} theme={null}
{
"trialStartDate": null,
}
```
`trialStartDate` : number | null.
Início do período de trial. Pode ser `null`
```json {2} theme={null}
{
"trialEndDate": null,
}
```
`trialEndDate` : number | null.
Fim do período de trial. Pode ser `null`
```json {2} theme={null}
{
"currentPeriodStart": 1731622178441,
}
```
`currentPeriodStart` : number.
Início do período atual de cobrança (timestamp Unix)
```json {2} theme={null}
{
"currentPeriodEnd": 1734300578441,
}
```
`currentPeriodEnd` : number.
Fim do período atual de cobrança (timestamp Unix)
```json {2} theme={null}
{
"createdAt": 1731622178441,
}
```
`createdAt` : number.
Timestamp Unix de criação
```json {2} theme={null}
{
"updatedAt": 1731622178441,
}
```
`updatedAt` : number.
Timestamp Unix da última atualização
```json {2} theme={null}
{
"canceledAt": null,
}
```
`canceledAt` : number | null.
Timestamp Unix do cancelamento. Pode ser `null`
```json {2-13} theme={null}
{
"items": [
{
"id": "si_abc123",
"product": "prod_xyz",
"price": "pri_xyz",
"name": "Plano Mensal",
"amount": 9900,
"quantity": 1,
"createdAt": 1731622178441,
"updatedAt": 1731622178441
}
]
}
```
`items` : array.
Lista de itens da assinatura. Cada item contém: `id` (string, prefixo `si_`), `product` (ID do produto), `price` (ID do preço), `name`, `amount` (centavos), `quantity`, `createdAt`, `updatedAt`