Verify KRIN postbacks: the krin-pb-v2 example
Check the signature on every KRIN reward postback: a GET krin-pb-v2 example and a POST JSON example, worked through with real values, code in Node, PHP and Python, and what the console's test postback shows.
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 and Postback settings and test postbacks. See what's live
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_microsandtest, one per line, as decoded from the URL. For POST JSON it is the header’st, 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
Section titled “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=53493e91b788502054cef2f461a753cbb08ced30af9972e3dcd5a4c56d85a555User-Agent: KRIN-Postback/1X-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-v21764867600cnv_01kbnkrpg0fgz9y6hb7h6nwvvgcreditplayer-104241241250005. Sign it and compare. HMAC-SHA256 with the postback key, as lowercase hex:
53493e91b788502054cef2f461a753cbb08ced30af9972e3dcd5a4c56d85a555Compare 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.
// 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 exampleapp.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 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 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 "", 200Your 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
Section titled “POST JSON: the signature, step by step”KRIN posts the message as JSON with these headers:
Content-Type: application/jsonX-Krin-Signature: t=1764867600,v1=d2ac88178d4693b9a2a0382a66aada97a4ec9711ba44e6cd2961c34a0fb525ccX-Krin-Delivery: dlv_...User-Agent: KRIN-Postback/1- Read
tand everyv1fromX-Krin-Signature. Refuse the message iftis more than 300 seconds away from your clock. - Take the body as the raw bytes you received, before any JSON parsing.
- HMAC-SHA256 with the postback key over
t, a dot, then the raw body:1764867600.{"kind":"credit",...}. - Compare with each
v1in constant time. For the example body in Reward postbacks the result isd2ac88178d4693b9a2a0382a66aada97a4ec9711ba44e6cd2961c34a0fb525cc. - Parse the JSON only now. If
testistrue, answer 2xx and stop. Otherwise act once perconversion_id+kind.
// 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 rotateexport 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 checkapp.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 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 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 FalseWhile you rotate the postback key
Section titled “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:
sigis 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
Section titled “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
Section titled “Common mistakes”- Signing the encoded values.
user_id=player%2B1must be signed asplayer+1. - Reformatting numbers. Sign
rewardandpayout_microsexactly as received.412and412.0are 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 withtest, as0or1(nevertrueorfalse), and the console refuses a GET template without{test}.
Download all test vectors: vectors.json.
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.