Webhooks (avisos)
Registra una URL en tu panel y la llamamos cuando cambia un dato que contrataste. El aviso no lleva datos: cuando llegue, llama a la API.
Cómo registrarla
- En tu panel, en la página de la clave: la URL, los eventos y Guardar. El secreto de firma (
whsec_…) se muestra una sola vez. - La URL tiene que ser
https, en el puerto 443 o 8443, con un nombre de host o una dirección pública. - Enviar prueba entrega un aviso
webhook.test, para que compruebes tu endpoint.
Eventos
| Evento | Cuándo | Plan |
|---|---|---|
market.world.updated | Cambió el Market de un mundo de tu plan; uno por mundo. | market |
coins.updated | Cambiaron los revendedores de coins o las ofertas P2P. | Cualquier plan |
npc_profit.updated | Cambió NPC Profit. | npc-profit |
webhook.test | Pulsaste Enviar prueba en el panel. | Siempre |
Tú eliges los eventos; solo se entregan los de los módulos vigentes.
La petición
POST /tgm HTTP/1.1
Host: hooks.example.com
Content-Type: application/json
User-Agent: TGM-Webhooks/1
X-TGM-Signature: t=1763380800,v1=<64 hex>
{"id":"3f0c2d9e-8a51-4c47-9b3e-1f2a6d7c8e90","type":"market.world.updated","created_at":"2026-11-17T12:00:00.000Z","data":{"world":"Antica","data_version":"efd2cda81ebbb612","etag":"\"efd2cda81ebbb612\""}}ides único por aviso y no cambia en los reintentos: úsalo para ignorar repetidos.datadice qué cambió:world(cuando lo hay),data_versiony el nuevoetag. Pide los datos a la API como siempre; cuestan unidades como siempre.- Las peticiones llegan desde nuestro servicio de entrega con
User-Agent: TGM-Webhooks/1. No hay una lista fija de direcciones: confía en la firma, nunca en la IP.
Cómo comprobar la firma
Cada petición lleva X-TGM-Signature: t=<unix>,v1=<hex>. v1 es el HMAC-SHA256, en hexadecimal, de "<t>.<body>" con tu secreto como clave.
- Usa el cuerpo exactamente como llegó, antes de leer el JSON.
- Compara en tiempo constante.
- Rechaza el aviso cuyo
testé a más de 5 minutos de tu reloj. - Cada intento se firma de nuevo, con un
tnuevo.
#!/usr/bin/env bash
# Checks one Tibia Global Market webhook notice (needs openssl).
# TGM_WEBHOOK_SECRET=whsec_... bash webhook-verify.sh "<X-TGM-Signature>" < body.json
# The body must be the raw bytes you received, before any JSON parsing.
set -euo pipefail
header="${1:-}"
if [ -z "${TGM_WEBHOOK_SECRET:-}" ] || [ -z "$header" ]; then
echo "Set TGM_WEBHOOK_SECRET and pass the X-TGM-Signature header as the first argument." >&2
exit 2
fi
t=""
sigs=()
IFS=',' read -ra parts <<< "$header"
for p in "${parts[@]}"; do
p="${p// /}"
case "$p" in
t=*) t="${p#t=}" ;;
v1=*) sigs+=("${p#v1=}") ;;
esac
done
if ! [[ "$t" =~ ^[0-9]+$ ]] || [ "${#sigs[@]}" -eq 0 ]; then
echo "rejected: malformed signature header" >&2
exit 1
fi
# HMAC-SHA256 over "<t>.<raw body>", straight from stdin (no trailing newline added).
expected=$( { printf '%s.' "$t"; cat; } | openssl dgst -sha256 -hmac "$TGM_WEBHOOK_SECRET" | awk '{print $NF}')
# Constant-time comparison: compare HMACs of both values under a random key.
nonce=$(openssl rand -hex 16)
mac() { printf '%s' "$1" | openssl dgst -sha256 -hmac "$nonce" | awk '{print $NF}'; }
want=$(mac "$expected")
match=0
for s in "${sigs[@]}"; do
if [ "$(mac "$s")" = "$want" ]; then match=1; fi
done
if [ "$match" -ne 1 ]; then
echo "rejected: bad signature" >&2
exit 1
fi
now=$(date +%s)
age=$(( now > t ? now - t : t - now ))
if [ "$age" -gt $(( 5 * 60 )) ]; then
echo "rejected: timestamp too old" >&2
exit 1
fi
echo "ok"
// Checks one Tibia Global Market webhook notice.
// TGM_WEBHOOK_SECRET=whsec_... node webhook-verify.mjs "<X-TGM-Signature>" < body.json
// The body must be the raw bytes you received, before any JSON parsing.
import { createHmac, timingSafeEqual } from 'node:crypto';
import { resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
const TOLERANCE_S = 5 * 60;
/** true when the header signs this exact body with this secret, at most 5 minutes ago. */
export function verify(secret, header, rawBody, nowS = Math.floor(Date.now() / 1000)) {
const parts = String(header).split(',').map((p) => p.trim().split('='));
const t = parts.find(([k]) => k === 't')?.[1];
const sigs = parts.filter(([k]) => k === 'v1').map(([, v]) => v);
if (!t || !/^\d+$/.test(t) || sigs.length === 0) return { ok: false, why: 'malformed signature header' };
const expected = createHmac('sha256', secret).update(`${t}.`).update(rawBody).digest();
const match = sigs.some((hex) => {
const got = Buffer.from(hex, 'hex');
return got.length === expected.length && timingSafeEqual(got, expected);
});
if (!match) return { ok: false, why: 'bad signature' };
if (Math.abs(nowS - Number(t)) > TOLERANCE_S) return { ok: false, why: 'timestamp too old' };
return { ok: true };
}
// Command line: the same check on stdin.
if (process.argv[1] && fileURLToPath(import.meta.url) === resolve(process.argv[1])) {
const secret = process.env.TGM_WEBHOOK_SECRET;
const header = process.argv[2];
if (!secret || !header) {
console.error('Set TGM_WEBHOOK_SECRET and pass the X-TGM-Signature header as the first argument.');
process.exit(2);
}
const chunks = [];
for await (const c of process.stdin) chunks.push(c);
const r = verify(secret, header, Buffer.concat(chunks));
if (!r.ok) {
console.error(`rejected: ${r.why}`);
process.exit(1);
}
console.log('ok');
}
# Checks one Tibia Global Market webhook notice.
# TGM_WEBHOOK_SECRET=whsec_... python webhook_verify.py "<X-TGM-Signature>" < body.json
# The body must be the raw bytes you received, before any JSON parsing.
import hashlib
import hmac
import os
import sys
import time
TOLERANCE_S = 5 * 60
def verify(secret, header, raw_body, now_s=None):
"""(True, "") when the header signs this exact body with this secret, at most 5 minutes ago."""
now_s = int(time.time()) if now_s is None else now_s
parts = [p.strip().split("=", 1) for p in header.split(",")]
t = next((p[1] for p in parts if len(p) == 2 and p[0] == "t"), "")
sigs = [p[1] for p in parts if len(p) == 2 and p[0] == "v1"]
if not t.isdigit() or not sigs:
return False, "malformed signature header"
expected = hmac.new(secret.encode(), t.encode() + b"." + raw_body, hashlib.sha256).hexdigest()
if not any(hmac.compare_digest(expected.encode(), s.encode()) for s in sigs):
return False, "bad signature"
if abs(now_s - int(t)) > TOLERANCE_S:
return False, "timestamp too old"
return True, ""
if __name__ == "__main__":
secret = os.environ.get("TGM_WEBHOOK_SECRET", "")
if not secret or len(sys.argv) < 2:
print("Set TGM_WEBHOOK_SECRET and pass the X-TGM-Signature header as the first argument.", file=sys.stderr)
sys.exit(2)
ok, why = verify(secret, sys.argv[1], sys.stdin.buffer.read())
if not ok:
print("rejected: " + why, file=sys.stderr)
sys.exit(1)
print("ok")
Los scripts leen el secreto de TGM_WEBHOOK_SECRET, la cabecera como primer argumento y el cuerpo de la entrada estándar, e imprimen ok o el motivo.
Cómo responder
Responde 2xx en menos de 10 segundos y haz el trabajo después. Las redirecciones (3xx) no se siguen y cuentan como fallo.
Reintentos
Cualquier otra respuesta, o ninguna en 10 segundos, es un fallo. Reintentamos el mismo aviso tras 1 min, 5 min, 30 min, 2 h y 6 h, y luego lo abandonamos.
Límites
| Límite | Valor |
|---|---|
| URLs por cuenta | 1 |
market.world.updated por mundo | 1 cada 5 minutos |
| Avisos por día | 2.000 |
Pruebas por día (webhook.test) | 5 |
Tu panel lista las últimas 20 entregas con su estado.