Para empezar
Autenticación
Toda llamada a la API del operador y todo callback de billetera se firman con HMAC-SHA256 usando el secreto del merchant. El esquema es el mismo en ambos sentidos.
Encabezados#
| Encabezado | Valor |
|---|---|
X-Merchant-Id | Código del merchant. |
X-Timestamp | Momento del envío en milisegundos desde 1970 (epoch), como texto. |
X-Nonce | Valor aleatorio único por solicitud (p. ej.: 16 bytes en hex). |
X-Signature | Firma en hex en minúsculas (64 caracteres). |
Content-Type | application/json cuando hay cuerpo. |
Cadena firmada#
{timestamp}.{nonce}.{MÉTODO}.{path con query}.{cuerpo crudo}MÉTODOen mayúsculas (GET,POST).path con queryexactamente como en la URL, incluido el prefijo de versión:/v1/game/launch,/v1/games?page=2&limit=20.cuerpo crudoes el texto exacto enviado en el cuerpo. EnGET(sin cuerpo) está vacío — la cadena termina en..
X-Signature = hex( HMAC_SHA256( secreto, cadena_firmada ) )Firma el texto que envías
Serializa el JSON una vez, firma ese texto y envía el mismo texto en el cuerpo. Volver a serializar después de firmar (otro orden de campos, espacios, escapes) invalida la firma.
Reglas de validación#
TALOS rechaza la solicitud (HTTP 401, o 503 en AUTH_UNAVAILABLE) cuando:
| Código | Cuándo |
|---|---|
MISSING_AUTH_HEADERS | Falta alguno de los cuatro encabezados. |
REQUEST_EXPIRED | X-Timestamp fuera de la ventana de 5 minutos (hacia adelante o hacia atrás) — mantén el reloj del servidor sincronizado (NTP). |
INVALID_MERCHANT | Código de merchant inexistente. |
MERCHANT_BLOCKED | Merchant bloqueado. |
INVALID_SIGNATURE | La firma no coincide. |
IP_NOT_ALLOWED | El merchant tiene una lista de IPs y la solicitud vino de otra IP. |
NONCE_REUSED | El mismo X-Nonce ya fue usado por este merchant (genera uno nuevo en cada solicitud, incluso en los reintentos). |
AUTH_UNAVAILABLE | Falla temporal al registrar el nonce; reintenta con un nonce nuevo. |
La autenticación ocurre antes de la validación del cuerpo: una solicitud no autenticada nunca recibe 422.
Ejemplos#
Un cliente mínimo que firma y envía. Los ejemplos de las páginas de referencia usan la función talos de abajo.
// talos.ts — Node 18+ / Bun
import { createHmac, randomBytes } from 'node:crypto'
const HOST = process.env.TALOS_API_HOST! // p. ej.: https://<host-de-la-api> (sin /v1)
const MERCHANT = process.env.TALOS_MERCHANT!
const SECRET = process.env.TALOS_SECRET!
export async function talos(method: 'GET' | 'POST', path: string, payload?: unknown) {
const body = payload === undefined ? '' : JSON.stringify(payload)
const timestamp = Date.now().toString()
const nonce = randomBytes(16).toString('hex')
const signature = createHmac('sha256', SECRET)
.update(`${timestamp}.${nonce}.${method}.${path}.${body}`, 'utf8')
.digest('hex')
const res = await fetch(`${HOST}${path}`, {
method,
headers: {
...(payload === undefined ? {} : { 'Content-Type': 'application/json' }),
'X-Merchant-Id': MERCHANT,
'X-Timestamp': timestamp,
'X-Nonce': nonce,
'X-Signature': signature
},
body: payload === undefined ? undefined : body
})
return res.json()
}
// uso
const me = await talos('GET', '/v1/merchant')<?php
// talos.php — PHP 8+
function talos(string $method, string $path, ?array $payload = null): array
{
$body = $payload === null ? '' : json_encode($payload, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
$timestamp = (string) (int) round(microtime(true) * 1000);
$nonce = bin2hex(random_bytes(16));
$signature = hash_hmac('sha256', "$timestamp.$nonce." . strtoupper($method) . ".$path.$body", getenv('TALOS_SECRET'));
$headers = [
'X-Merchant-Id: ' . getenv('TALOS_MERCHANT'),
"X-Timestamp: $timestamp",
"X-Nonce: $nonce",
"X-Signature: $signature",
];
if ($payload !== null) {
$headers[] = 'Content-Type: application/json';
}
$ch = curl_init(getenv('TALOS_API_HOST') . $path); // host sin /v1
curl_setopt_array($ch, [
CURLOPT_CUSTOMREQUEST => strtoupper($method),
CURLOPT_HTTPHEADER => $headers,
CURLOPT_RETURNTRANSFER => true,
]);
if ($payload !== null) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
}
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response, true);
}
$me = talos('GET', '/v1/merchant');# talos.py — Python 3.9+
import hashlib, hmac, json, os, secrets, time
import urllib.error, urllib.request
def talos(method: str, path: str, payload=None) -> dict:
body = '' if payload is None else json.dumps(payload, separators=(',', ':'), ensure_ascii=False)
timestamp = str(int(time.time() * 1000))
nonce = secrets.token_hex(16)
message = f'{timestamp}.{nonce}.{method.upper()}.{path}.{body}'
signature = hmac.new(os.environ['TALOS_SECRET'].encode(), message.encode('utf-8'), hashlib.sha256).hexdigest()
headers = {
'X-Merchant-Id': os.environ['TALOS_MERCHANT'],
'X-Timestamp': timestamp,
'X-Nonce': nonce,
'X-Signature': signature,
}
if payload is not None:
headers['Content-Type'] = 'application/json'
request = urllib.request.Request(
os.environ['TALOS_API_HOST'] + path, # host sin /v1
data=body.encode('utf-8') if payload is not None else None,
headers=headers,
method=method.upper(),
)
try:
with urllib.request.urlopen(request) as response:
return json.load(response)
except urllib.error.HTTPError as error: # los 4xx/5xx también traen el sobre JSON
return json.load(error)
me = talos('GET', '/v1/merchant')Vector de prueba#
Úsalo para verificar tu implementación:
| Entrada | Valor |
|---|---|
| secreto | segredo-de-teste |
| timestamp | 1767225600000 |
| nonce | 0f1e2d3c4b5a69788796a5b4c3d2e1f0 |
| método / path | POST /v1/game/launch |
| cuerpo | {"player_id":"user-123","game":"fortune-tiger"} |
1767225600000.0f1e2d3c4b5a69788796a5b4c3d2e1f0.POST./v1/game/launch.{"player_id":"user-123","game":"fortune-tiger"}Firma esperada (calculada con la misma función de TALOS):
6c3a614460cc673c9a247c3e8ced9de5e2d14e5e31b4d0493693f8b6703b2a7aValidar las llamadas de TALOS#
Los callbacks de billetera llegan con los mismos cuatro encabezados, firmados con el secreto del merchant indicado en X-Merchant-Id. Antes de tocar el saldo:
- Lee el cuerpo crudo (texto) antes de cualquier parse de JSON.
- Verifica que
X-Merchant-Idsea uno de tus merchants y usa su secreto. - Rechaza un
X-Timestampfuera de una ventana de 5 minutos. - Recalcula la firma con el método (
POST), el path + query de tuwalletUrly el cuerpo crudo, y compara en tiempo constante. - Recomendado: guarda los nonces recibidos durante al menos 10 minutos y rechaza los repetidos.
- Solo entonces haz el parse del JSON.
Responde 401 con { "ok": false, "error": "INVALID_SIGNATURE" } cuando la validación falle.
import { createHmac, timingSafeEqual } from 'node:crypto'
const SECRETS: Record<string, string> = { [process.env.TALOS_MERCHANT!]: process.env.TALOS_SECRET! }
const WINDOW_MS = 5 * 60_000
export function verifyTalos(request: Request, rawBody: string): boolean {
const merchant = request.headers.get('x-merchant-id')
const timestamp = request.headers.get('x-timestamp')
const nonce = request.headers.get('x-nonce')
const signature = request.headers.get('x-signature')
const secret = merchant ? SECRETS[merchant] : undefined
if (!secret || !timestamp || !nonce || !signature) return false
if (Math.abs(Date.now() - Number(timestamp)) > WINDOW_MS) return false
const url = new URL(request.url)
const expected = createHmac('sha256', secret)
.update(`${timestamp}.${nonce}.${request.method}.${url.pathname}${url.search}.${rawBody}`, 'utf8')
.digest()
const given = Buffer.from(signature, 'hex')
return given.length === expected.length && timingSafeEqual(given, expected)
}<?php
function verify_talos(string $rawBody, string $method, string $pathWithQuery): bool
{
$secrets = [getenv('TALOS_MERCHANT') => getenv('TALOS_SECRET')];
$merchant = $_SERVER['HTTP_X_MERCHANT_ID'] ?? '';
$timestamp = $_SERVER['HTTP_X_TIMESTAMP'] ?? '';
$nonce = $_SERVER['HTTP_X_NONCE'] ?? '';
$signature = $_SERVER['HTTP_X_SIGNATURE'] ?? '';
$secret = $secrets[$merchant] ?? null;
if (!$secret || $timestamp === '' || $nonce === '' || $signature === '') {
return false;
}
if (abs(microtime(true) * 1000 - (float) $timestamp) > 5 * 60 * 1000) {
return false;
}
$expected = hash_hmac('sha256', "$timestamp.$nonce." . strtoupper($method) . ".$pathWithQuery.$rawBody", $secret);
return hash_equals($expected, strtolower($signature));
}
$raw = file_get_contents('php://input');
if (!verify_talos($raw, $_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI'])) {
http_response_code(401);
echo json_encode(['ok' => false, 'error' => 'INVALID_SIGNATURE']);
exit;
}import hashlib, hmac, os, time
SECRETS = {os.environ['TALOS_MERCHANT']: os.environ['TALOS_SECRET']}
def verify_talos(headers, method: str, path_with_query: str, raw_body: str) -> bool:
secret = SECRETS.get(headers.get('X-Merchant-Id', ''))
timestamp = headers.get('X-Timestamp')
nonce = headers.get('X-Nonce')
signature = headers.get('X-Signature')
if not secret or not timestamp or not nonce or not signature:
return False
if abs(time.time() * 1000 - float(timestamp)) > 5 * 60 * 1000:
return False
message = f'{timestamp}.{nonce}.{method.upper()}.{path_with_query}.{raw_body}'
expected = hmac.new(secret.encode(), message.encode('utf-8'), hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, signature.lower())Detrás de un proxy
El path firmado es el de la walletUrl configurada en TALOS. Si un proxy reescribe el path antes de llegar a tu aplicación, usa el path original de la walletUrl en el cálculo.