Criar Cobrança Pix
Cria uma cobrança Pix com QR Code para pagamento instantâneo.
POST /api/charge/pix
Endpoint
POST https://api.divipay.com.br/api/charge/pixHeaders
| Header | Valor | Obrigatório |
|---|---|---|
| Authorization | Bearer | Sim |
| Content-Type | application/json | Sim |
Body Parameters
| Campo | Tipo | Descrição | Obrigatório |
|---|---|---|---|
| amount | number | Valor da cobrança em reais | Sim |
| description | string | Descrição (máx. 25 caracteres) | Sim |
| referenceId | string | ID de referência do seu sistema | Sim |
| callbackUrl | string | URL para receber webhook | Sim |
| expirationSeconds | number | Tempo de expiração em segundos | Sim |
| customerId | string | ID da subconta (opcional) | Não |
| fee | string | Taxa fixa a ser cobrada | Não |
| client | object | Dados do cliente | Sim |
| itens | array | Lista de itens da cobrança | Sim |
Objeto Client
| Campo | Tipo | Descrição | Obrigatório |
|---|---|---|---|
| name | string | Nome do cliente (máx. 255 caracteres) | Sim |
| document | string | CPF ou CNPJ (somente números) | Sim |
| array/string | Email do cliente | Sim | |
| phone | string | Telefone com DDD (somente números) | Sim |
| ip | string | IP do cliente | Não |
Objeto Item
| Campo | Tipo | Descrição | Obrigatório |
|---|---|---|---|
| name | string | Nome do item | Sim |
| quantity | number | Quantidade | Sim |
| unitPrice | number | Valor unitário | Sim |
| feePercent | number | Percentual de taxa para split | Sim |
Exemplo de Requisição
bash
curl -X POST https://api.divipay.com.br/api/charge/pix \
-H "Authorization: Bearer SEU_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"amount": 100.00,
"description": "Pagamento Pedido #123",
"referenceId": "pedido-123",
"callbackUrl": "https://seusite.com/webhook",
"expirationSeconds": 3600,
"client": {
"name": "João Silva",
"document": "12345678901",
"email": "joao@email.com",
"phone": "11999999999",
"ip": "192.168.1.1"
},
"itens": [
{
"name": "Produto A",
"quantity": 2,
"unitPrice": 50.00,
"feePercent": 0
}
]
}'javascript
const response = await fetch('https://api.divipay.com.br/api/charge/pix', {
method: 'POST',
headers: {
'Authorization': 'Bearer SEU_TOKEN',
'Content-Type': 'application/json'
},
body: JSON.stringify({
amount: 100.00,
description: 'Pagamento Pedido #123',
referenceId: 'pedido-123',
callbackUrl: 'https://seusite.com/webhook',
expirationSeconds: 3600,
client: {
name: 'João Silva',
document: '12345678901',
email: 'joao@email.com',
phone: '11999999999',
ip: '192.168.1.1'
},
itens: [
{
name: 'Produto A',
quantity: 2,
unitPrice: 50.00,
feePercent: 0
}
]
})
});
const data = await response.json();python
import requests
response = requests.post(
'https://api.divipay.com.br/api/charge/pix',
headers={
'Authorization': 'Bearer SEU_TOKEN',
'Content-Type': 'application/json'
},
json={
'amount': 100.00,
'description': 'Pagamento Pedido #123',
'referenceId': 'pedido-123',
'callbackUrl': 'https://seusite.com/webhook',
'expirationSeconds': 3600,
'client': {
'name': 'João Silva',
'document': '12345678901',
'email': 'joao@email.com',
'phone': '11999999999',
'ip': '192.168.1.1'
},
'itens': [
{
'name': 'Produto A',
'quantity': 2,
'unitPrice': 50.00,
'feePercent': 0
}
]
}
)
data = response.json()Resposta de Sucesso
Status: 201 Created
json
{
"id": "cob_abc123xyz789",
"status": "PENDING",
"amount": 100.00,
"description": "Pagamento Pedido #123",
"referenceId": "pedido-123",
"qrCode": "00020126580014br.gov.bcb.pix0136123e4567-e89b-12d3-a456-42661417400052040000530398654041.005802BR5913DIVIPAY LTDA6009SAO PAULO62070503***63041D3D",
"qrCodeImage": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...",
"pixCopyPaste": "00020126580014br.gov.bcb.pix0136123e4567...",
"expiresAt": "2024-11-04T16:00:00.000Z",
"createdAt": "2024-11-04T15:00:00.000Z"
}Exibindo o QR Code
Opção 1: Imagem Base64
html
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA..." alt="QR Code Pix" />Opção 2: Código Pix Copia e Cola
html
<div>
<p>Ou copie o código Pix:</p>
<input
type="text"
value="00020126580014br.gov.bcb.pix..."
readonly
onclick="this.select()"
/>
<button onclick="copyToClipboard()">Copiar</button>
</div>
<script>
function copyToClipboard() {
const input = document.querySelector('input');
input.select();
document.execCommand('copy');
alert('Código Pix copiado!');
}
</script>Split de Pagamento
Para dividir o pagamento com uma subconta, use o campo customerId e configure a taxa:
json
{
"customerId": "sub_abc123",
"fee": "5.00",
"amount": 100.00,
// ... outros campos
}Neste exemplo:
- R$ 5,00 ficam na conta principal
- R$ 95,00 vão para a subconta
SPLIT INVERSO
Use valor negativo no fee para inverter o split. Exemplo: "fee": "-5.00" envia R$ 5,00 para a conta principal e R$ 95,00 para a subconta.
Webhook
Quando o pagamento for confirmado, você receberá:
json
{
"event": "charge.paid",
"chargeId": "cob_abc123xyz789",
"referenceId": "pedido-123",
"amount": 100.00,
"paidAt": "2024-11-04T15:30:00.000Z",
"status": "PAID",
"customerId": null
}Respostas de Erro
403 Forbidden
Token inválido ou expirado.
json
{
"statusCode": 403,
"message": "Forbidden"
}400 Bad Request
Dados inválidos na requisição.
json
{
"statusCode": 400,
"message": "Validation failed",
"errors": [
"amount must be a positive number",
"client.document must be a valid CPF or CNPJ"
]
}Exemplo Completo
javascript
async function createPixCharge(orderId, amount, customer) {
try {
const response = await fetch('https://api.divipay.com.br/api/charge/pix', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
amount,
description: `Pedido #${orderId}`,
referenceId: orderId,
callbackUrl: `${process.env.BASE_URL}/webhook/divipay`,
expirationSeconds: 3600, // 1 hora
client: {
name: customer.name,
document: customer.cpf,
email: customer.email,
phone: customer.phone,
ip: customer.ip
},
itens: customer.cart.map(item => ({
name: item.name,
quantity: item.quantity,
unitPrice: item.price,
feePercent: 0
}))
})
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const charge = await response.json();
return {
chargeId: charge.id,
qrCode: charge.qrCodeImage,
pixCode: charge.pixCopyPaste,
expiresAt: charge.expiresAt
};
} catch (error) {
console.error('Erro ao criar cobrança:', error);
throw error;
}
}