Documentación de la API
API REST completa para gestionar códigos TOTP y autenticación de dos factores.
URL Base
https://tu-tenant.tudominio.com/api
La API de TienPyc 2FA te permite integrar funcionalidades de autenticación de dos factores en tus aplicaciones. Cada tenant tiene su propia API key y límites configurables.
Autenticación
Todas las peticiones a la API deben incluir tu API Key en el header de autorización:
Authorization: Bearer TU_API_KEY
⚠️ Importante: Nunca compartas tu API Key públicamente. Guárdala de forma segura en variables de entorno.
Rate Limiting
Los límites de peticiones dependen de tu plan:
Los headers de respuesta incluyen información sobre tu límite:
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 999
X-RateLimit-Reset: 1640000000
Generar Código TOTP
POST /api/totp/generate
Genera un código TOTP de 6 dígitos para una cuenta específica.
Parámetros
| Parámetro | Tipo | Descripción |
|---|---|---|
account_id |
integer | ID de la cuenta TOTP |
client_id |
integer | ID del cliente (opcional) |
Respuesta Exitosa
{
"success": true,
"data": {
"code": "123456",
"expires_in": 30,
"account_name": "Google - usuario@example.com"
}
}
Listar Cuentas TOTP
GET /api/totp/accounts
Obtiene todas las cuentas TOTP del tenant.
Respuesta
{
"success": true,
"data": [
{
"id": 1,
"account_name": "Google - usuario@example.com",
"issuer": "Google",
"created_at": "2026-01-23T10:00:00Z"
}
]
}
Crear Cuenta TOTP
POST /api/totp/accounts
Parámetros
account_name |
string | Nombre de la cuenta |
secret |
string | Secret TOTP (base32) |
issuer |
string | Emisor (opcional) |
Ejemplo en PHP
<?php
$apiKey = 'TU_API_KEY';
$baseUrl = 'https://tu-tenant.tudominio.com/api';
// Generar código TOTP
$ch = curl_init($baseUrl . '/totp/generate');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $apiKey,
'Content-Type: application/json',
'Accept: application/json'
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
'account_id' => 1
]));
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode === 200) {
$data = json_decode($response, true);
echo "Código TOTP: " . $data['data']['code'];
} else {
echo "Error: " . $response;
}
?>
Ejemplo en Python
import requests
API_KEY = 'TU_API_KEY'
BASE_URL = 'https://tu-tenant.tudominio.com/api'
headers = {
'Authorization': f'Bearer {API_KEY}',
'Content-Type': 'application/json'
}
# Generar código TOTP
response = requests.post(
f'{BASE_URL}/totp/generate',
headers=headers,
json={'account_id': 1}
)
if response.status_code == 200:
data = response.json()
print(f"Código TOTP: {data['data']['code']}")
print(f"Expira en: {data['data']['expires_in']} segundos")
else:
print(f"Error: {response.text}")
Ejemplo en JavaScript (Node.js)
const axios = require('axios');
const API_KEY = 'TU_API_KEY';
const BASE_URL = 'https://tu-tenant.tudominio.com/api';
// Generar código TOTP
async function generateTOTP(accountId) {
try {
const response = await axios.post(
`${BASE_URL}/totp/generate`,
{ account_id: accountId },
{
headers: {
'Authorization': `Bearer ${API_KEY}`,
'Content-Type': 'application/json'
}
}
);
console.log('Código TOTP:', response.data.data.code);
console.log('Expira en:', response.data.data.expires_in, 'segundos');
} catch (error) {
console.error('Error:', error.response?.data || error.message);
}
}
generateTOTP(1);
Ejemplo con cURL
curl -X POST https://tu-tenant.tudominio.com/api/totp/generate \
-H "Authorization: Bearer TU_API_KEY" \
-H "Content-Type: application/json" \
-d '{"account_id": 1}'
Webhooks
Configura webhooks para recibir notificaciones en tiempo real cuando ocurran eventos en tu cuenta.
Configuración
Ve a tu panel de administración → Webhooks → Crear Webhook
Verificación de Firma
Cada webhook incluye una firma HMAC SHA-256 en el header X-Webhook-Signature:
$payload = file_get_contents('php://input');
$signature = $_SERVER['HTTP_X_WEBHOOK_SIGNATURE'];
$secret = 'TU_WEBHOOK_SECRET';
$expectedSignature = hash_hmac('sha256', $payload, $secret);
if (hash_equals($expectedSignature, $signature)) {
// Firma válida, procesar evento
$data = json_decode($payload, true);
} else {
// Firma inválida
http_response_code(401);
}
Eventos Disponibles
totp.generated
Se generó un código TOTP
totp.created
Se creó una nueva cuenta TOTP
client.created
Se creó un nuevo cliente
api.limit_reached
Se alcanzó el límite de peticiones API