# Verificare i postback KRIN: l'esempio krin-pb-v2

> **Non ancora in produzione.** Questa guida segue il contratto API pubblicato. I passaggi funzionano non appena queste parti rispondono in produzione: Proprietà, posizionamenti e segreti, Impostazioni postback e postback di test.

> Per verificare un postback KRIN, ricostruisci la stringa firmata e confronta l'HMAC-SHA256 calcolato con la chiave postback del tuo posizionamento. Per un postback GET la stringa è krin-pb-v2, ts, conversion_id, kind, user_id, reward, payout_micros e test, uno per riga, così come risultano decodificati dall'URL. Per il POST JSON è il t dell'intestazione, un punto e il corpo grezzo. Rifiuta tutto ciò che ha più di 300 secondi.

Ogni postback che KRIN invia al tuo server è firmato con la **chiave postback** del tuo posizionamento (`kps_live_...`). Controlla questa firma prima di accreditare chiunque. Questa pagina svolge un postback GET e un postback POST con valori reali, così puoi confrontare il tuo codice riga per riga.

> **Risposta.** Per verificare un postback KRIN, ricostruisci la stringa firmata e confronta l'HMAC-SHA256 calcolato con la chiave postback del tuo posizionamento. Per un postback GET la stringa è `krin-pb-v2`, `ts`, `conversion_id`, `kind`, `user_id`, `reward`, `payout_micros` e `test`, uno per riga, così come risultano decodificati dall'URL. Per il POST JSON è il `t` dell'intestazione, un punto e il corpo grezzo. Rifiuta tutto ciò che ha più di 300 secondi.

Gli esempi usano questa chiave di test e questo orario. Non sono valori reali: la tua chiave si trova nella console, in **Postback e chiavi → Chiave postback**.

| | valore |
|---|---|
| chiave postback | `kps_test_5f2b9c1d8e7a4b3c2d1e0f9a8b7c6d5e` |
| `ts` | `1764867600` |
| la conversione | `cnv_01kbnkrpg0fgz9y6hb7h6nwvvg`, kind `credit`, utente `player-1042`, ricompensa `412` Gems, i tuoi guadagni netti `412500` micro-USD (0,4125 $) |

## GET: la firma krin-pb-v2, passo per passo

**1. Il tuo modello di URL.** Chiama ogni parametro come la sua macro; così le funzioni qui sotto funzionano così come sono:

```
https://api.example.com/krin/postback?conversion_id={conversion_id}&kind={kind}&user_id={user_id}&reward={reward}&payout_micros={payout_micros}&ts={ts}&test={test}&sig={sig}
```

Un modello GET deve contenere la firma `{sig}` e le sette macro firmate `{ts}` `{conversion_id}` `{kind}` `{user_id}` `{reward}` `{payout_micros}` `{test}`; altrimenti la console non lo salva. Puoi aggiungere qualsiasi altra macro, come `{event_key}` o `{country}`; solo queste sette sono firmate. `{launch}` non è tra queste: usala solo da POST.

**2. La richiesta che riceve il tuo server.** KRIN compila i valori con la codifica percentuale:

```
GET /krin/postback?conversion_id=cnv_01kbnkrpg0fgz9y6hb7h6nwvvg&kind=credit&user_id=player-1042&reward=412&payout_micros=412500&ts=1764867600&test=0&sig=53493e91b788502054cef2f461a753cbb08ced30af9972e3dcd5a4c56d85a555
User-Agent: KRIN-Postback/1
X-Krin-Delivery: dlv_...
```

**3. Controlla l'orario.** Rifiuta il messaggio se `ts` si discosta di oltre 300 secondi dal tuo orologio.

**4. Costruisci la stringa firmata.** Prendi i valori **dopo** la decodifica dell'URL (l'oggetto query del tuo framework li contiene già), esattamente come sono arrivati, e unisci queste otto righe con `\n` (senza a capo finale):

```
krin-pb-v2
1764867600
cnv_01kbnkrpg0fgz9y6hb7h6nwvvg
credit
player-1042
412
412500
0
```

**5. Firma e confronta.** HMAC-SHA256 con la chiave postback, in esadecimale minuscolo:

```
53493e91b788502054cef2f461a753cbb08ced30af9972e3dcd5a4c56d85a555
```

Confrontalo con `sig` in tempo costante. Se corrispondono, il messaggio viene da KRIN e nessuno di quei sette valori è stato modificato. `test` è uno di questi, quindi un postback di test non può mai passare per uno reale. La stessa conversione inviata come test (`test=1`) dà la firma `84e8afb4c9eb9c8afb186a0b9a146c85ad9170ef131d89c4637b2572719f04b6`.

**6. Agisci una sola volta.** Se `test` è `1`, rispondi 2xx e fermati: non accreditare mai un test. Altrimenti registra `conversion_id` + `kind` nella tua tabella dei postback applicati; se la riga c'era già, rispondi 2xx e non fare nulla. Poi accredita (o storna) e rispondi 2xx. Prendi gli importi solo da valori firmati: `reward` e `payout_micros`, mai `payout_usd`.

```js
// Node 18+ (from docs code/krin.mjs)
import { createHmac, timingSafeEqual } from "node:crypto";

const same = (a, b) => a.length === b.length && timingSafeEqual(Buffer.from(a), Buffer.from(b));

// q: the decoded query values. secrets: [current] or [new, old] while you rotate.
export function verifyPostbackGet(q, secrets, now = Math.floor(Date.now() / 1000)) {
  if (!/^\d+$/.test(q.ts ?? "") || Math.abs(now - Number(q.ts)) > 300) return false;
  if (q.test !== "0" && q.test !== "1") return false;
  const message = ["krin-pb-v2", q.ts, q.conversion_id, q.kind, q.user_id, q.reward, q.payout_micros, q.test].join("\n");
  return secrets.some((secret) =>
    same(String(q.sig ?? ""), createHmac("sha256", secret).update(message).digest("hex")));
}

// Express example
app.get("/krin/postback", async (req, res) => {
  if (!verifyPostbackGet(req.query, [process.env.KRIN_POSTBACK_SECRET])) return res.sendStatus(401);
  if (req.query.test === "1") return res.sendStatus(200);           // signed test: acknowledge, never credit
  await applyOnce(req.query.conversion_id, req.query.kind, req.query); // unique on (conversion_id, kind)
  res.sendStatus(200);
});
```

```php
<?php
// PHP 8.1+ (from docs code/krin.php)
function krin_verify_postback_get(array $q, array $secrets, ?int $now = null): bool {
    $now ??= time();
    $ts = (string) ($q['ts'] ?? '');
    if (!ctype_digit($ts) || abs($now - (int) $ts) > 300) {
        return false;
    }
    $test = (string) ($q['test'] ?? '');
    if ($test !== '0' && $test !== '1') {
        return false;
    }
    $message = implode("\n", ['krin-pb-v2', $ts, $q['conversion_id'] ?? '', $q['kind'] ?? '',
        $q['user_id'] ?? '', $q['reward'] ?? '', $q['payout_micros'] ?? '', $test]);
    foreach ($secrets as $secret) {
        if (hash_equals(hash_hmac('sha256', $message, $secret), (string) ($q['sig'] ?? ''))) {
            return true;
        }
    }
    return false;
}

if (!krin_verify_postback_get($_GET, [getenv('KRIN_POSTBACK_SECRET')])) {
    http_response_code(401);
    exit;
}
if ($_GET['test'] !== '1') {                                   // signed test: acknowledge, never credit
    apply_once($_GET['conversion_id'], $_GET['kind'], $_GET);  // unique on (conversion_id, kind)
}
http_response_code(200);
```

```python
# Python 3.9+ (from docs code/krin.py)
import hashlib, hmac, time

def verify_postback_get(q: dict, secrets: list, now=None) -> bool:
    """q holds the decoded query values."""
    now = int(time.time()) if now is None else now
    ts = str(q.get("ts", ""))
    if not ts.isdigit() or abs(now - int(ts)) > 300:
        return False
    test = str(q.get("test", ""))
    if test not in ("0", "1"):
        return False
    message = "\n".join(["krin-pb-v2", ts] + [str(q.get(k, "")) for k in
                         ("conversion_id", "kind", "user_id", "reward", "payout_micros")] + [test])
    return any(hmac.compare_digest(
        hmac.new(s.encode(), message.encode(), hashlib.sha256).hexdigest(), str(q.get("sig", "")))
        for s in secrets)

# Flask example
@app.get("/krin/postback")
def krin_postback():
    q = request.args.to_dict()
    if not verify_postback_get(q, [os.environ["KRIN_POSTBACK_SECRET"]]):
        return "", 401
    if q["test"] != "1":                                 # signed test: acknowledge, never credit
        apply_once(q["conversion_id"], q["kind"], q)     # unique on (conversion_id, kind)
    return "", 200
```

**I tuoi nomi di parametro.** Se il tuo handler legge già altri nomi (per esempio `cid` e `uid`), tienili nel modello e rimappali prima della verifica: `{ ts: q.ts, conversion_id: q.cid, kind: q.kind, user_id: q.uid, reward: q.amount, payout_micros: q.net, test: q.is_test, sig: q.sig }`. La stringa firmata non cambia mai: usa sempre `krin-pb-v2` e i sette valori nell'ordine sopra.

## POST JSON: la firma, passo per passo

KRIN invia il messaggio come JSON con queste intestazioni:

```
Content-Type: application/json
X-Krin-Signature: t=1764867600,v1=d2ac88178d4693b9a2a0382a66aada97a4ec9711ba44e6cd2961c34a0fb525cc
X-Krin-Delivery: dlv_...
User-Agent: KRIN-Postback/1
```

1. Leggi `t` e ogni `v1` da `X-Krin-Signature`. Rifiuta il messaggio se `t` si discosta di oltre 300 secondi dal tuo orologio.
2. Prendi il corpo come i **byte grezzi** ricevuti, prima di qualsiasi lettura del JSON.
3. HMAC-SHA256 con la chiave postback su `t`, un punto e poi il corpo grezzo: `1764867600.{"kind":"credit",...}`.
4. Confronta con ogni `v1` in tempo costante. Per il corpo di esempio in [Postback di ricompensa](https://docs.krin.io/it/publishers/postbacks#test-vectors) il risultato è `d2ac88178d4693b9a2a0382a66aada97a4ec9711ba44e6cd2961c34a0fb525cc`.
5. Solo ora leggi il JSON. Se `test` è `true`, rispondi 2xx e fermati. Altrimenti agisci una volta per `conversion_id` + `kind`.

```js
// Node 18+ (from docs code/krin.mjs)
import { createHmac, timingSafeEqual } from "node:crypto";

const same = (a, b) => a.length === b.length && timingSafeEqual(Buffer.from(a), Buffer.from(b));

// secrets: [current] or [new, old] while you rotate
export function verifyPostbackPost(rawBody, header, secrets, now = Math.floor(Date.now() / 1000)) {
  let t = null;
  const sigs = [];
  for (const part of header.split(",")) {
    const [k, v = ""] = part.trim().split("=", 2);
    if (k === "t") t = v;
    else if (k === "v1") sigs.push(v);
  }
  if (!/^\d+$/.test(t ?? "") || Math.abs(now - Number(t)) > 300) return false;
  return secrets.some((secret) => {
    const expected = createHmac("sha256", secret).update(`${t}.`).update(rawBody).digest("hex");
    return sigs.some((v) => same(v, expected));
  });
}

// Express example: keep the raw body for the signature check
app.post("/krin/postback", express.raw({ type: "application/json" }), async (req, res) => {
  if (!verifyPostbackPost(req.body, req.get("X-Krin-Signature") ?? "", [process.env.KRIN_POSTBACK_SECRET])) {
    return res.sendStatus(401);
  }
  const pb = JSON.parse(req.body);
  if (pb.test) return res.sendStatus(200);       // acknowledge, never credit
  await applyOnce(pb.conversion_id, pb.kind, pb); // unique on (conversion_id, kind)
  res.sendStatus(200);
});
```

```php
<?php
// PHP 8.1+ (from docs code/krin.php)
function krin_verify_postback_post(string $rawBody, string $header, array $secrets, ?int $now = null): bool {
    $now ??= time();
    $t = null;
    $sigs = [];
    foreach (explode(',', $header) as $part) {
        [$k, $v] = array_pad(explode('=', trim($part), 2), 2, '');
        if ($k === 't') { $t = $v; } elseif ($k === 'v1') { $sigs[] = $v; }
    }
    if ($t === null || !ctype_digit($t) || abs($now - (int) $t) > 300) {
        return false;
    }
    foreach ($secrets as $secret) {
        $expected = hash_hmac('sha256', $t . '.' . $rawBody, $secret);
        foreach ($sigs as $v) {
            if (hash_equals($expected, $v)) {
                return true;
            }
        }
    }
    return false;
}

$raw = file_get_contents('php://input');
if (!krin_verify_postback_post($raw, $_SERVER['HTTP_X_KRIN_SIGNATURE'] ?? '', [getenv('KRIN_POSTBACK_SECRET')])) {
    http_response_code(401);
    exit;
}
$pb = json_decode($raw, true, flags: JSON_THROW_ON_ERROR | JSON_BIGINT_AS_STRING);
if (!$pb['test']) {
    apply_once($pb['conversion_id'], $pb['kind'], $pb); // unique on (conversion_id, kind)
}
http_response_code(200);
```

```python
# Python 3.9+ (from docs code/krin.py)
import hashlib, hmac, time

def verify_postback_post(raw_body: bytes, header: str, secrets: list, now=None) -> bool:
    now = int(time.time()) if now is None else now
    t, sigs = None, []
    for part in header.split(","):
        key, _, value = part.strip().partition("=")
        if key == "t":
            t = value
        elif key == "v1":
            sigs.append(value)
    if not t or not t.isdigit() or abs(now - int(t)) > 300:
        return False
    for secret in secrets:
        expected = hmac.new(secret.encode(), t.encode() + b"." + raw_body, hashlib.sha256).hexdigest()
        if any(hmac.compare_digest(expected, v) for v in sigs):
            return True
    return False
```

## Mentre ruoti la chiave postback

Quando scegli **Nuova chiave**, la chiave precedente continua a funzionare per 24 ore. In quel periodo:

- **POST:** l'intestazione porta due valori, `v1=<new>,v1=<old>`. Uno dei due può corrispondere.
- **GET:** `sig` è firmato solo con la chiave **nuova**.

Quindi distribuisci prima la nuova chiave sul tuo server e verifica con entrambe le chiavi (`[new, old]`) finché non passano le 24 ore.

## Provalo con un postback di test

Nella console, apri **Postback e chiavi** sul posizionamento e scegli **Invia postback di test**. KRIN invia un messaggio reale e firmato al tuo URL:

| campo | valore nel test |
|---|---|
| `test` | `true` in JSON, `1` in un URL GET |
| `kind` | `credit` |
| `user_id` | `krin-test-user` |
| `event_key` | `krin_test` ("KRIN test postback") |
| `payout_micros` | `100000` (0,10 $), con la `reward` che le tue impostazioni di valuta danno per quell'importo |
| `conversion_id`, `click_id`, `offer_id` | nuovi id di test ogni volta |

Il tuo server dovrebbe verificarlo come qualsiasi altro messaggio, saltare l'accredito perché è un test e rispondere 2xx. La console mostra cos'è successo:

| la console mostra | cosa significa | cosa fare |
|---|---|---|
| **Postback confermato** con uno stato 2xx | il tuo server ha verificato e risposto | niente: questo conta per **Vai live** |
| il tuo server ha rifiutato la firma (401 o 403) | la verifica è fallita dalla tua parte | usa la chiave **postback**, non quella di avvio; firma i valori decodificati; per POST firma il corpo grezzo, non un JSON riserializzato |
| il tuo server ha risposto con un altro stato | la richiesta ti è arrivata, ma il tuo handler è fallito | guarda la richiesta mostrata con le chiavi mascherate e il log del tuo server per quell'id `X-Krin-Delivery` |
| KRIN non è riuscita a raggiungere il tuo server | timeout (10 secondi), DNS, TLS, connessione rifiutata o un reindirizzamento | usa l'indirizzo https finale sulla porta 443 con un nome host pubblico; KRIN non segue mai i reindirizzamenti |

Puoi inviare fino a 30 test per posizionamento all'ora.

## Errori comuni

- **Firmare i valori codificati.** `user_id=player%2B1` va firmato come `player+1`.
- **Riformattare i numeri.** Firma `reward` e `payout_micros` esattamente come ricevuti. `412` e `412.0` sono stringhe diverse.
- **Leggere il JSON prima della verifica.** Qualsiasi cambio di spazi o di ordine delle chiavi cambia i byte; conserva il corpo grezzo.
- **Usare la chiave di avvio.** La chiave di avvio firma i link della bacheca; la chiave postback firma i postback.
- **Un orologio in ritardo.** I messaggi con più di 300 secondi falliscono. Tieni il tuo server sincronizzato con NTP.
- **Dimenticare `test`.** La stringa firmata finisce sempre con `test`, come `0` o `1` (mai `true` o `false`), e la console rifiuta un modello GET senza `{test}`.

Scarica tutti i vettori di test: [vectors.json](https://docs.krin.io/postbacks/test-vectors.json).

## FAQ

**Quale formato dovrei scegliere?**
POST JSON se scrivi un nuovo handler: tutto il messaggio è firmato. GET se il tuo server legge già un URL con parametri da un'altra rete: ci si può fidare solo dei valori firmati, quindi prendi gli importi solo da `reward` e `payout_micros` e riconosci i test solo dal `test` firmato.

**Devo verificare la firma anche dei postback di test?**
Sì. Verifica ogni messaggio allo stesso modo, così il test dimostra che la tua verifica reale funziona.

**Posso invece autorizzare gli indirizzi IP di KRIN?**
No. È la firma a dimostrare che un messaggio viene da KRIN.

**Cosa devo rispondere a un messaggio che ho già applicato?**
2xx. KRIN può consegnare di nuovo lo stesso messaggio dopo un timeout; la tua chiave univoca su `conversion_id` + `kind` lo rende sicuro.
