Consultar Cobrança
Consulta o status e detalhes de uma cobrança existente.
GET /api/charge/
Consulta uma cobrança genérica (Link de Pagamento).
Endpoint
GET https://api.divipay.com.br/api/charge/{chargeId}Headers
| Header | Valor | Obrigatório |
|---|---|---|
| Authorization | Bearer | Sim |
Path Parameters
| Parâmetro | Tipo | Descrição |
|---|---|---|
| chargeId | string | ID da cobrança |
Exemplo de Requisição
bash
curl -X GET https://api.divipay.com.br/api/charge/cob_abc123 \
-H "Authorization: Bearer SEU_TOKEN"javascript
const response = await fetch(
'https://api.divipay.com.br/api/charge/cob_abc123',
{
headers: {
'Authorization': 'Bearer SEU_TOKEN'
}
}
);
const charge = await response.json();python
import requests
response = requests.get(
'https://api.divipay.com.br/api/charge/cob_abc123',
headers={
'Authorization': 'Bearer SEU_TOKEN'
}
)
charge = response.json()Resposta de Sucesso
Status: 200 OK
json
{
"id": "cob_abc123",
"status": "PAID",
"amount": 100.00,
"description": "Pedido #123",
"referenceId": "pedido-123",
"chargeType": "INVOICE",
"createdAt": "2024-11-04T15:00:00.000Z",
"paidAt": "2024-11-04T15:30:00.000Z",
"customerId": null,
"clientId": "cli_xyz789",
"devedorCpfCnpj": "12345678901",
"devedorName": "João Silva"
}GET /api/charge/{chargeId}/pix
Consulta uma cobrança Pix específica.
Endpoint
GET https://api.divipay.com.br/api/charge/{chargeId}/pixExemplo de Requisição
bash
curl -X GET https://api.divipay.com.br/api/charge/cob_abc123/pix \
-H "Authorization: Bearer SEU_TOKEN"Resposta
json
{
"id": "cob_abc123",
"status": "PAID",
"amount": 100.00,
"description": "Pagamento Pix",
"referenceId": "pedido-123",
"qrCode": "00020126580014br.gov.bcb.pix...",
"qrCodeImage": "data:image/png;base64,iVBORw0KG...",
"pixCopyPaste": "00020126580014br.gov.bcb.pix...",
"expiresAt": "2024-11-04T16:00:00.000Z",
"createdAt": "2024-11-04T15:00:00.000Z",
"paidAt": "2024-11-04T15:30:00.000Z"
}GET /api/charge/{chargeId}/credit-card
Consulta uma cobrança de Cartão de Crédito.
Endpoint
GET https://api.divipay.com.br/api/charge/{chargeId}/credit-cardExemplo de Requisição
bash
curl -X GET https://api.divipay.com.br/api/charge/cc_abc123/credit-card \
-H "Authorization: Bearer SEU_TOKEN"Resposta
json
{
"id": "cc_abc123",
"status": "PAID",
"amount": 200.00,
"description": "Compra Online",
"referenceId": "order-789",
"chargeType": "CREDIT_CARD",
"createdAt": "2024-11-04T15:00:00.000Z",
"paidAt": "2024-11-04T15:30:00.000Z",
"customerId": null,
"clientId": "cli_xyz789",
"devedorCpfCnpj": "12345678901",
"devedorName": "João Silva"
}Status da Cobrança
| Status | Descrição |
|---|---|
| PENDING | Aguardando pagamento |
| PAID | Pagamento confirmado |
| CANCELED | Cobrança cancelada |
| EXPIRED | Cobrança expirada |
| REFUNDED | Pagamento estornado |
Exemplo de Uso
Verificar Status
javascript
async function checkChargeStatus(chargeId) {
try {
const response = await fetch(
`https://api.divipay.com.br/api/charge/${chargeId}`,
{
headers: {
'Authorization': `Bearer ${token}`
}
}
);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const charge = await response.json();
switch (charge.status) {
case 'PENDING':
console.log('⏳ Aguardando pagamento');
break;
case 'PAID':
console.log('✅ Pagamento confirmado');
console.log('Pago em:', charge.paidAt);
break;
case 'CANCELED':
console.log('❌ Cobrança cancelada');
break;
case 'EXPIRED':
console.log('⏰ Cobrança expirada');
break;
case 'REFUNDED':
console.log('↩️ Pagamento estornado');
break;
default:
console.log('❓ Status desconhecido:', charge.status);
}
return charge;
} catch (error) {
console.error('Erro ao consultar cobrança:', error);
throw error;
}
}
// Uso
const charge = await checkChargeStatus('cob_abc123');Polling de Status
javascript
async function waitForPayment(chargeId, maxAttempts = 60) {
for (let i = 0; i < maxAttempts; i++) {
const charge = await checkChargeStatus(chargeId);
if (charge.status === 'PAID') {
console.log('✅ Pagamento confirmado!');
return charge;
}
if (charge.status === 'CANCELED' || charge.status === 'EXPIRED') {
throw new Error(`Cobrança ${charge.status.toLowerCase()}`);
}
console.log(`Tentativa ${i + 1}/${maxAttempts} - Status: ${charge.status}`);
// Aguardar 5 segundos antes de tentar novamente
await new Promise(resolve => setTimeout(resolve, 5000));
}
throw new Error('Timeout aguardando pagamento');
}
// Uso
try {
const charge = await waitForPayment('cob_abc123');
console.log('Pagamento recebido:', charge);
} catch (error) {
console.error('Erro:', error.message);
}ATENÇÃO
Evite polling excessivo. Use webhooks para receber notificações em tempo real.
Consultar Múltiplas Cobranças
javascript
async function getCharges(chargeIds) {
const promises = chargeIds.map(id =>
fetch(`https://api.divipay.com.br/api/charge/${id}`, {
headers: { 'Authorization': `Bearer ${token}` }
}).then(r => r.json())
);
const charges = await Promise.all(promises);
return charges;
}
// Uso
const charges = await getCharges([
'cob_abc123',
'cob_def456',
'cob_ghi789'
]);
charges.forEach(charge => {
console.log(`${charge.id}: ${charge.status}`);
});Integração com Banco de Dados
javascript
async function syncChargeStatus(chargeId) {
try {
// Consultar API
const charge = await checkChargeStatus(chargeId);
// Atualizar banco de dados
await db.charges.update({
where: { id: chargeId },
data: {
status: charge.status,
paidAt: charge.paidAt,
updatedAt: new Date()
}
});
// Se foi pago, processar pedido
if (charge.status === 'PAID') {
await processOrder(charge.referenceId);
}
return charge;
} catch (error) {
console.error('Erro ao sincronizar:', error);
throw error;
}
}Exibir Status para Cliente
javascript
function getStatusDisplay(status) {
const statusMap = {
'PENDING': {
icon: '⏳',
text: 'Aguardando Pagamento',
color: 'orange',
description: 'Seu pagamento está sendo processado'
},
'PAID': {
icon: '✅',
text: 'Pagamento Confirmado',
color: 'green',
description: 'Seu pagamento foi aprovado com sucesso'
},
'CANCELED': {
icon: '❌',
text: 'Cancelado',
color: 'red',
description: 'Esta cobrança foi cancelada'
},
'EXPIRED': {
icon: '⏰',
text: 'Expirado',
color: 'gray',
description: 'O prazo para pagamento expirou'
},
'REFUNDED': {
icon: '↩️',
text: 'Estornado',
color: 'blue',
description: 'O pagamento foi estornado'
}
};
return statusMap[status] || {
icon: '❓',
text: 'Status Desconhecido',
color: 'gray',
description: ''
};
}
// Uso em React
function ChargeStatus({ chargeId }) {
const [charge, setCharge] = useState(null);
useEffect(() => {
checkChargeStatus(chargeId).then(setCharge);
}, [chargeId]);
if (!charge) return <div>Carregando...</div>;
const status = getStatusDisplay(charge.status);
return (
<div style={{ color: status.color }}>
<h2>{status.icon} {status.text}</h2>
<p>{status.description}</p>
{charge.paidAt && (
<p>Pago em: {new Date(charge.paidAt).toLocaleString()}</p>
)}
</div>
);
}Respostas de Erro
404 Not Found
Cobrança não encontrada.
json
{
"statusCode": 404,
"message": "Charge not found",
"error": "Not Found"
}403 Forbidden
Sem permissão para acessar a cobrança.
json
{
"statusCode": 403,
"message": "Forbidden"
}Boas Práticas
1. Cache de Consultas
javascript
const chargeCache = new Map();
async function getCachedCharge(chargeId, ttl = 60000) {
const cached = chargeCache.get(chargeId);
if (cached && Date.now() - cached.timestamp < ttl) {
return cached.data;
}
const charge = await checkChargeStatus(chargeId);
chargeCache.set(chargeId, {
data: charge,
timestamp: Date.now()
});
return charge;
}2. Retry com Backoff
javascript
async function checkChargeWithRetry(chargeId, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await checkChargeStatus(chargeId);
} catch (error) {
if (i === maxRetries - 1) throw error;
const delay = Math.pow(2, i) * 1000;
await new Promise(resolve => setTimeout(resolve, delay));
}
}
}3. Use Webhooks
Prefira webhooks ao invés de polling:
javascript
// ❌ RUIM - Polling constante
setInterval(() => {
checkChargeStatus(chargeId);
}, 5000);
// ✅ BOM - Webhook
app.post('/webhook', (req, res) => {
const event = req.body;
if (event.event === 'charge.paid') {
processPayment(event.chargeId);
}
res.status(200).send('OK');
});