# Reward postbacks: credit users safely

> **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, Reward postbacks for real conversions, Delivery log and replays.

> KRIN sends your server a reward postback whenever a user's conversion is credited or reversed. Each message is signed with HMAC-SHA256 using the placement's postback secret, carries your own net and the user's reward, and is retried for 72 hours until your server answers 2xx. Credit once per conversion_id and kind, and never for test messages.

The reward postback is the one message your server needs from KRIN. It says "credit this user" or "take this reward back", and it proves it came from KRIN.

> **Answer.** KRIN sends your server a reward postback whenever a user's conversion is credited or reversed. Each message is signed with HMAC-SHA256 using the placement's postback secret, carries your own net and the user's reward, and is retried for 72 hours until your server answers 2xx. Credit once per `conversion_id` and `kind`, and never for test messages.

## What KRIN sends, and when

| `kind` | sent when | what you do |
|---|---|---|
| `credit` | a conversion is approved | add `reward` to the user's balance |
| `reverse` | an approved conversion is reversed inside the offer's reversal window | take the reward back (or mark it, by your own policy) |
| `hold` | a rule holds a conversion; the user's receipt says "On hold" | optional: show "pending" in your UI. Only with `send_holds` |
| `decline` | a held conversion ends rejected; nothing was ever credited | optional: clear the pending item. Only with `send_holds` |

- Messages for one `conversion_id` arrive one at a time and in order. A `reverse` never arrives before its `credit` was delivered or finally failed.
- Settlement sends nothing: it changes nothing for the user.
- Every reversal carries a `reason_code`. Reversals happen only inside the window the offer declared (14 to 30 days for direct offers; survey and partner offers show their own window before you turn them on). After the window, the reward is final.

## The message

Every message carries the fields below. Money fields are **your net**, never what the advertiser paid.

| field | example | notes |
|---|---|---|
| `kind` | `credit` | see the table above |
| `conversion_id` | `cnv_01kbnkrpg0fgz9y6hb7h6nwvvg` | stable; your dedupe key with `kind` |
| `click_id` | `clk_01kbnkrnzv2c4t3bq8xyn9w7fe` | the click that led to it |
| `user_id` | `player-1042` | the id you put in the signed launch |
| `placement_id`, `offer_id` | `plc_...`, `ofr_...` | |
| `offer_name`, `event_key`, `event_name` | `level_10`, `Reach level 10` | the milestone the user completed |
| `payout_micros` | `412500` | your net in micro-USD (1 USD = 1,000,000), an integer |
| `payout_usd` | `"0.4125"` | the same amount as a decimal string |
| `reward` | `"412"` | what to credit, in your currency, after your rounding. A decimal string |
| `currency` | `Gems` | |
| `status` | `approved` | the conversion's state |
| `reason_code` | `null` | set on `reverse`, `hold` and `decline`: `under_review`, `not_credited`, or a code you or your user can act on, such as `network_vpn` or `geo_mismatch` |
| `ip`, `country` | `null`, `US` | |
| `ts` | `1764867600` | unix seconds when KRIN signed it |
| `test` | `false` | `true` for test postbacks and sandbox conversions. **Never credit those** |
| `launch` | `signed` | how the user's wall session was opened: `signed` (your server signed the launch link), `unsigned` (opened without a signed launch, such as a public web wall where anyone can type a user id) or `headless` (your server, with the Headless Offer API). The last field of the body. A message without it reads as `unsigned` |

If `launch` is `unsigned`, nothing proved the user id: you can hold such rewards on your side until you've checked the user. Act on `launch` only from POST, where it's signed with the body. In a GET template `{launch}` isn't signed, like `{click_id}`: treat a missing or unexpected value as `unsigned`.

Treat `reward` and `payout_usd` as decimal strings. Don't parse them as floating-point numbers. With a GET template, take money only from the signed values `reward` and `payout_micros`.

## Two formats

**POST JSON** (recommended). The body is the JSON above. Headers:

```
Content-Type: application/json
X-Krin-Signature: t=1764867600,v1=<hex>
X-Krin-Delivery: <delivery id>
User-Agent: KRIN-Postback/1
```

**GET URL template** (handy when you move from another network). You give KRIN a URL with macros and KRIN fills them in, URL-encoded:

```
https://api.example.com/krin?cid={conversion_id}&kind={kind}&uid={user_id}&amount={reward}&net={payout_micros}&ts={ts}&is_test={test}&sig={sig}
```

Available macros: `{conversion_id}` `{click_id}` `{user_id}` `{placement_id}` `{offer_id}` `{offer_name}` `{event_key}` `{event_name}` `{payout_usd}` `{payout_micros}` `{reward}` `{currency}` `{status}` `{kind}` `{ip}` `{country}` `{ts}` `{test}` `{launch}` `{sig}`.

The template must include every signed value: `{sig}` `{ts}` `{conversion_id}` `{kind}` `{user_id}` `{reward}` `{payout_micros}` `{test}`. Otherwise KRIN refuses it with `postback_template_unsigned`.

Rules for the URL: https on port 443, a public host name (no IP address, no local name, no macros in the host). A POST URL takes no macros, because the values travel in the signed body.

## Check the signature

A worked example with real values, step by step, is in [Verify KRIN postbacks](https://docs.krin.io/en/publishers/postbacks/verify).

**POST:** `v1 = hex(HMAC-SHA256(postback_secret, "<t>.<raw body>"))`, where `t` is the number in the header. Use the raw bytes you received, before any JSON parsing.

**GET:** `sig = hex(HMAC-SHA256(postback_secret, canonical))`, where `canonical` is these values joined with `\n`, exactly as they read after URL-decoding (`test` is `0` or `1`):

```
krin-pb-v2
{ts}
{conversion_id}
{kind}
{user_id}
{reward}
{payout_micros}
{test}
```

`test` is signed, so a test postback can never pass as a real one.

For both formats:

- Compare in constant time.
- Refuse a message whose `t` / `ts` is more than **300 seconds** away from your clock.
- While you rotate the postback secret, accept either secret. During a rotation the POST header carries two values (`t=...,v1=<new>,v1=<old>`), and either may match.

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

def verify_postback_get(q: dict, secrets: list, now=None) -> bool:
    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)
```

## Test vectors

Run your check against these before you go live. Secret: `kps_test_5f2b9c1d8e7a4b3c2d1e0f9a8b7c6d5e`, `t = ts = 1764867600`.

POST body (exact bytes, one line):

```json
{"kind":"credit","conversion_id":"cnv_01kbnkrpg0fgz9y6hb7h6nwvvg","click_id":"clk_01kbnkrnzv2c4t3bq8xyn9w7fe","user_id":"player-1042","placement_id":"plc_01kbmz6v7r1s0e5d4c3b2a1z0y","offer_id":"ofr_01kbmy9x8w7v6t5s4r3q2p1n0m","event_key":"level_10","event_name":"Reach level 10","payout_micros":412500,"payout_usd":"0.4125","reward":"412","currency":"Gems","status":"approved","reason_code":null,"ip":null,"country":"US","ts":1764867600,"test":false}
```

| check | expected |
|---|---|
| POST `v1` | `d2ac88178d4693b9a2a0382a66aada97a4ec9711ba44e6cd2961c34a0fb525cc` |
| POST `v1` (the same body ending `,"launch":"unsigned"}`) | `a01842afbf42877b65631fc778090870361921a6f6923268d7b594a19641cd1d` |
| GET `sig` (same conversion, `test` = `0`) | `53493e91b788502054cef2f461a753cbb08ced30af9972e3dcd5a4c56d85a555` |
| GET `sig` (same conversion as a test, `test` = `1`) | `84e8afb4c9eb9c8afb186a0b9a146c85ad9170ef131d89c4637b2572719f04b6` |
| the same body with one byte changed | must fail |
| the same message checked 301 seconds after `t` | must fail |

Download: [vectors.json](https://docs.krin.io/postbacks/test-vectors.json). Your test clock must be set to `t` for the vectors to pass.

## Credit exactly once

KRIN may deliver the same message more than once: a retry after your server timed out, or a replay. Make crediting idempotent:

1. Keep a table of applied postbacks with a unique key on (`conversion_id`, `kind`).
2. In one transaction: insert that row and change the user's balance. If the row already exists, do nothing.
   A test message (`test` true, or `1` in a GET) is answered 2xx and never credited.
3. Answer 2xx either way.

Answer quickly (KRIN waits 10 seconds). If your crediting is slow, store the message, answer 2xx, and process it in the background.

## Retries and replays

| your server answers | KRIN does |
|---|---|
| any 2xx | delivered (KRIN ignores the body) |
| 410 Gone | stops at once: you said never send this again. You can still replay it |
| anything else, a timeout (10 s), a TLS or connection error, or a 3xx redirect | retries |

- Retries come after about 1, 5 and 15 minutes, 1 hour, then every 2 hours, with some jitter, for **72 hours**. Then the delivery is marked failed.
- A `429` or `503` with `Retry-After` delays the next try by up to 1 hour.
- Redirects are never followed. Point the URL at the final address.
- **Deliveries** (under **Conversions** in the console) shows every attempt: status code, latency and whether the signature went out. Replay one delivery or a whole time range from there, or with `POST /v1/publisher/deliveries/replay`. A replay is a new delivery of the same message, so your dedupe keeps it safe.

## Allowlist KRIN's IP addresses

Don't allowlist IP addresses for KRIN postbacks yet. Check the signature: it is what proves the message came from KRIN.

## FAQ

**Why didn't my user get their reward?**
Look for the conversion in **Deliveries**: it shows every attempt to your server and what your server answered. If a delivery failed, fix your endpoint and replay it.

**Is `payout_usd` what the advertiser paid?**
No. It is your own net earnings for that conversion. KRIN never sends advertiser prices.

**Do I have to handle `reverse`?**
Yes. KRIN always sends reversals, and you can't turn them off. They only happen inside the offer's declared window and always carry a reason code.

**Should I reject a message with an unknown `kind`?**
Answer 2xx and log it, so one unexpected message never blocks the ones behind it.

**What if my server was down for a day?**
KRIN keeps retrying for 72 hours. After that, replay the failed deliveries from **Deliveries**.
