Saltar a contenido

Autenticación

Visión general

La API de Pontotel usa Bearer Token Authentication (JWT) para autenticar solicitudes.

Flujo de autenticación

  1. Enviar credenciales al endpoint /login/
  2. Recibir access_token en la respuesta
  3. Incluir el token en el header Authorization: Bearer {token}
  4. El token vence en 1 hora

Endpoint de Login

POST /api/v4/login/

Request

JSON
1
2
3
4
{
  "username": "tu_usuario",
  "password": "tu_contrasena"
}

Respuesta (200 OK)

JSON
1
2
3
{
  "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...",
}

Ejemplos de código

Python
import httpx
from datetime import datetime, timedelta, timezone

class PontotelAuth:
    def __init__(self, username, password, base_url):
        self.username = username
        self.password = password
        self.base_url = base_url
        self.token = None
        self.token_expires_at = None

    async def login(self):
        """Hace login y obtiene un token"""
        url = f"{self.base_url}/login/"
        payload = {
            "username": self.username,
            "password": self.password
        }

        async with httpx.AsyncClient() as client:
            response = await client.post(url, json=payload)
            response.raise_for_status()

        data = response.json()
        self.token = data["access_token"]
        self.token_expires_at = datetime.now(tz=timezone.utc) + timedelta(minutes=60)

        return self.token

    async def get_token(self):
        """Devuelve un token valido y lo renueva si hace falta"""
        if not self.token or datetime.now(tz=timezone.utc) >= self.token_expires_at:
            await self.login()
        return self.token

    async def get_headers(self):
        """Devuelve headers autenticados"""
        return {
            "Authorization": f"Bearer {await self.get_token()}",
            "Content-Type": "application/json"
        }

# Uso
import asyncio

async def main():
    auth = PontotelAuth(
        username="tu_usuario",
        password="tu_contrasena",
        base_url="https://apis.pontotel.com.br/pontotel/api/v4"
    )

    # Hacer solicitudes
    headers = await auth.get_headers()
    async with httpx.AsyncClient() as client:
        response = await client.get(
            "https://apis.pontotel.com.br/pontotel/api/v4/usuarios/",
            headers=headers
        )

asyncio.run(main())
JavaScript
class PontotelAuth {
  constructor(username, password, baseUrl) {
    this.username = username;
    this.password = password;
    this.baseUrl = baseUrl;
    this.token = null;
    this.tokenExpiresAt = null;
  }

  async login() {
    const url = `${this.baseUrl}/login/`;
    const response = await fetch(url, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        username: this.username,
        password: this.password
      })
    });

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

    const data = await response.json();
    this.token = data.access_token;
    this.tokenExpiresAt = Date.now() + (data.expires_in * 1000);

    return this.token;
  }

  async getToken() {
    if (!this.token || Date.now() >= this.tokenExpiresAt) {
      await this.login();
    }
    return this.token;
  }

  async getHeaders() {
    const token = await this.getToken();
    return {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json'
    };
  }
}

// Uso
const auth = new PontotelAuth(
  'tu_usuario',
  'tu_contrasena',
  'https://apis.pontotel.com.br/pontotel/api/v4'
);

// Hacer solicitudes
const headers = await auth.getHeaders();
const response = await fetch(
  'https://apis.pontotel.com.br/pontotel/api/v4/usuarios/',
  { headers }
);
Bash
# 1. Login
curl -X POST "https://apis.pontotel.com.br/pontotel/api/v4/login/" \
  -H "Content-Type: application/json" \
  -d '{
    "username": "tu_usuario",
    "password": "tu_contrasena"
  }' \
  | jq -r '.access_token' > token.txt

# 2. Usar token
TOKEN=$(cat token.txt)

curl -X GET "https://apis.pontotel.com.br/pontotel/api/v4/usuarios/" \
  -H "Authorization: Bearer $TOKEN"

Seguridad

Prácticas importantes

  • Nunca compartas credenciales o tokens
  • Guardá los tokens en variables de entorno o secret managers
  • Rotá credenciales de forma regular
  • Usá HTTPS siempre (obligatorio)
  • No hagas commit de tokens en Git

Almacenamiento seguro

Python
# .env
PONTOTEL_USERNAME=tu_usuario
PONTOTEL_PASSWORD=tu_contrasena

# codigo
import os

auth = PontotelAuth(
    username=os.environ.get("PONTOTEL_USERNAME"),
    password=os.environ.get("PONTOTEL_PASSWORD"),
    base_url="https://apis.pontotel.com.br/pontotel/api/v4"
)
JavaScript
// .env
PONTOTEL_USERNAME=tu_usuario
PONTOTEL_PASSWORD=tu_contrasena

// codigo
require('dotenv').config();

const auth = new PontotelAuth(
  process.env.PONTOTEL_USERNAME,
  process.env.PONTOTEL_PASSWORD,
  'https://apis.pontotel.com.br/pontotel/api/v4'
);

Expiración y renovación

  • Los tokens vencen en 1 hora (3600 segundos)
  • Tratá los errores 401 Unauthorized reautenticando
  • Implementá una lógica de renovación automática a partir del atributo exp del token

Ejemplo de Retry Logic

Python
import httpx

transport = httpx.AsyncHTTPTransport(retries=3)

async def realizar_requisicao_com_retentativa(url, headers):
    async with httpx.AsyncClient(transport=transport) as client:
        response = await client.get(url, headers=headers)
        response.raise_for_status()
        return response

# Uso
import asyncio

async def main():
    response = await realizar_requisicao_com_retentativa(url, headers)

asyncio.run(main())

Errores comunes

Código Error Solución
400 Bad Request Verificá el formato del payload
401 Unauthorized Credenciales invalidas o token vencido
403 Forbidden No tenés permiso para ese recurso
422 Validation error Verificá los datos enviados en el payload

Próximos pasos