# Verify KRIN postbacks: the krin-pb-v2 example

> **Not live on production yet.** This guide follows the published API contract. Its steps work once these parts answer in production: Properties, placements and secrets, Postback settings and test postbacks.

> To verify a KRIN postback, rebuild the signed string and compare HMAC-SHA256 with your placement's postback key. For a GET postback the string is krin-pb-v2, ts, conversion_id, kind, user_id, reward, payout_micros and test, one per line, as decoded from the URL. For POST JSON it is the header's t, a dot and the raw body. Refuse anything older than 300 seconds.

Every postback KRIN sends to your server is signed with your placement's **postback key** (`kps_live_...`). Check that signature before you credit anyone. This page works through one GET postback and one POST postback with real values, so you can compare your code line by line.

> **Answer.** To verify a KRIN postback, rebuild the signed string and compare HMAC-SHA256 with your placement's postback key. For a GET postback the string is `krin-pb-v2`, `ts`, `conversion_id`, `kind`, `user_id`, `reward`, `payout_micros` and `test`, one per line, as decoded from the URL. For POST JSON it is the header's `t`, a dot and the raw body. Refuse anything older than 300 seconds.

The examples use this test key and time. They are not real values: your own key comes from **Postback and keys → Postback key** in the console.

| | value |
|---|---|
| postback key | `kps_test_5f2b9c1d8e7a4b3c2d1e0f9a8b7c6d5e` |
| `ts` | `1764867600` |
| the conversion | `cnv_01kbnkrpg0fgz9y6hb7h6nwvvg`, kind `credit`, user `player-1042`, reward `412` Gems, your net `412500` micro-USD ($0.4125) |

## GET: the krin-pb-v2 signature, step by step

**1. Your URL template.** Name each parameter after its macro; then the helpers below work as they are:

```
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}
```

A GET template must hold the signature `{sig}` and the seven signed macros `{ts}` `{conversion_id}` `{kind}` `{user_id}` `{reward}` `{payout_micros}` `{test}`; otherwise the console refuses to save it. You may add any other macro, such as `{event_key}` or `{country}`; only these seven are signed. `{launch}` isn't one of them: act on it only from POST.

**2. The request your server receives.** KRIN fills in the values, percent-encoded:

```
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. Check the time.** Refuse the message if `ts` is more than 300 seconds away from your clock.

**4. Build the signed string.** Take the values **after** URL-decoding (your framework's query object already has them), exactly as they arrived, and join these eight lines with `\n` (no line break at the end):

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

**5. Sign it and compare.** HMAC-SHA256 with the postback key, as lowercase hex:

```
53493e91b788502054cef2f461a753cbb08ced30af9972e3dcd5a4c56d85a555
```

Compare it with `sig` in constant time. If they match, the message is from KRIN and nothing in those seven values was changed. `test` is one of them, so a test postback can never pass as a real one. The same conversion sent as a test (`test=1`) signs to `84e8afb4c9eb9c8afb186a0b9a146c85ad9170ef131d89c4637b2572719f04b6`.

**6. Act on it once.** If `test` is `1`, answer 2xx and stop: never credit a test. Otherwise record `conversion_id` + `kind` in your table of applied postbacks; if the row was already there, answer 2xx and do nothing. Then credit (or reverse) and answer 2xx. Use only signed values for money: `reward` and `payout_micros`, never `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
```

**Your own parameter names.** If your handler already reads other names (for example `cid` and `uid`), keep them in the template and map them back before you check: `{ 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 }`. The signed string never changes: it always uses `krin-pb-v2` and the seven values in the order above.

## POST JSON: the signature, step by step

KRIN posts the message as JSON with these headers:

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

1. Read `t` and every `v1` from `X-Krin-Signature`. Refuse the message if `t` is more than 300 seconds away from your clock.
2. Take the body as the **raw bytes** you received, before any JSON parsing.
3. HMAC-SHA256 with the postback key over `t`, a dot, then the raw body: `1764867600.{"kind":"credit",...}`.
4. Compare with each `v1` in constant time. For the example body in [Reward postbacks](https://docs.krin.io/en/publishers/postbacks#test-vectors) the result is `d2ac88178d4693b9a2a0382a66aada97a4ec9711ba44e6cd2961c34a0fb525cc`.
5. Parse the JSON only now. If `test` is `true`, answer 2xx and stop. Otherwise act once 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
```

## While you rotate the postback key

When you choose **New key**, the previous key keeps working for 24 hours. During that time:

- **POST:** the header carries two values, `v1=<new>,v1=<old>`. Either may match.
- **GET:** `sig` is signed with the **new** key only.

So deploy the new key to your server first, and check against both keys (`[new, old]`) until the 24 hours are over.

## Try it with a test postback

In the console, open the placement's **Postback and keys** and choose **Send test postback**. KRIN sends a real, signed message to your URL:

| field | value in the test |
|---|---|
| `test` | `true` in JSON, `1` in a GET URL |
| `kind` | `credit` |
| `user_id` | `krin-test-user` |
| `event_key` | `krin_test` ("KRIN test postback") |
| `payout_micros` | `100000` ($0.10), with the `reward` your currency settings give for it |
| `conversion_id`, `click_id`, `offer_id` | new test ids each time |

Your server should verify it like any other message, skip the credit because it is a test, and answer 2xx. The console shows what happened:

| the console says | what it means | what to do |
|---|---|---|
| **Postback acknowledged** with a 2xx status | your server checked and answered | nothing: this counts for **Go live** |
| your server refused the signature (401 or 403) | the check failed on your side | use the **postback** key, not the launch key; sign the decoded values; for POST, sign the raw body, not re-serialized JSON |
| your server answered another status | the request reached you, but your handler failed | look at the request shown with the keys masked, and your server log for that `X-Krin-Delivery` id |
| KRIN could not reach your server | timeout (10 seconds), DNS, TLS, connection refused or a redirect | use the final https address on port 443 with a public host name; KRIN never follows redirects |

You can send up to 30 tests per placement per hour.

## Common mistakes

- **Signing the encoded values.** `user_id=player%2B1` must be signed as `player+1`.
- **Reformatting numbers.** Sign `reward` and `payout_micros` exactly as received. `412` and `412.0` are different strings.
- **Parsing the JSON before the check.** Any change of spacing or key order changes the bytes; keep the raw body.
- **Using the launch key.** The launch key signs wall links; the postback key signs postbacks.
- **A slow clock.** Messages older than 300 seconds fail. Keep your server on NTP.
- **Leaving out `test`.** The signed string always ends with `test`, as `0` or `1` (never `true` or `false`), and the console refuses a GET template without `{test}`.

Download all test vectors: [vectors.json](https://docs.krin.io/postbacks/test-vectors.json).

## FAQ

**Which format should I choose?**
POST JSON if you are writing a new handler: the whole message is signed. GET if your server already reads a URL with parameters from another network: only the signed values can be trusted, so take money only from `reward` and `payout_micros`, and tell tests apart only by the signed `test`.

**Do I have to check the signature on test postbacks?**
Yes. Check every message the same way, so the test proves your real check works.

**Can I allowlist KRIN's IP addresses instead?**
No. The signature is what proves a message came from KRIN.

**What should I answer to a message I already applied?**
2xx. KRIN may deliver the same message again after a timeout; your unique key on `conversion_id` + `kind` keeps it safe.
