Começando
Autenticação
Toda chamada à API do operador e todo callback de carteira são assinados com HMAC-SHA256 usando o segredo do merchant. O esquema é o mesmo nos dois sentidos.
Cabeçalhos#
| Cabeçalho | Valor |
|---|---|
X-Merchant-Id | Código do merchant. |
X-Timestamp | Momento do envio em milissegundos desde 1970 (epoch), em texto. |
X-Nonce | Valor aleatório único por requisição (ex.: 16 bytes em hex). |
X-Signature | Assinatura em hex minúsculo (64 caracteres). |
Content-Type | application/json quando houver corpo. |
String assinada#
{timestamp}.{nonce}.{MÉTODO}.{path com query}.{corpo cru}MÉTODOem maiúsculas (GET,POST).path com queryexatamente como na URL, incluindo o prefixo da versão:/v1/game/launch,/v1/games?page=2&limit=20.corpo crué o texto exato enviado no corpo. EmGET(sem corpo) é vazio — a string termina em..
X-Signature = hex( HMAC_SHA256( segredo, string_assinada ) )Assine o texto que você envia
Serialize o JSON uma vez, assine esse texto e envie o mesmo texto no corpo. Reserializar depois de assinar (outra ordem de campos, espaços, escapes) invalida a assinatura.
Regras de validação#
O TALOS recusa a requisição (HTTP 401, ou 503 em AUTH_UNAVAILABLE) quando:
| Código | Quando |
|---|---|
MISSING_AUTH_HEADERS | Falta algum dos quatro cabeçalhos. |
REQUEST_EXPIRED | X-Timestamp fora da janela de 5 minutos (para mais ou para menos) — mantenha o relógio do servidor sincronizado (NTP). |
INVALID_MERCHANT | Código de merchant inexistente. |
MERCHANT_BLOCKED | Merchant bloqueado. |
INVALID_SIGNATURE | Assinatura não confere. |
IP_NOT_ALLOWED | O merchant tem lista de IPs e a requisição veio de outro IP. |
NONCE_REUSED | O mesmo X-Nonce já foi usado por este merchant (gere um novo a cada requisição, inclusive nos reenvios). |
AUTH_UNAVAILABLE | Falha temporária ao registrar o nonce; tente de novo com novo nonce. |
A autenticação acontece antes da validação do corpo: uma requisição não autenticada nunca recebe 422.
Exemplos#
Um cliente mínimo que assina e envia. Os exemplos das páginas da referência usam a função talos abaixo.
// talos.ts — Node 18+ / Bun
import { createHmac, randomBytes } from 'node:crypto'
const HOST = process.env.TALOS_API_HOST! // ex.: https://<host-da-api> (sem /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 sem /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 sem /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: # 4xx/5xx também trazem o envelope JSON
return json.load(error)
me = talos('GET', '/v1/merchant')Vetor de teste#
Use para conferir a sua implementação:
| Entrada | Valor |
|---|---|
| segredo | segredo-de-teste |
| timestamp | 1767225600000 |
| nonce | 0f1e2d3c4b5a69788796a5b4c3d2e1f0 |
| método / path | POST /v1/game/launch |
| corpo | {"player_id":"user-123","game":"fortune-tiger"} |
1767225600000.0f1e2d3c4b5a69788796a5b4c3d2e1f0.POST./v1/game/launch.{"player_id":"user-123","game":"fortune-tiger"}Assinatura esperada (calculada com a mesma função do TALOS):
6c3a614460cc673c9a247c3e8ced9de5e2d14e5e31b4d0493693f8b6703b2a7aValidar as chamadas do TALOS#
Os callbacks de carteira chegam com os mesmos quatro cabeçalhos, assinados com o segredo do merchant indicado em X-Merchant-Id. Antes de mexer no saldo:
- Leia o corpo cru (texto) antes de qualquer parse de JSON.
- Confira se
X-Merchant-Idé um dos seus merchants e use o segredo dele. - Recuse
X-Timestampfora de uma janela de 5 minutos. - Recalcule a assinatura com o método (
POST), o path + query da suawalletUrle o corpo cru, e compare em tempo constante. - Recomendado: guarde os nonces recebidos por pelo menos 10 minutos e recuse repetidos.
- Só então faça o parse do JSON.
Responda 401 com { "ok": false, "error": "INVALID_SIGNATURE" } quando a validação falhar.
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())Atrás de proxy
O path assinado é o da walletUrl configurada no TALOS. Se um proxy reescreve o path antes da sua aplicação, use o path original da walletUrl no cálculo.