# Webhooks

Get notified of payments, refunds and payouts as they happen.

Add an HTTPS endpoint in the dashboard (**Developers → Webhooks**) or with [POST /v1/webhook_endpoints](/api/webhook-endpoints.md). Each endpoint has its own signing secret, can subscribe to all event types or a chosen few, and can listen to test mode, live mode or both.

## The request

For every matching [event](/api/events.md), K-LINK Pay sends a `POST` with a JSON body (the event) and a `Klink-Signature` header:

```text title="POST https://your-site/webhooks/klink-pay"
Content-Type: application/json
Klink-Signature: t=1795773672,v1=5f2c8e…

{
  "id": "evt_2Bc4De6Fg8Hi0Jk2Lm4No6",
  "object": "event",
  "type": "payment.succeeded",
  "livemode": false,
  "created_at": "2026-11-27T10:01:12Z",
  "data": {
    "object": {
      "id": "pay_4Nq7xY2mKc8vTz1aB3dE9f",
      "object": "payment",
      "livemode": false,
      "status": "succeeded",
      "amount": 15200,
      "currency": "MMK",
      "method": "mmqr",
      "reference": "order-1001",
      "bank_reference": "KP7GQ2M9XW4T",
      "description": "Table 4",
      "checkout_url": "https://checkout.klinkpay.net/c/pay_4Nq7xY2mKc8vTz1aB3dE9f",
      "qr_payload": "00020101021226…6304A1B2",
      "redirect_url": null,
      "customer_phone": null,
      "return_url": "https://shop.example.com/orders/1001",
      "metadata": {
        "order_id": "1001"
      },
      "failure_reason": null,
      "expires_at": "2026-11-27T10:15:00Z",
      "succeeded_at": "2026-11-27T10:01:12Z",
      "created_at": "2026-11-27T10:00:00Z",
      "amount_refunded": 0,
      "fees": {
        "provider": 76,
        "klink": 152,
        "total": 228
      },
      "net": 14972,
      "payment_link": null
    }
  }
}
```

## Event types

| Type | When |
|---|---|
| `payment.succeeded` | The customer paid. Fulfil the order. |
| `payment.failed` | The bank declined or the payment failed. |
| `payment.expired` | Nobody paid before expires_at. |
| `payment.canceled` | You canceled the payment. |
| `refund.pending` | A refund was requested. K-LINK processes it to the payer (status manual). |
| `refund.succeeded` | K-LINK refunded the payer and marked the refund done. |
| `refund.failed` | The refund could not be completed. |
| `payout.created` | A payout to your bank account was prepared. |
| `payout.paid` | The payout was transferred to your bank. |
| `payout.canceled` | A prepared payout was canceled. |

## Verifying signatures

The header is `t=<unix timestamp>,v1=<signature>`, where the signature is the hex HMAC-SHA256 of `<t>.<raw body>` keyed with your endpoint's secret. To verify:

1. Read the **raw** request body, before any JSON parsing (re-serialised JSON won't match).
2. Split the header on `,` and take `t` and `v1`.
3. Compute `HMAC-SHA256(secret, t + "." + body)` as lowercase hex.
4. Compare it with `v1` in constant time.
5. Reject the request if `t` is more than 5 minutes from now, to stop replays.

```javascript
import crypto from "node:crypto";
import express from "express";

const app = express();
const SECRET = process.env.KLINK_PAY_WEBHOOK_SECRET;
const TOLERANCE_SECONDS = 300;

// Use the raw body: the signature covers the exact bytes we sent.
app.post("/webhooks/klink-pay", express.raw({ type: "application/json" }), (req, res) => {
  const header = req.get("Klink-Signature") ?? "";
  const parts = Object.fromEntries(header.split(",").map((p) => p.split("=", 2)));
  const t = Number(parts.t);
  const body = req.body.toString("utf8");

  const expected = crypto.createHmac("sha256", SECRET).update(`${t}.${body}`).digest("hex");
  const given = Buffer.from(parts.v1 ?? "", "hex");
  const valid =
    given.length === expected.length / 2 &&
    crypto.timingSafeEqual(given, Buffer.from(expected, "hex")) &&
    Math.abs(Date.now() / 1000 - t) <= TOLERANCE_SECONDS;
  if (!valid) return res.status(400).send("bad signature");

  const event = JSON.parse(body);
  // Deduplicate by event.id, then hand off to a queue and answer quickly.
  if (event.type === "payment.succeeded") {
    markOrderPaid(event.data.object.reference);
  }
  res.sendStatus(200);
});
```

```php
<?php
$secret = getenv("KLINK_PAY_WEBHOOK_SECRET");
$body = file_get_contents("php://input"); // raw body
$header = $_SERVER["HTTP_KLINK_SIGNATURE"] ?? "";

$parts = [];
foreach (explode(",", $header) as $part) {
    [$k, $v] = array_pad(explode("=", $part, 2), 2, "");
    $parts[$k] = $v;
}
$t = (int) ($parts["t"] ?? 0);
$expected = hash_hmac("sha256", $t . "." . $body, $secret);

if (!hash_equals($expected, $parts["v1"] ?? "") || abs(time() - $t) > 300) {
    http_response_code(400);
    exit("bad signature");
}

$event = json_decode($body, true);
// Deduplicate by $event["id"].
if ($event["type"] === "payment.succeeded") {
    mark_order_paid($event["data"]["object"]["reference"]);
}
http_response_code(200);
```

```python
import hashlib
import hmac
import json
import os
import time

from flask import Flask, abort, request

app = Flask(__name__)
SECRET = os.environ["KLINK_PAY_WEBHOOK_SECRET"].encode()

@app.post("/webhooks/klink-pay")
def klink_pay_webhook():
    body = request.get_data()  # raw bytes
    parts = dict(p.split("=", 1) for p in request.headers.get("Klink-Signature", "").split(",") if "=" in p)
    t = int(parts.get("t", "0"))
    expected = hmac.new(SECRET, f"{t}.".encode() + body, hashlib.sha256).hexdigest()

    if not hmac.compare_digest(expected, parts.get("v1", "")) or abs(time.time() - t) > 300:
        abort(400)

    event = json.loads(body)
    # Deduplicate by event["id"].
    if event["type"] == "payment.succeeded":
        mark_order_paid(event["data"]["object"]["reference"])
    return "", 200
```

## Responding and retries

Answer with any `2xx` status within a few seconds. Do the slow work (emails, fulfilment) after responding, e.g. in a queue. A non-2xx answer, a timeout or a connection error is retried after:

| Attempt | Delay after the previous attempt |
|---|---|
| 2 | 30 seconds |
| 3 | 2 minutes |
| 4 | 10 minutes |
| 5 | 30 minutes |
| 6 | 1 hour |
| 7 | 3 hours |
| 8 | 6 hours |
| 9 | 12 hours |
| 10 | 24 hours |

After the last retry the delivery is marked failed. You can see every delivery, its HTTP status and error in the dashboard, and send it again with **Retry**.

### Duplicates and order

- The same event can arrive more than once (e.g. if your 200 got lost). Store the event `id` and skip ids you have handled.
- Events can arrive out of order. Use `data.object.status`, or fetch the object with the API, rather than assuming the order.
- Check `livemode` if one endpoint receives both modes.

### Rotating the secret

Rotate an endpoint's secret in the dashboard if it may have leaked. The new secret is shown once; update your server straight away, because deliveries are signed with the new secret from then on.

> [!NOTE]
> Missed something while your server was down? List recent events with [GET /v1/events](/api/events.md).
