Webhooks (avisos)
Cadastre uma URL no seu painel e nós a chamamos quando um dado que você contratou muda. O aviso não leva dado: quando ele chegar, chame a API.
Como cadastrar
- No seu painel, na página da chave: a URL, os eventos e Salvar. O segredo de assinatura (
whsec_…) é mostrado uma vez só. - A URL precisa ser
https, na porta 443 ou 8443, com um nome de host ou endereço público. - Enviar teste entrega um aviso
webhook.test, para você conferir o seu endpoint.
Eventos
| Evento | Quando | Plano |
|---|---|---|
market.world.updated | O Market de um mundo do seu plano mudou; um por mundo. | market |
coins.updated | Os revendedores de coins ou as ofertas P2P mudaram. | Qualquer plano |
npc_profit.updated | O NPC Profit mudou. | npc-profit |
webhook.test | Você apertou Enviar teste no painel. | Sempre |
Você escolhe os eventos; só saem os dos módulos em vigor.
O pedido
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\""}}idé único por aviso e não muda nas novas tentativas: use-o para ignorar repetidos.datadiz o que mudou:world(quando houver),data_versione o novoetag. Busque o dado pela API, como sempre; ele custa unidades como sempre.- Os pedidos vêm do nosso serviço de entrega, com
User-Agent: TGM-Webhooks/1. Não há lista fixa de endereços: confie na assinatura, nunca no IP.
Como conferir a assinatura
Todo pedido leva X-TGM-Signature: t=<unix>,v1=<hex>. O v1 é o HMAC-SHA256, em hexadecimal, de "<t>.<body>" com o seu segredo como chave.
- Use o corpo exatamente como chegou, antes de ler o JSON.
- Compare em tempo constante.
- Recuse o aviso cujo
testeja a mais de 5 minutos do seu relógio. - Cada tentativa é assinada de novo, com um
tnovo.
#!/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")
Os scripts leem o segredo de TGM_WEBHOOK_SECRET, o cabeçalho como primeiro argumento e o corpo da entrada padrão, e imprimem ok ou o motivo.
Como responder
Responda 2xx em até 10 segundos e faça o trabalho depois. Redirecionamentos (3xx) não são seguidos e contam como falha.
Novas tentativas
Qualquer outra resposta, ou nenhuma em 10 segundos, é falha. Tentamos o mesmo aviso de novo depois de 1 min, 5 min, 30 min, 2 h e 6 h, e aí desistimos dele.
Limites
| Limite | Valor |
|---|---|
| URLs por conta | 1 |
market.world.updated por mundo | 1 a cada 5 minutos |
| Avisos por dia | 2.000 |
Testes por dia (webhook.test) | 5 |
O painel lista as últimas 20 entregas, com a situação de cada uma.