Webhooks / Callbacks
Receive asynchronous updates when your order completes, and verify they came from us.
Instead of polling the order-status endpoint, we strongly recommend providing a Callback URL under Developer Settings in your member dashboard. In production it must be an https:// URL.
When an order reaches a terminal state (success or failed), our background worker sends an HTTP POST request to your callback URL.
Payload Format
We send a JSON payload to your server:
{
"ref_id": "R-12345",
"status": "success",
"product_code": "MLBB-86",
"product_name": "Mobile Legends 86 Diamonds",
"price": 725,
"serial_number": "KAYBS-A7B2C3D4EF",
"message": "Order completed",
"failure_code": null,
"failure_reason": null,
"quantity": 1,
"units": []
}quantity is the number of units in the order (1 for a plain product, the ingredient count for a combo) and units carries each unit’s own status and serial_number ([] for a plain product).
Failure payload
A failed order carries the two failure fields populated, so your handler can act on the cause without a second API call:
{
"ref_id": "R-12345",
"status": "failed",
"product_code": "MLBB-86",
"product_name": "Mobile Legends 86 Diamonds",
"price": 725,
"serial_number": null,
"message": "Region Lock",
"failure_code": "REGION_LOCKED",
"failure_reason": "Region Lock",
"quantity": 1,
"units": []
}failure_code / failure_reason are additive
Both fields are always present in the payload and are null on a success. If your
integration predates them it keeps working untouched — unknown JSON keys are ignored by every
mainstream parser. Switch on failure_code (stable), display failure_reason (wording may
change). The full code list is in Order Status.
Your coins are refunded automatically on a failure; confirm the amount with
GET /api/v1/order-status, which returns refunded_amount.
refunded_amount appears when coins went back
A callback carries refunded_amount only when coins were actually returned: the full price on
a failed order, or a share of it on a "success" order whose product delivered only part of its
items (for example a bundle where one of two top-ups failed). The key is absent otherwise, so an
integration that ignores it keeps working. GET /api/v1/order-status reports the same figure.
Request Headers
Every callback carries these headers:
Callback Headers
| Parameter | Type | Required | Description |
|---|---|---|---|
Content-Type | String | No | Always application/json. |
X-Timestamp | String | No | When we signed the callback, as Unix time in milliseconds (e.g. 1760700000000). |
X-Signature | String | No | Lowercase hex HMAC-SHA256 of the raw body followed by X-Timestamp, keyed with your API key. |
Security: verifying a callback
Anyone can POST to a public URL, so check every callback before you act on it. The signature is
made with your API key — the same key you send as X-Api-Key:
X-Signature = hex( HMAC-SHA256( key = your API key, message = rawBody + X-Timestamp ) )
rawBody is the request body exactly as it arrived and X-Timestamp is appended as its
string of digits, with nothing in between.
Verification steps
- Reject stale callbacks: if
X-Timestampis more than 5 minutes away from your server’s current time, reject it. This stops a captured callback from being replayed later. - Sign the raw bytes: compute the HMAC over the raw request body exactly as received, then the timestamp. Never parse and re-serialize the JSON first — any change in spacing, key order or escaping produces a different signature.
- Compare in constant time: use Node
crypto.timingSafeEqual, PHPhash_equalsor Pythonhmac.compare_digest, never==. - Answer 2xx fast, work later: we wait at most 5 seconds for your answer. Acknowledge, then process the callback asynchronously.
- Be idempotent on
ref_id: retries and dashboard resends can deliver the same callback more than once. Apply each order’s outcome once.
After you regenerate your API key
Callbacks are signed with your current API key, so switch your verification to the new key
as soon as you regenerate. If a callback fails verification around the moment you rotated, do
not trust its body — read the order from GET /api/v1/order-status instead.
Node.js (Express)
import crypto from 'node:crypto';
import express from 'express';
const app = express();
const API_KEY = process.env.KAYBS_API_KEY;
const MAX_SKEW_MS = 5 * 60 * 1000;
// express.raw keeps the body as the exact bytes we sent; express.json() would re-parse it.
app.post('/kaybs/callback', express.raw({ type: 'application/json', limit: '64kb' }), (req, res) => {
if (!Buffer.isBuffer(req.body)) return res.sendStatus(400);
const timestamp = req.get('X-Timestamp') ?? '';
const received = req.get('X-Signature') ?? '';
if (!/^\d+$/.test(timestamp) || Math.abs(Date.now() - Number(timestamp)) > MAX_SKEW_MS) {
return res.status(401).send('stale timestamp');
}
const expected = crypto
.createHmac('sha256', API_KEY)
.update(Buffer.concat([req.body, Buffer.from(timestamp, 'utf8')]))
.digest('hex');
const a = Buffer.from(received, 'utf8');
const b = Buffer.from(expected, 'utf8');
if (a.length !== b.length || !crypto.timingSafeEqual(a, b)) {
return res.status(401).send('bad signature');
}
let payload;
try {
payload = JSON.parse(req.body.toString('utf8'));
} catch {
return res.sendStatus(400);
}
res.sendStatus(200); // acknowledge within 5 seconds
handleCallback(payload).catch((err) => console.error('callback handler failed', err));
});
async function handleCallback(payload) {
// Idempotent: the same ref_id can arrive more than once.
if (payload.test === true) {
console.log('test callback', payload.ref_id, payload.status);
return;
}
// ...update the order identified by payload.ref_id, once.
}
app.listen(3000);
PHP
<?php
$apiKey = getenv('KAYBS_API_KEY');
$raw = file_get_contents('php://input'); // exact bytes, never re-encoded
$timestamp = $_SERVER['HTTP_X_TIMESTAMP'] ?? '';
$received = $_SERVER['HTTP_X_SIGNATURE'] ?? '';
if (!ctype_digit($timestamp) || abs((int) round(microtime(true) * 1000) - (int) $timestamp) > 300000) {
http_response_code(401);
exit('stale timestamp');
}
$expected = hash_hmac('sha256', $raw . $timestamp, $apiKey);
if (!hash_equals($expected, $received)) {
http_response_code(401);
exit('bad signature');
}
$payload = json_decode($raw, true);
if (!is_array($payload)) {
http_response_code(400);
exit('invalid json');
}
http_response_code(200);
echo 'ok';
if (function_exists('fastcgi_finish_request')) {
fastcgi_finish_request(); // PHP-FPM: send the 200 now, keep working
}
// Your idempotent handler, keyed on $payload['ref_id'].
// $payload['test'] is true only on a test-order callback.
handle_kaybs_callback($payload);
Python (Flask)
import hashlib
import hmac
import json
import os
import time
from flask import Flask, request
app = Flask(__name__)
API_KEY = os.environ["KAYBS_API_KEY"].encode()
MAX_SKEW_MS = 5 * 60 * 1000
@app.post("/kaybs/callback")
def kaybs_callback():
raw = request.get_data() # exact bytes; never sign request.json
timestamp = request.headers.get("X-Timestamp", "")
received = request.headers.get("X-Signature", "")
if not (timestamp.isascii() and timestamp.isdigit()) or abs(time.time() * 1000 - int(timestamp)) > MAX_SKEW_MS:
return "stale timestamp", 401
expected = hmac.new(API_KEY, raw + timestamp.encode(), hashlib.sha256).hexdigest()
if not hmac.compare_digest(expected.encode(), received.encode()):
return "bad signature", 401
try:
payload = json.loads(raw)
except ValueError:
return "invalid json", 400
enqueue_callback(payload) # your async, idempotent handler keyed on payload["ref_id"]
return "ok", 200
Check a signature by hand
Paste a callback your server received to see the signature it should carry.
Callback IP addresses
Also allow our callback IP addresses through your firewall. Whitelist all three — a callback may be delivered from any of them:
- 208.77.246.240
- 208.77.246.241
- 208.77.246.242
Test callbacks
A test order ("test": true or "test": "failed") sends one callback to your URL shortly after the response, with no retries. It is signed exactly like a real one and carries one extra field, "test": true, which never appears on a real callback:
{
"ref_id": "TEST-0001",
"status": "success",
"product_code": "MLBB-86",
"product_name": "Mobile Legends 86 Diamonds",
"price": 725,
"serial_number": "TEST-4K9QZ2M7XA",
"message": "Order completed",
"failure_code": null,
"failure_reason": null,
"quantity": 1,
"units": [],
"test": true
}A "test": "failed" order calls back with "status": "failed", "serial_number": null, "failure_code": "TEST_FAILURE" and "failure_reason": "Simulated failure (test order)". Make sure your handler never delivers or refunds anything for a callback with "test": true.
Serial Number Format
The serial_number always begins with our branded KAYBS- reference (KAYBS- plus 10 characters). For voucher products the redeemable code follows it after a /. Depending on the upstream supplier, a supplier reference starting with ALG- may sit in between, and some vouchers are delivered in two parts (for example a PIN and a password, or a serial and a PIN):
{
"ref_id": "R-99001",
"status": "success",
"product_code": "STEAMPHP-500",
"product_name": "Steam Voucher PHP 500",
"price": 520,
"serial_number": "KAYBS-A7B2C3D4EF/ALG-KF97TR2F5P/STEAMPH-9XQ2-K7MP-44TZ",
"message": "Order completed",
"failure_code": null,
"failure_reason": null,
"quantity": 1,
"units": []
}Drop our reference, keep every remaining part
Split the serial on /, drop the first segment (our KAYBS- reference) and a leading ALG- supplier reference, and give your customer every remaining segment. Taking only the last segment hands a two-part voucher’s buyer half a credential.
function voucherParts(serial) {
const parts = serial.split('/').slice(1); // drop our KAYBS- reference
if (parts[0] && /^ALG-[A-Z0-9]+$/i.test(parts[0])) parts.shift(); // supplier reference
return parts; // [] means an instant top-up: nothing to redeem
}For instant/direct products there is no / at all — the value is a branded reference only, since the top-up is delivered straight to the target account. For a combo order, read each unit’s serial_number in units; the order-level serial_number joins them with , .
Retry Policy
A delivery counts as successful only when your server answers with a 2xx status. Any other status (3xx, 4xx, 5xx), a connection error, or a timeout after 5 seconds triggers an automatic retry:
Retry Schedule
| Parameter | Required | Description |
|---|---|---|
Attempt 1 | No | Immediate — sent right after order reaches terminal state. |
Attempt 2 | No | 5 seconds after the first attempt. |
Attempt 3 | No | 15 seconds after the first attempt. |
Attempt 4 (Final) | No | 30 seconds after the first attempt. |
Make serial_number nullable, not just optional
serial_number is null on every non-success status — the key is always present, with a
null value. A validator that accepts “missing or string” (for example Zod’s .optional()
without .nullable()) rejects the whole body, so your endpoint refuses exactly the callbacks
that tell you an order FAILED while success callbacks keep arriving normally — the failure is
invisible from both ends until someone reads delivery logs.
Permanently Failed
If all 4 attempts fail, the callback is marked as permanently failed. Our worker will not retry again automatically.
You have two options:
- Resend from your dashboard — Open Orders, click the failed order, then “Resend Callback”. A resend is limited to once every 30 minutes per order; sooner returns
429with aretry_after_secondsfield. - Poll manually — Use the
GET /api/v1/order-status?ref_id=...endpoint to fetch the current order status.