Skip to content

Autenticação

Obtenha um token JWT para acessar a API DiviPay.

POST /api/auth

Autentica sua aplicação e retorna um token de acesso válido por 24 horas.

Endpoint

POST https://api.divipay.com.br/api/auth

Headers

HeaderValorObrigatório
Content-Typeapplication/jsonSim

Body Parameters

CampoTipoDescriçãoObrigatório
client_idstringID do cliente fornecido no painelSim
client_secretstringSecret do cliente fornecido no painelSim

Exemplo de Requisição

bash
curl -X POST https://api.divipay.com.br/api/auth \
  -H "Content-Type: application/json" \
  -d '{
    "client_id": "seu_client_id",
    "client_secret": "seu_client_secret"
  }'
javascript
const response = await fetch('https://api.divipay.com.br/api/auth', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    client_id: 'seu_client_id',
    client_secret: 'seu_client_secret'
  })
});

const data = await response.json();
console.log(data.token);
python
import requests

response = requests.post(
    'https://api.divipay.com.br/api/auth',
    json={
        'client_id': 'seu_client_id',
        'client_secret': 'seu_client_secret'
    }
)

data = response.json()
print(data['token'])
php
<?php
$ch = curl_init('https://api.divipay.com.br/api/auth');

curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
    'client_id' => 'seu_client_id',
    'client_secret' => 'seu_client_secret'
]));

$response = curl_exec($ch);
$data = json_decode($response, true);

echo $data['token'];
?>

Resposta de Sucesso

Status: 201 Created

json
{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c",
  "expireIn": 86400,
  "expireOn": "2024-11-05T15:00:00.000Z",
  "type": "Bearer"
}
CampoTipoDescrição
tokenstringToken JWT para autenticação
expireInnumberTempo de expiração em segundos (24h = 86400s)
expireOnstringData/hora de expiração no formato ISO 8601
typestringTipo do token (sempre "Bearer")

Respostas de Erro

401 Unauthorized

Credenciais inválidas ou API não habilitada para a conta.

json
{
  "statusCode": 401,
  "message": "Unauthorized",
  "error": "Invalid credentials"
}

403 Forbidden

Conta sem permissão para acessar a API.

json
{
  "statusCode": 403,
  "message": "Forbidden",
  "error": "API access not enabled for this account"
}

Usando o Token

Após obter o token, inclua-o no header Authorization de todas as requisições:

bash
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

Exemplo

bash
curl -X GET https://api.divipay.com.br/api/charge/abc123 \
  -H "Authorization: Bearer SEU_TOKEN_AQUI"

Renovação do Token

O token expira em 24 horas. Implemente lógica para renovar automaticamente:

javascript
class DiviPayClient {
  constructor(clientId, clientSecret) {
    this.clientId = clientId;
    this.clientSecret = clientSecret;
    this.token = null;
    this.tokenExpiry = null;
  }

  async authenticate() {
    const response = await fetch('https://api.divipay.com.br/api/auth', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        client_id: this.clientId,
        client_secret: this.clientSecret
      })
    });

    const data = await response.json();
    this.token = data.token;
    this.tokenExpiry = new Date(data.expireOn);
  }

  async getToken() {
    // Renova se não existe ou está próximo de expirar (5 min antes)
    if (!this.token || new Date() >= new Date(this.tokenExpiry - 5 * 60 * 1000)) {
      await this.authenticate();
    }
    return this.token;
  }

  async request(endpoint, options = {}) {
    const token = await this.getToken();
    
    return fetch(`https://api.divipay.com.br${endpoint}`, {
      ...options,
      headers: {
        ...options.headers,
        'Authorization': `Bearer ${token}`
      }
    });
  }
}

// Uso
const client = new DiviPayClient('client_id', 'client_secret');
const response = await client.request('/api/charge/pix', {
  method: 'POST',
  body: JSON.stringify({ /* ... */ })
});

Segurança

IMPORTANTE

  • Nunca exponha suas credenciais em código frontend
  • Sempre use HTTPS em produção
  • Armazene credenciais em variáveis de ambiente
  • Rotacione suas credenciais periodicamente
  • Monitore o uso da API para detectar acessos não autorizados

Boas Práticas

javascript
// ✅ BOM - Credenciais em variáveis de ambiente
const CLIENT_ID = process.env.DIVIPAY_CLIENT_ID;
const CLIENT_SECRET = process.env.DIVIPAY_CLIENT_SECRET;

// ❌ RUIM - Credenciais hardcoded
const CLIENT_ID = 'abc123';
const CLIENT_SECRET = 'xyz789';

Documentação da API DiviPay