Skip to content

Autenticação

Sistema de autenticação baseado em OAuth2 com tokens JWT.

Visão Geral

A API DiviPay utiliza autenticação via Bearer Token (JWT) que expira em 24 horas.

Obtendo Credenciais

  1. Acesse o painel DiviPay
  2. Navegue até Configurações > API
  3. Clique em Gerar Credenciais
  4. Copie seu client_id e client_secret

SEGURANÇA

Nunca exponha suas credenciais em código frontend ou repositórios públicos.

Fluxo de Autenticação

mermaid
sequenceDiagram
    participant App as Sua Aplicação
    participant API as DiviPay API
    
    App->>API: POST /api/auth (client_id, client_secret)
    API->>App: Token JWT (válido por 24h)
    
    App->>API: GET /api/charge/123 (Bearer Token)
    API->>App: Dados da cobrança
    
    Note over App,API: Token expira após 24h
    
    App->>API: POST /api/auth (renovar token)
    API->>App: Novo Token JWT

Autenticando

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"
  }'

Resposta:

json
{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "expireIn": 86400,
  "expireOn": "2024-11-05T15:00:00.000Z",
  "type": "Bearer"
}

Usando o Token

Inclua o token 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"

Gerenciamento de Token

Classe Helper (Node.js)

javascript
class DiviPayAuth {
  constructor(clientId, clientSecret, apiUrl = 'https://api.divipay.com.br') {
    this.clientId = clientId;
    this.clientSecret = clientSecret;
    this.apiUrl = apiUrl;
    this.token = null;
    this.tokenExpiry = null;
  }

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

    if (!response.ok) {
      throw new Error(`Authentication failed: ${response.status}`);
    }

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

    return this.token;
  }

  async getToken() {
    // Renova se não existe ou expira em menos de 5 minutos
    const fiveMinutes = 5 * 60 * 1000;
    const now = new Date();
    
    if (!this.token || !this.tokenExpiry || 
        now >= new Date(this.tokenExpiry.getTime() - fiveMinutes)) {
      await this.authenticate();
    }

    return this.token;
  }

  async request(endpoint, options = {}) {
    const token = await this.getToken();

    const response = await fetch(`${this.apiUrl}${endpoint}`, {
      ...options,
      headers: {
        ...options.headers,
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    });

    if (!response.ok) {
      const error = await response.json();
      throw new Error(`API Error: ${error.message || response.statusText}`);
    }

    return response.json();
  }
}

// Uso
const auth = new DiviPayAuth(
  process.env.DIVIPAY_CLIENT_ID,
  process.env.DIVIPAY_CLIENT_SECRET
);

// Fazer requisições
const charge = await auth.request('/api/charge/pix', {
  method: 'POST',
  body: JSON.stringify({ /* ... */ })
});

Classe Helper (PHP)

php
<?php
class DiviPayAuth {
    private $clientId;
    private $clientSecret;
    private $apiUrl;
    private $token;
    private $tokenExpiry;

    public function __construct($clientId, $clientSecret, $apiUrl = 'https://api.divipay.com.br') {
        $this->clientId = $clientId;
        $this->clientSecret = $clientSecret;
        $this->apiUrl = $apiUrl;
    }

    public function authenticate() {
        $ch = curl_init($this->apiUrl . '/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' => $this->clientId,
            'client_secret' => $this->clientSecret
        ]));

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($httpCode !== 201) {
            throw new Exception("Authentication failed: $httpCode");
        }

        $data = json_decode($response, true);
        $this->token = $data['token'];
        $this->tokenExpiry = strtotime($data['expireOn']);

        return $this->token;
    }

    public function getToken() {
        $fiveMinutes = 5 * 60;
        $now = time();

        if (!$this->token || !$this->tokenExpiry || 
            $now >= ($this->tokenExpiry - $fiveMinutes)) {
            $this->authenticate();
        }

        return $this->token;
    }

    public function request($endpoint, $method = 'GET', $data = null) {
        $token = $this->getToken();
        $ch = curl_init($this->apiUrl . $endpoint);

        $headers = [
            'Authorization: Bearer ' . $token,
            'Content-Type: application/json'
        ];

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        if ($method !== 'GET') {
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
            if ($data) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
            }
        }

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($httpCode < 200 || $httpCode >= 300) {
            throw new Exception("API Error: $httpCode - $response");
        }

        return json_decode($response, true);
    }
}

// Uso
$auth = new DiviPayAuth(
    getenv('DIVIPAY_CLIENT_ID'),
    getenv('DIVIPAY_CLIENT_SECRET')
);

$charge = $auth->request('/api/charge/pix', 'POST', [
    // dados da cobrança
]);
?>

Classe Helper (Python)

python
import requests
from datetime import datetime, timedelta

class DiviPayAuth:
    def __init__(self, client_id, client_secret, api_url='https://api.divipay.com.br'):
        self.client_id = client_id
        self.client_secret = client_secret
        self.api_url = api_url
        self.token = None
        self.token_expiry = None

    def authenticate(self):
        response = requests.post(
            f'{self.api_url}/api/auth',
            json={
                'client_id': self.client_id,
                'client_secret': self.client_secret
            }
        )

        if response.status_code != 201:
            raise Exception(f'Authentication failed: {response.status_code}')

        data = response.json()
        self.token = data['token']
        self.token_expiry = datetime.fromisoformat(data['expireOn'].replace('Z', '+00:00'))

        return self.token

    def get_token(self):
        five_minutes = timedelta(minutes=5)
        now = datetime.now()

        if not self.token or not self.token_expiry or \
           now >= (self.token_expiry - five_minutes):
            self.authenticate()

        return self.token

    def request(self, endpoint, method='GET', data=None):
        token = self.get_token()

        headers = {
            'Authorization': f'Bearer {token}',
            'Content-Type': 'application/json'
        }

        url = f'{self.api_url}{endpoint}'

        if method == 'GET':
            response = requests.get(url, headers=headers)
        elif method == 'POST':
            response = requests.post(url, headers=headers, json=data)
        elif method == 'PUT':
            response = requests.put(url, headers=headers, json=data)
        elif method == 'DELETE':
            response = requests.delete(url, headers=headers)

        if response.status_code < 200 or response.status_code >= 300:
            raise Exception(f'API Error: {response.status_code} - {response.text}')

        return response.json()

# Uso
import os

auth = DiviPayAuth(
    os.getenv('DIVIPAY_CLIENT_ID'),
    os.getenv('DIVIPAY_CLIENT_SECRET')
)

charge = auth.request('/api/charge/pix', 'POST', {
    # dados da cobrança
})

Variáveis de Ambiente

Armazene credenciais em variáveis de ambiente:

.env

bash
DIVIPAY_CLIENT_ID=seu_client_id
DIVIPAY_CLIENT_SECRET=seu_client_secret
DIVIPAY_API_URL=https://api.divipay.com.br

Node.js

javascript
require('dotenv').config();

const auth = new DiviPayAuth(
  process.env.DIVIPAY_CLIENT_ID,
  process.env.DIVIPAY_CLIENT_SECRET,
  process.env.DIVIPAY_API_URL
);

PHP

php
<?php
// Usando vlucas/phpdotenv
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();

$auth = new DiviPayAuth(
    $_ENV['DIVIPAY_CLIENT_ID'],
    $_ENV['DIVIPAY_CLIENT_SECRET'],
    $_ENV['DIVIPAY_API_URL']
);
?>

Python

python
import os
from dotenv import load_dotenv

load_dotenv()

auth = DiviPayAuth(
    os.getenv('DIVIPAY_CLIENT_ID'),
    os.getenv('DIVIPAY_CLIENT_SECRET'),
    os.getenv('DIVIPAY_API_URL')
)

Erros Comuns

401 Unauthorized

Credenciais inválidas ou API não habilitada.

Solução:

  1. Verifique se client_id e client_secret estão corretos
  2. Confirme que a API está habilitada no painel
  3. Verifique se não há espaços extras nas credenciais

403 Forbidden

Token inválido ou expirado.

Solução:

  1. Renove o token
  2. Verifique se está usando o token correto
  3. Confirme que o token não expirou

Token Expira Muito Rápido

Solução: Implemente renovação automática 5 minutos antes da expiração.

Segurança

✅ Boas Práticas

  • Use HTTPS em produção
  • Armazene credenciais em variáveis de ambiente
  • Nunca exponha credenciais no frontend
  • Rotacione credenciais periodicamente
  • Monitore uso da API
  • Implemente rate limiting

❌ Evite

  • Hardcoded credentials
  • Credenciais em repositórios Git
  • Compartilhar credenciais por email/chat
  • Usar mesmas credenciais em dev/prod
  • Expor tokens em logs

Próximos Passos

Documentação da API DiviPay