Medidores de Uso
Gerenciamento de medidores (usage meters) para cobrança baseada em consumo.
Endpoints
| Método | Endpoint | Descrição | Permissão |
|---|---|---|---|
| POST | /billing/api/v1/meters | Criar medidor | BILLING_METERS_CREATE |
| GET | /billing/api/v1/meters | Listar medidores | BILLING_METERS_READ |
| GET | /billing/api/v1/meters/:id | Obter medidor | BILLING_METERS_READ |
| PATCH | /billing/api/v1/meters/:id | Atualizar medidor | BILLING_METERS_UPDATE |
| DELETE | /billing/api/v1/meters/:id | Excluir medidor | BILLING_METERS_DELETE |
Atributos
| Campo | Tipo | Descrição |
|---|---|---|
productId | string (UUID) | ID do produto de billing associado |
name | string | Nome do medidor |
eventName | string | Nome do evento a ser medido |
aggregationType | enum | Tipo de agregação |
propertyKey | string | Chave da propriedade para agregação |
isActive | boolean | Se o medidor está ativo |
createdAt | datetime | Data de criação |
updatedAt | datetime | Data da última atualização |
Tipos de Agregação
| Tipo | Descrição |
|---|---|
SUM | Soma de todas as quantidades |
MAX | Valor máximo registrado |
LAST | Último valor registrado |
AVERAGE | Média dos valores |
COUNT_DISTINCT | Contagem de valores distintos |
Criar Medidor
POST /billing/api/v1/meters
Cria um novo medidor de uso associado a um produto.
Atributos
| Campo | Tipo | Obrigatório | Descrição |
|---|---|---|---|
productId | string | Sim | ID do produto de billing |
name | string | Sim | Nome descritivo do medidor |
eventName | string | Sim | Nome do evento a ser capturado |
aggregationType | enum | Sim | Tipo de agregação |
propertyKey | string | Não | Chave para extrair valor do evento |
isActive | boolean | Não | Se está ativo (default: true) |
- cURL
- JavaScript
curl -X POST 'https://billing.stg.catalisa.app/billing/api/v1/meters' \
-H 'Authorization: Bearer SEU_TOKEN' \
-H 'Content-Type: application/json' \
-d '{
"data": {
"type": "usage-meters",
"attributes": {
"productId": "550e8400-e29b-41d4-a716-446655440001",
"name": "API Calls",
"eventName": "api.request",
"aggregationType": "SUM",
"propertyKey": "count",
"isActive": true
}
}
}'
const response = await fetch('https://billing.stg.catalisa.app/billing/api/v1/meters', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
data: {
type: 'usage-meters',
attributes: {
productId: '550e8400-e29b-41d4-a716-446655440001',
name: 'API Calls',
eventName: 'api.request',
aggregationType: 'SUM',
propertyKey: 'count',
isActive: true,
},
},
}),
});
const { data } = await response.json();
console.log(`Medidor criado: ${data.id}`);
Response (201 Created)
{
"data": {
"type": "usage-meters",
"id": "550e8400-e29b-41d4-a716-446655440010",
"links": {
"self": "/billing/api/v1/meters/550e8400-e29b-41d4-a716-446655440010"
},
"attributes": {
"productId": "550e8400-e29b-41d4-a716-446655440001",
"name": "API Calls",
"eventName": "api.request",
"aggregationType": "SUM",
"propertyKey": "count",
"isActive": true,
"createdAt": "2024-01-15T10:30:00Z",
"updatedAt": "2024-01-15T10:30:00Z"
}
}
}
Listar Medidores
GET /billing/api/v1/meters
Lista todos os medidores 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[productId] | UUID | Filtrar por produto |
filter[isActive] | boolean | Filtrar por status ativo |
- cURL
- JavaScript
curl 'https://billing.stg.catalisa.app/billing/api/v1/meters?filter[isActive]=true' \
-H 'Authorization: Bearer SEU_TOKEN'
const params = new URLSearchParams({
'filter[isActive]': 'true',
});
const response = await fetch(`https://billing.stg.catalisa.app/billing/api/v1/meters?${params}`, {
headers: {
'Authorization': `Bearer ${token}`,
},
});
const { data, meta } = await response.json();
console.log(`Total de medidores: ${meta.totalItems}`);
Atualizar Medidor
PATCH /billing/api/v1/meters/:id
Atualiza um medidor existente.
- cURL
- JavaScript
curl -X PATCH 'https://billing.stg.catalisa.app/billing/api/v1/meters/550e8400-e29b-41d4-a716-446655440010' \
-H 'Authorization: Bearer SEU_TOKEN' \
-H 'Content-Type: application/json' \
-d '{
"data": {
"type": "usage-meters",
"id": "550e8400-e29b-41d4-a716-446655440010",
"attributes": {
"name": "API Calls - Updated",
"isActive": false
}
}
}'
const meterId = '550e8400-e29b-41d4-a716-446655440010';
const response = await fetch(`https://billing.stg.catalisa.app/billing/api/v1/meters/${meterId}`, {
method: 'PATCH',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
data: {
type: 'usage-meters',
id: meterId,
attributes: {
name: 'API Calls - Updated',
isActive: false,
},
},
}),
});
const { data } = await response.json();
console.log(`Medidor atualizado: ${data.attributes.name}`);
Excluir Medidor
DELETE /billing/api/v1/meters/:id
Remove um medidor. O medidor não pode ter eventos de uso associados.
- cURL
- JavaScript
curl -X DELETE 'https://billing.stg.catalisa.app/billing/api/v1/meters/550e8400-e29b-41d4-a716-446655440010' \
-H 'Authorization: Bearer SEU_TOKEN'
const meterId = '550e8400-e29b-41d4-a716-446655440010';
const response = await fetch(`https://billing.stg.catalisa.app/billing/api/v1/meters/${meterId}`, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${token}`,
},
});
if (response.status === 204) {
console.log('Medidor excluído com sucesso');
}
Response (204 No Content)
Sem corpo de resposta.
Exemplos de Uso
Medidor de Requisições API
// Criar medidor para contar requisições
const apiCallsMeter = {
productId: 'produto-api-uuid',
name: 'API Requests',
eventName: 'api.request',
aggregationType: 'SUM',
propertyKey: 'count', // ou null para contar eventos
};
Medidor de Armazenamento
// Criar medidor para storage (último valor = uso atual)
const storageMeter = {
productId: 'produto-storage-uuid',
name: 'Storage Used',
eventName: 'storage.usage',
aggregationType: 'LAST',
propertyKey: 'bytesUsed',
};
Medidor de Usuários Ativos
// Criar medidor para contar usuários únicos
const activeUsersMeter = {
productId: 'produto-usuarios-uuid',
name: 'Active Users',
eventName: 'user.activity',
aggregationType: 'COUNT_DISTINCT',
propertyKey: 'userId',
};
Erros Comuns
| Código | Erro | Descrição |
|---|---|---|
| 400 | VALIDATION | Dados inválidos |
| 404 | NOT_FOUND | Medidor ou produto não encontrado |
| 409 | CONFLICT | Medidor tem eventos associados (delete) |