Faturamento
Gerenciamento de faturas (Invoices) e pagamentos (Payments).
Endpoints de Faturas
| Método | Endpoint | Descrição | Permissão |
|---|---|---|---|
| POST | /billing/api/v1/invoices | Criar fatura | BILLING_INVOICES_CREATE |
| GET | /billing/api/v1/invoices | Listar faturas | BILLING_INVOICES_READ |
| GET | /billing/api/v1/invoices/:id | Obter fatura por ID | BILLING_INVOICES_READ |
| PATCH | /billing/api/v1/invoices/:id | Atualizar fatura | BILLING_INVOICES_UPDATE |
| POST | /billing/api/v1/invoices/:id/finalize | Finalizar fatura | BILLING_INVOICES_FINALIZE |
| POST | /billing/api/v1/invoices/:id/void | Anular fatura | BILLING_INVOICES_VOID |
| POST | /billing/api/v1/invoices/:id/line-items | Adicionar linha à fatura | BILLING_INVOICES_UPDATE |
| POST | /billing/api/v1/invoices/generate | Gerar fatura de assinatura | BILLING_INVOICES_CREATE |
Endpoints de Pagamentos
| Método | Endpoint | Descrição | Permissão |
|---|---|---|---|
| POST | /billing/api/v1/payments | Registrar pagamento | BILLING_PAYMENTS_RECORD |
| GET | /billing/api/v1/payments | Listar pagamentos | BILLING_PAYMENTS_READ |
| GET | /billing/api/v1/payments/:id | Obter pagamento por ID | BILLING_PAYMENTS_READ |
| POST | /billing/api/v1/payments/:id/refund | Processar reembolso | BILLING_PAYMENTS_REFUND |
Atributos da Fatura
| Campo | Tipo | Descrição |
|---|---|---|
billingAccountId | string (UUID) | ID da conta de faturamento |
invoiceNumber | string | Número da fatura (gerado automaticamente) |
status | enum | Status da fatura |
currency | string | Moeda |
periodStart | datetime | Início do período de cobrança |
periodEnd | datetime | Fim do período de cobrança |
subtotal | number | Subtotal antes de taxas |
taxAmount | number | Valor de impostos |
discountAmount | number | Valor de descontos |
total | number | Valor total |
amountPaid | number | Valor já pago |
amountDue | number | Valor em aberto |
dueDate | datetime | Data de vencimento |
finalizedAt | datetime | Data de finalização |
paidAt | datetime | Data do pagamento completo |
voidedAt | datetime | Data de anulação |
notes | string | Observações |
lineItems | array | Itens da fatura |
createdAt | datetime | Data de criação |
updatedAt | datetime | Data da última atualização |
Status da Fatura
| Status | Descrição |
|---|---|
DRAFT | Rascunho - pode ser editada |
PENDING | Finalizada - aguardando pagamento |
PAID | Paga integralmente |
OVERDUE | Vencida - pagamento atrasado |
CANCELED | Cancelada (antes de finalizar) |
VOID | Anulada (após finalizar) |
Tipos de Cobrança (chargeType)
| Tipo | Descrição |
|---|---|
SUBSCRIPTION | Cobrança de assinatura |
USAGE | Cobrança por uso |
ONE_TIME | Cobrança única |
PRORATION | Ajuste proporcional |
CREDIT | Crédito (valor negativo) |
Atributos do Pagamento
| Campo | Tipo | Descrição |
|---|---|---|
billingAccountId | string (UUID) | ID da conta de faturamento |
invoiceId | string (UUID) | ID da fatura (opcional) |
status | enum | Status do pagamento |
amount | number | Valor do pagamento |
currency | string | Moeda |
paymentMethod | string | Método de pagamento |
externalRef | string | Referência externa (gateway) |
refundedAmount | number | Valor reembolsado |
refundedAt | datetime | Data do reembolso |
processedAt | datetime | Data do processamento |
failedAt | datetime | Data da falha |
failureReason | string | Motivo da falha |
metadata | object | Dados adicionais |
createdAt | datetime | Data de criação |
updatedAt | datetime | Data da última atualização |
Status do Pagamento
| Status | Descrição |
|---|---|
PENDING | Aguardando processamento |
PROCESSING | Em processamento |
COMPLETED | Concluído com sucesso |
FAILED | Falhou |
REFUNDED | Reembolsado (total ou parcial) |
Criar Fatura
POST /api/v1/invoices
Cria uma nova fatura para uma conta de faturamento.
Atributos
| Campo | Tipo | Obrigatório | Descrição |
|---|---|---|---|
billingAccountId | string | Sim | ID da conta de faturamento |
periodStart | datetime | Sim | Início do período |
periodEnd | datetime | Sim | Fim do período |
dueDate | datetime | Não | Data de vencimento |
notes | string | Não | Observações |
- cURL
- JavaScript
curl -X POST 'https://billing.stg.catalisa.app/billing/api/v1/invoices' \
-H 'Authorization: Bearer SEU_TOKEN' \
-H 'Content-Type: application/json' \
-d '{
"data": {
"type": "invoices",
"attributes": {
"billingAccountId": "550e8400-e29b-41d4-a716-446655440010",
"periodStart": "2024-02-01T00:00:00Z",
"periodEnd": "2024-02-29T23:59:59Z",
"dueDate": "2024-03-10T23:59:59Z"
}
}
}'
const response = await fetch('https://billing.stg.catalisa.app/billing/api/v1/invoices', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
data: {
type: 'invoices',
attributes: {
billingAccountId: '550e8400-e29b-41d4-a716-446655440010',
periodStart: '2024-02-01T00:00:00Z',
periodEnd: '2024-02-29T23:59:59Z',
dueDate: '2024-03-10T23:59:59Z',
},
},
}),
});
const { data } = await response.json();
console.log(`Fatura criada: ${data.attributes.invoiceNumber}`);
Response (201 Created)
{
"data": {
"type": "invoices",
"id": "550e8400-e29b-41d4-a716-446655440050",
"links": {
"self": "/api/v1/invoices/550e8400-e29b-41d4-a716-446655440050"
},
"attributes": {
"billingAccountId": "550e8400-e29b-41d4-a716-446655440010",
"invoiceNumber": "INV-2024-0001",
"status": "DRAFT",
"currency": "BRL",
"periodStart": "2024-02-01T00:00:00Z",
"periodEnd": "2024-02-29T23:59:59Z",
"subtotal": 0,
"taxAmount": 0,
"discountAmount": 0,
"total": 0,
"amountPaid": 0,
"amountDue": 0,
"dueDate": "2024-03-10T23:59:59Z",
"lineItems": [],
"createdAt": "2024-02-28T10:00:00Z",
"updatedAt": "2024-02-28T10:00:00Z"
}
},
"links": {
"self": "/api/v1/invoices/550e8400-e29b-41d4-a716-446655440050"
}
}
Adicionar Linha à Fatura
POST /billing/api/v1/invoices/:id/line-items
Adiciona um item de cobrança à fatura (somente para faturas em DRAFT).
Atributos
| Campo | Tipo | Obrigatório | Descrição |
|---|---|---|---|
subscriptionId | string | Não | ID da assinatura relacionada |
chargeType | enum | Sim | Tipo de cobrança |
description | string | Sim | Descrição do item |
quantity | number | Sim | Quantidade |
unitPrice | number | Sim | Preço unitário |
periodStart | datetime | Não | Início do período |
periodEnd | datetime | Não | Fim do período |
metadata | object | Não | Dados adicionais |
- cURL
- JavaScript
curl -X POST 'https://billing.stg.catalisa.app/billing/api/v1/invoices/550e8400-e29b-41d4-a716-446655440050/line-items' \
-H 'Authorization: Bearer SEU_TOKEN' \
-H 'Content-Type: application/json' \
-d '{
"data": {
"type": "invoice-line-items",
"attributes": {
"chargeType": "SUBSCRIPTION",
"description": "Plano Pro - Fevereiro 2024",
"quantity": 5,
"unitPrice": 299.90,
"periodStart": "2024-02-01T00:00:00Z",
"periodEnd": "2024-02-29T23:59:59Z"
}
}
}'
const invoiceId = '550e8400-e29b-41d4-a716-446655440050';
const response = await fetch(`https://billing.stg.catalisa.app/billing/api/v1/invoices/${invoiceId}/line-items`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
data: {
type: 'invoice-line-items',
attributes: {
chargeType: 'SUBSCRIPTION',
description: 'Plano Pro - Fevereiro 2024',
quantity: 5,
unitPrice: 299.90,
periodStart: '2024-02-01T00:00:00Z',
periodEnd: '2024-02-29T23:59:59Z',
},
},
}),
});
const { data } = await response.json();
console.log(`Novo total: R$ ${data.attributes.total}`);
Response (200 OK)
Retorna a fatura atualizada com o novo item.
{
"data": {
"type": "invoices",
"id": "550e8400-e29b-41d4-a716-446655440050",
"attributes": {
"invoiceNumber": "INV-2024-0001",
"status": "DRAFT",
"subtotal": 1499.50,
"taxAmount": 0,
"discountAmount": 0,
"total": 1499.50,
"amountDue": 1499.50,
"lineItems": [
{
"chargeType": "SUBSCRIPTION",
"description": "Plano Pro - Fevereiro 2024",
"quantity": 5,
"unitPrice": 299.90,
"amount": 1499.50,
"periodStart": "2024-02-01T00:00:00Z",
"periodEnd": "2024-02-29T23:59:59Z"
}
],
"updatedAt": "2024-02-28T10:30:00Z"
}
}
}
Finalizar Fatura
POST /api/v1/invoices/:id/finalize
Finaliza uma fatura, tornando-a pronta para pagamento. Após finalizada, a fatura não pode mais ser editada.
- cURL
- JavaScript
curl -X POST 'https://billing.stg.catalisa.app/billing/api/v1/invoices/550e8400-e29b-41d4-a716-446655440050/finalize' \
-H 'Authorization: Bearer SEU_TOKEN'
const invoiceId = '550e8400-e29b-41d4-a716-446655440050';
const response = await fetch(`https://billing.stg.catalisa.app/billing/api/v1/invoices/${invoiceId}/finalize`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
},
});
const { data } = await response.json();
console.log(`Status: ${data.attributes.status}`); // PENDING
console.log(`Finalizada em: ${data.attributes.finalizedAt}`);
Response (200 OK)
{
"data": {
"type": "invoices",
"id": "550e8400-e29b-41d4-a716-446655440050",
"attributes": {
"invoiceNumber": "INV-2024-0001",
"status": "PENDING",
"total": 1499.50,
"amountDue": 1499.50,
"dueDate": "2024-03-10T23:59:59Z",
"finalizedAt": "2024-02-28T11:00:00Z",
"updatedAt": "2024-02-28T11:00:00Z"
}
}
}
Anular Fatura
POST /api/v1/invoices/:id/void
Anula uma fatura finalizada. Use quando a fatura foi emitida incorretamente.
- cURL
- JavaScript
curl -X POST 'https://billing.stg.catalisa.app/billing/api/v1/invoices/550e8400-e29b-41d4-a716-446655440050/void' \
-H 'Authorization: Bearer SEU_TOKEN'
const invoiceId = '550e8400-e29b-41d4-a716-446655440050';
const response = await fetch(`https://billing.stg.catalisa.app/billing/api/v1/invoices/${invoiceId}/void`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
},
});
const { data } = await response.json();
console.log(`Status: ${data.attributes.status}`); // VOID
console.log(`Anulada em: ${data.attributes.voidedAt}`);
Response (200 OK)
{
"data": {
"type": "invoices",
"id": "550e8400-e29b-41d4-a716-446655440050",
"attributes": {
"invoiceNumber": "INV-2024-0001",
"status": "VOID",
"total": 1499.50,
"amountDue": 0,
"voidedAt": "2024-02-28T12:00:00Z",
"updatedAt": "2024-02-28T12:00:00Z"
}
}
}
Listar Faturas
GET /api/v1/invoices
Lista todas as faturas com suporte a paginação e filtros.
Query Parameters
| Parâmetro | Tipo | Descrição |
|---|---|---|
page[number] | integer | Número da página |
page[size] | integer | Itens por página |
filter[billingAccountId] | UUID | Filtrar por conta |
filter[status] | enum | Filtrar por status |
filter[startDate] | datetime | Data inicial |
filter[endDate] | datetime | Data final |
- cURL
- JavaScript
curl 'https://billing.stg.catalisa.app/billing/api/v1/invoices?filter[status]=PENDING&filter[billingAccountId]=550e8400-e29b-41d4-a716-446655440010' \
-H 'Authorization: Bearer SEU_TOKEN'
const params = new URLSearchParams({
'filter[status]': 'PENDING',
'filter[billingAccountId]': '550e8400-e29b-41d4-a716-446655440010',
});
const response = await fetch(`https://billing.stg.catalisa.app/billing/api/v1/invoices?${params}`, {
headers: {
'Authorization': `Bearer ${token}`,
},
});
const { data, meta } = await response.json();
console.log(`Total de faturas pendentes: ${meta.totalItems}`);
Response (200 OK)
{
"data": [
{
"type": "invoices",
"id": "550e8400-e29b-41d4-a716-446655440050",
"attributes": {
"invoiceNumber": "INV-2024-0001",
"status": "PENDING",
"currency": "BRL",
"total": 1499.50,
"amountDue": 1499.50,
"dueDate": "2024-03-10T23:59:59Z"
}
}
],
"meta": {
"totalItems": 1,
"totalPages": 1,
"currentPage": 1,
"itemsPerPage": 20
}
}
Registrar Pagamento
POST /api/v1/payments
Registra um pagamento recebido.
Atributos
| Campo | Tipo | Obrigatório | Descrição |
|---|---|---|---|
billingAccountId | string | Sim | ID da conta de faturamento |
invoiceId | string | Não | ID da fatura (se aplicável) |
amount | number | Sim | Valor do pagamento |
paymentMethod | string | Não | Método de pagamento |
externalRef | string | Não | Referência externa |
metadata | object | Não | Dados adicionais |
- cURL
- JavaScript
curl -X POST 'https://billing.stg.catalisa.app/billing/api/v1/payments' \
-H 'Authorization: Bearer SEU_TOKEN' \
-H 'Content-Type: application/json' \
-d '{
"data": {
"type": "payments",
"attributes": {
"billingAccountId": "550e8400-e29b-41d4-a716-446655440010",
"invoiceId": "550e8400-e29b-41d4-a716-446655440050",
"amount": 1499.50,
"paymentMethod": "PIX",
"externalRef": "E12345678901234567890123456789012"
}
}
}'
const response = await fetch('https://billing.stg.catalisa.app/billing/api/v1/payments', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
data: {
type: 'payments',
attributes: {
billingAccountId: '550e8400-e29b-41d4-a716-446655440010',
invoiceId: '550e8400-e29b-41d4-a716-446655440050',
amount: 1499.50,
paymentMethod: 'PIX',
externalRef: 'E12345678901234567890123456789012',
},
},
}),
});
const { data } = await response.json();
console.log(`Pagamento registrado: ${data.id}`);
console.log(`Status: ${data.attributes.status}`);
Response (201 Created)
{
"data": {
"type": "payments",
"id": "550e8400-e29b-41d4-a716-446655440060",
"links": {
"self": "/api/v1/payments/550e8400-e29b-41d4-a716-446655440060"
},
"attributes": {
"billingAccountId": "550e8400-e29b-41d4-a716-446655440010",
"invoiceId": "550e8400-e29b-41d4-a716-446655440050",
"status": "COMPLETED",
"amount": 1499.50,
"currency": "BRL",
"paymentMethod": "PIX",
"externalRef": "E12345678901234567890123456789012",
"processedAt": "2024-02-28T14:00:00Z",
"createdAt": "2024-02-28T14:00:00Z",
"updatedAt": "2024-02-28T14:00:00Z"
}
},
"links": {
"self": "/api/v1/payments/550e8400-e29b-41d4-a716-446655440060"
}
}
Processar Reembolso
POST /api/v1/payments/:id/refund
Processa um reembolso total ou parcial de um pagamento.
Query Parameters
| Parâmetro | Tipo | Descrição |
|---|---|---|
amount | number | Valor do reembolso (omitir para total) |
- cURL
- JavaScript
# Reembolso total
curl -X POST 'https://billing.stg.catalisa.app/billing/api/v1/payments/550e8400-e29b-41d4-a716-446655440060/refund' \
-H 'Authorization: Bearer SEU_TOKEN'
# Reembolso parcial
curl -X POST 'https://billing.stg.catalisa.app/billing/api/v1/payments/550e8400-e29b-41d4-a716-446655440060/refund?amount=500.00' \
-H 'Authorization: Bearer SEU_TOKEN'
const paymentId = '550e8400-e29b-41d4-a716-446655440060';
// Reembolso total
const response = await fetch(`https://billing.stg.catalisa.app/billing/api/v1/payments/${paymentId}/refund`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
},
});
// Reembolso parcial
const partialResponse = await fetch(`https://billing.stg.catalisa.app/billing/api/v1/payments/${paymentId}/refund?amount=500.00`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
},
});
const { data } = await response.json();
console.log(`Status: ${data.attributes.status}`); // REFUNDED
console.log(`Valor reembolsado: R$ ${data.attributes.refundedAmount}`);
Response (200 OK)
{
"data": {
"type": "payments",
"id": "550e8400-e29b-41d4-a716-446655440060",
"attributes": {
"billingAccountId": "550e8400-e29b-41d4-a716-446655440010",
"invoiceId": "550e8400-e29b-41d4-a716-446655440050",
"status": "REFUNDED",
"amount": 1499.50,
"currency": "BRL",
"paymentMethod": "PIX",
"refundedAmount": 1499.50,
"refundedAt": "2024-02-28T15:00:00Z",
"updatedAt": "2024-02-28T15:00:00Z"
}
}
}
Listar Pagamentos
GET /api/v1/payments
Lista todos os pagamentos com suporte a paginação e filtros.
Query Parameters
| Parâmetro | Tipo | Descrição |
|---|---|---|
page[number] | integer | Número da página |
page[size] | integer | Itens por página |
filter[billingAccountId] | UUID | Filtrar por conta |
filter[invoiceId] | UUID | Filtrar por fatura |
filter[status] | enum | Filtrar por status |
- cURL
- JavaScript
curl 'https://billing.stg.catalisa.app/billing/api/v1/payments?filter[status]=COMPLETED&page[size]=10' \
-H 'Authorization: Bearer SEU_TOKEN'
const params = new URLSearchParams({
'filter[status]': 'COMPLETED',
'page[size]': '10',
});
const response = await fetch(`https://billing.stg.catalisa.app/billing/api/v1/payments?${params}`, {
headers: {
'Authorization': `Bearer ${token}`,
},
});
const { data, meta } = await response.json();
console.log(`Total de pagamentos: ${meta.totalItems}`);
Response (200 OK)
{
"data": [
{
"type": "payments",
"id": "550e8400-e29b-41d4-a716-446655440060",
"attributes": {
"billingAccountId": "550e8400-e29b-41d4-a716-446655440010",
"invoiceId": "550e8400-e29b-41d4-a716-446655440050",
"status": "COMPLETED",
"amount": 1499.50,
"currency": "BRL",
"paymentMethod": "PIX",
"processedAt": "2024-02-28T14:00:00Z"
}
}
],
"meta": {
"totalItems": 25,
"totalPages": 3,
"currentPage": 1,
"itemsPerPage": 10
}
}
Ciclo de Vida da Fatura
Estados da Fatura
DRAFT (Rascunho)
- Fatura pode ser editada
- Permite adicionar/remover linhas de cobrança
- Não está disponível para pagamento
- Transições:
- →
PENDING: Chamada definalize()(finalizar) - →
CANCELED: Chamada decancel()(cancelar antes de finalizar)
- →
PENDING (Pendente)
- Fatura finalizada e aguardando pagamento
- Não pode mais ser editada
- Disponível para pagamento
- Transições:
- →
PAID: Pagamento completo recebido - →
VOID: Chamada devoid()(anular após finalizar) - →
OVERDUE: Data de vencimento passou sem pagamento
- →
PAID (Paga)
- Fatura paga integralmente
- Estado final
- Não permite mais transições
OVERDUE (Vencida)
- Vencimento passou sem pagamento completo
- Ainda pode receber pagamentos
- Transições:
- →
PAID: Quando receber pagamento completo
- →
CANCELED (Cancelada)
- Fatura cancelada antes de ser finalizada
- Estado final
- Não permite mais transições
VOID (Anulada)
- Fatura anulada após ter sido finalizada
- Usado quando fatura foi emitida incorretamente
- Estado final
- Não permite mais transições
Erros Comuns
Faturas
| Código | Erro | Descrição |
|---|---|---|
| 400 | VALIDATION | Dados inválidos |
| 404 | NOT_FOUND | Fatura ou conta não encontrada |
| 409 | CONFLICT | Fatura não está em DRAFT (edição) |
| 409 | CONFLICT | Fatura não está PENDING (anulação) |
| 409 | CONFLICT | Fatura já foi paga ou anulada |
Pagamentos
| Código | Erro | Descrição |
|---|---|---|
| 400 | VALIDATION | Dados inválidos |
| 404 | NOT_FOUND | Pagamento, fatura ou conta não encontrada |
| 409 | CONFLICT | Pagamento já foi reembolsado |
| 409 | CONFLICT | Valor de reembolso excede o disponível |
| 409 | CONFLICT | Pagamento não está COMPLETED (reembolso) |