Ambientes
A DiviPay oferece dois ambientes: Sandbox para testes e Produção para operações reais.
Sandbox (Testes)
Ambiente isolado para desenvolvimento e testes sem movimentação real de dinheiro.
URL Base
https://pay-sandbox.hge.appCaracterísticas
- ✅ Mesma API da produção
- ✅ Sem custos ou taxas
- ✅ Pagamentos simulados
- ✅ Dados de teste fornecidos
- ✅ Webhooks funcionais
- ✅ Ideal para desenvolvimento
Credenciais
Obtenha credenciais de sandbox no painel de desenvolvimento.
Exemplo
javascript
const SANDBOX_URL = 'https://pay-sandbox.hge.app';
const auth = new DiviPayAuth(
process.env.SANDBOX_CLIENT_ID,
process.env.SANDBOX_CLIENT_SECRET,
SANDBOX_URL
);Produção
Ambiente real com movimentação financeira efetiva.
URL Base
https://api.divipay.com.brCaracterísticas
- 💰 Transações reais
- 💳 Taxas aplicadas
- 🔒 Alta disponibilidade
- 📊 Relatórios completos
- 🔐 Segurança reforçada
Credenciais
Obtenha credenciais de produção no painel principal após validação da conta.
Exemplo
javascript
const PRODUCTION_URL = 'https://api.divipay.com.br';
const auth = new DiviPayAuth(
process.env.PRODUCTION_CLIENT_ID,
process.env.PRODUCTION_CLIENT_SECRET,
PRODUCTION_URL
);Configuração por Ambiente
Variáveis de Ambiente
bash
# .env.development
DIVIPAY_API_URL=https://pay-sandbox.hge.app
DIVIPAY_CLIENT_ID=sandbox_client_id
DIVIPAY_CLIENT_SECRET=sandbox_client_secret
# .env.production
DIVIPAY_API_URL=https://api.divipay.com.br
DIVIPAY_CLIENT_ID=production_client_id
DIVIPAY_CLIENT_SECRET=production_client_secretNode.js
javascript
const config = {
development: {
apiUrl: 'https://pay-sandbox.hge.app',
clientId: process.env.SANDBOX_CLIENT_ID,
clientSecret: process.env.SANDBOX_CLIENT_SECRET
},
production: {
apiUrl: 'https://api.divipay.com.br',
clientId: process.env.PRODUCTION_CLIENT_ID,
clientSecret: process.env.PRODUCTION_CLIENT_SECRET
}
};
const env = process.env.NODE_ENV || 'development';
const currentConfig = config[env];
const auth = new DiviPayAuth(
currentConfig.clientId,
currentConfig.clientSecret,
currentConfig.apiUrl
);PHP
php
<?php
$config = [
'development' => [
'apiUrl' => 'https://pay-sandbox.hge.app',
'clientId' => getenv('SANDBOX_CLIENT_ID'),
'clientSecret' => getenv('SANDBOX_CLIENT_SECRET')
],
'production' => [
'apiUrl' => 'https://api.divipay.com.br',
'clientId' => getenv('PRODUCTION_CLIENT_ID'),
'clientSecret' => getenv('PRODUCTION_CLIENT_SECRET')
]
];
$env = getenv('APP_ENV') ?: 'development';
$currentConfig = $config[$env];
$auth = new DiviPayAuth(
$currentConfig['clientId'],
$currentConfig['clientSecret'],
$currentConfig['apiUrl']
);
?>Python
python
import os
config = {
'development': {
'api_url': 'https://pay-sandbox.hge.app',
'client_id': os.getenv('SANDBOX_CLIENT_ID'),
'client_secret': os.getenv('SANDBOX_CLIENT_SECRET')
},
'production': {
'api_url': 'https://api.divipay.com.br',
'client_id': os.getenv('PRODUCTION_CLIENT_ID'),
'client_secret': os.getenv('PRODUCTION_CLIENT_SECRET')
}
}
env = os.getenv('APP_ENV', 'development')
current_config = config[env]
auth = DiviPayAuth(
current_config['client_id'],
current_config['client_secret'],
current_config['api_url']
)Testando no Sandbox
Simulando Pagamentos Pix
No sandbox, pagamentos Pix são aprovados automaticamente após alguns segundos:
javascript
// 1. Criar cobrança
const charge = await auth.request('/api/charge/pix', 'POST', {
amount: 100.00,
// ... outros campos
});
console.log('Cobrança criada:', charge.id);
// 2. Aguardar webhook (simulado automaticamente)
// O webhook será enviado em ~10 segundosSimulando Pagamentos com Cartão
Use cartões de teste fornecidos:
javascript
// Cartão aprovado
{
cardNumber: '4111111111111111',
holder: 'TESTE APROVADO',
expirationDate: '12/2025',
securityCode: '123'
}
// Cartão recusado
{
cardNumber: '4000000000000002',
holder: 'TESTE RECUSADO',
expirationDate: '12/2025',
securityCode: '123'
}Testando Webhooks
Configure ngrok para receber webhooks localmente:
bash
# Instalar ngrok
npm install -g ngrok
# Expor porta local
ngrok http 3000
# Usar URL gerada
https://abc123.ngrok.io/webhook/divipayMigração para Produção
Checklist
- [ ] Obter credenciais de produção
- [ ] Atualizar variáveis de ambiente
- [ ] Testar autenticação
- [ ] Validar webhooks em produção
- [ ] Configurar monitoramento
- [ ] Implementar logs
- [ ] Testar com valores pequenos
- [ ] Documentar processo de rollback
Exemplo de Deploy
javascript
// config.js
module.exports = {
apiUrl: process.env.DIVIPAY_API_URL,
clientId: process.env.DIVIPAY_CLIENT_ID,
clientSecret: process.env.DIVIPAY_CLIENT_SECRET,
// Validar configuração
validate() {
if (!this.apiUrl || !this.clientId || !this.clientSecret) {
throw new Error('DiviPay configuration missing');
}
// Avisar se estiver em produção
if (this.apiUrl.includes('api.divipay.com.br')) {
console.log('⚠️ Running in PRODUCTION mode');
} else {
console.log('🧪 Running in SANDBOX mode');
}
}
};
// Validar ao iniciar
config.validate();Diferenças entre Ambientes
| Recurso | Sandbox | Produção |
|---|---|---|
| Transações reais | ❌ | ✅ |
| Taxas cobradas | ❌ | ✅ |
| Pagamentos simulados | ✅ | ❌ |
| Webhooks | ✅ | ✅ |
| Rate limiting | Relaxado | Rigoroso |
| Suporte | Prioritário | |
| SLA | Sem garantia | 99.9% |
Boas Práticas
1. Nunca Misture Ambientes
javascript
// ❌ RUIM
const auth = new DiviPayAuth(
process.env.PRODUCTION_CLIENT_ID,
process.env.SANDBOX_CLIENT_SECRET, // Misturado!
'https://api.divipay.com.br'
);
// ✅ BOM
const config = getConfig(process.env.NODE_ENV);
const auth = new DiviPayAuth(
config.clientId,
config.clientSecret,
config.apiUrl
);2. Identifique o Ambiente
javascript
function getEnvironment() {
const url = process.env.DIVIPAY_API_URL;
if (url.includes('sandbox')) {
return 'sandbox';
} else if (url.includes('api.divipay.com.br')) {
return 'production';
}
throw new Error('Unknown environment');
}
console.log(`Running in ${getEnvironment()} mode`);3. Logs Diferentes por Ambiente
javascript
const logger = {
log(message, data) {
if (process.env.NODE_ENV === 'production') {
// Log estruturado em produção
console.log(JSON.stringify({
timestamp: new Date().toISOString(),
level: 'info',
message,
data
}));
} else {
// Log simples em desenvolvimento
console.log(message, data);
}
}
};4. Validação Extra em Produção
javascript
async function createCharge(data) {
// Validação extra em produção
if (process.env.NODE_ENV === 'production') {
if (data.amount > 10000) {
throw new Error('Amount too high, requires manual approval');
}
}
return await auth.request('/api/charge/pix', 'POST', data);
}Monitoramento
Healthcheck
javascript
async function checkApiHealth() {
try {
const response = await fetch(`${config.apiUrl}/health`);
return response.ok;
} catch (error) {
console.error('API health check failed:', error);
return false;
}
}
// Verificar a cada 5 minutos
setInterval(checkApiHealth, 5 * 60 * 1000);Alertas
javascript
async function createChargeWithAlert(data) {
try {
return await auth.request('/api/charge/pix', 'POST', data);
} catch (error) {
// Alertar em produção
if (process.env.NODE_ENV === 'production') {
await sendAlert('Charge creation failed', error);
}
throw error;
}
}