Webhooks
We send every event to your endpoint as an HTTPS POST with a JSON body, signed with our Ed25519 key. This is how you learn that money arrived — and the page that keeps you from crediting a customer twice, or for money that never came.
Register an endpoint
POST /v1/webhook-endpointsReference
- Scope:
webhooks:write - SDK:
createWebhookEndpoint() - Success: HTTP 201
| Field | Notes |
|---|---|
url | HTTPS, port 443 or 8443, a public host name |
event_types | optional list of event types; empty means all |
description | optional, at most 200 characters |
One endpoint per project and mode is typical, and test and live have separate endpoints. A project can have at most 10 enabled endpoints per mode (403 limit_exceeded). A new endpoint is enabled; after 3 days of failed deliveries it becomes disabled.
samples/ts/register-webhook.ts// Register your webhook endpoint (once per project and mode).
// bun register-webhook.ts https://shop.example/nicepay/webhooks
import { NicePay } from "@nicepay/sdk-ts";
const nicepay = new NicePay({
keyId: process.env["NICEPAY_KEY_ID"] ?? "",
secret: process.env["NICEPAY_KEY_SECRET"] ?? "",
...(process.env["NICEPAY_API_BASE"] ? { baseUrl: process.env["NICEPAY_API_BASE"] } : {}),
});
const url = process.argv[2];
if (!url) throw new Error("usage: register-webhook.ts <https URL>");
const existing = await nicepay.listWebhookEndpoints();
const endpoint =
existing.data.find((e) => e.url === url) ??
(await nicepay.createWebhookEndpoint({
url,
// Empty means every event type; list them to receive fewer.
event_types: ["payin.succeeded", "payin.failed", "payin.expired", "payin.reversed", "payout.succeeded", "payout.failed", "payout.reversed", "webhook_endpoint.disabled"],
description: "production wallet service",
}));
console.log(`endpoint ${endpoint.id} ${endpoint.status} → ${endpoint.url}`);The five rules
- Verify the signature on the raw body. Read the body as bytes, verify, and only then parse. Never verify a parsed and re-serialised copy.
- Answer
2xxfast, then do the work. Anything but2xxwithin 10 seconds is a failed delivery and is retried. - Be idempotent on the event
id. A retried or redelivered event has the sameid(NP-Delivery-Idchanges per attempt;NP-Event-Iddoes not). - Do not assume order. Events can arrive out of order. Use
sequence, or fetch the object. - Before giving value, fetch the object by id. The SDKs'
handlePayinEventfetches the pay-in again and calls your function only when it really succeeded.
samples/ts/webhook-server.ts samples/php/webhook.php// A webhook endpoint that follows the five rules: verify the signature on the raw body,
// answer 2xx fast, be idempotent on the event id, don't trust order, and re-fetch the
// pay-in before giving value.
// bun webhook-server.ts 8080
import { createServer } from "node:http";
import { NicePay, WebhookSignatureError, type Event } from "@nicepay/sdk-ts";
const nicepay = new NicePay({
keyId: process.env["NICEPAY_KEY_ID"] ?? "",
secret: process.env["NICEPAY_KEY_SECRET"] ?? "",
...(process.env["NICEPAY_API_BASE"] ? { baseUrl: process.env["NICEPAY_API_BASE"] } : {}),
});
// In production these two are tables in YOUR database, each with a unique key:
// processed_events(event_id) and credited_payins(payin_id). Insert into credited_payins
// in the same transaction as the wallet credit; a duplicate insert means "already done".
const processedEvents = new Set<string>();
const creditedPayins = new Map<string, string>();
async function handle(event: Event): Promise<void> {
if (processedEvents.has(event.id)) return; // rule 3: idempotent on the event id
// Rule 5: handlePayinEvent fetches the pay-in again and calls back only if it succeeded.
await nicepay.handlePayinEvent(event, (payin) => {
if (!creditedPayins.has(payin.id)) {
// the unique key on the pay-in id
creditedPayins.set(payin.id, payin.amount_received); // credit what actually arrived
console.log(`credited ${payin.id} ${payin.amount_received} ${payin.currency} to ${String(payin.customer.ref)}`);
}
return Promise.resolve();
});
processedEvents.add(event.id);
}
const port = Number(process.argv[2] ?? "8080");
createServer((req, res) => {
const chunks: Buffer[] = [];
req.on("data", (c: Buffer) => chunks.push(c));
req.on("end", () => {
const raw = Buffer.concat(chunks); // rule 1: the raw bytes, not a parsed copy
nicepay
.constructEvent(raw, req.headers["np-signature"] as string | undefined)
.then((event) => {
res.writeHead(200).end(); // rule 2: answer fast, work after
console.log(`event ${event.type} #${String(event.sequence)} ${event.id}`);
return handle(event);
})
.catch((error: unknown) => {
if (error instanceof WebhookSignatureError) {
res.writeHead(400).end();
console.log(`refused: ${error.reason}`);
return;
}
// Not answered yet → 500 and Nice Pay retries; answered → log it and let the retry or catch-up handle it.
if (!res.headersSent) res.writeHead(500).end();
console.error(error);
});
});
}).listen(port, () => {
console.log(`listening on ${String(port)}`);
});<?php
// A wallet top-up webhook endpoint: verify, answer, credit exactly once.
// php -S 0.0.0.0:8080 webhook.php (behind your web server in production)
// WALLET_DB: a PDO DSN for your database (here SQLite, for the example).
declare(strict_types=1);
require 'vendor/autoload.php';
use NicePay\Exception\SignatureVerificationException;
$config = ['key_id' => getenv('NICEPAY_KEY_ID') ?: '', 'secret' => getenv('NICEPAY_KEY_SECRET') ?: ''];
if (getenv('NICEPAY_API_BASE')) {
$config['base_url'] = getenv('NICEPAY_API_BASE');
}
$nicepay = new NicePay\Client($config);
$db = new PDO(getenv('WALLET_DB') ?: 'sqlite:' . sys_get_temp_dir() . '/wallet.sqlite', null, null, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$db->exec('CREATE TABLE IF NOT EXISTS processed_events (event_id TEXT PRIMARY KEY)');
$db->exec('CREATE TABLE IF NOT EXISTS credited_payins (payin_id TEXT PRIMARY KEY, player TEXT NOT NULL, amount TEXT NOT NULL)');
$db->exec('CREATE TABLE IF NOT EXISTS wallets (player TEXT PRIMARY KEY, balance_minor INTEGER NOT NULL)');
// Rule 1: verify the signature on the raw body — exactly the bytes received.
$raw = file_get_contents('php://input');
try {
// cache_file keeps Nice Pay's public keys between requests (PHP starts fresh each time).
$event = $nicepay->webhooks(['cache_file' => sys_get_temp_dir() . '/nicepay-webhook-keys.json'])
->constructEvent($raw, $_SERVER['HTTP_NP_SIGNATURE'] ?? null);
} catch (SignatureVerificationException $e) {
http_response_code(400);
exit;
}
// Rule 3: idempotent on the event id (a retry of a delivery has the same id).
$fresh = $db->prepare('INSERT INTO processed_events (event_id) VALUES (?) ON CONFLICT DO NOTHING');
$fresh->execute([$event['id']]);
if ($fresh->rowCount() === 0) {
http_response_code(200);
exit;
}
// Rule 5: never credit from the event body. handlePayinEvent fetches the pay-in again
// and calls back only when it really succeeded.
try {
$nicepay->handlePayinEvent($event, static function (array $payin) use ($db): void {
$player = (string) $payin['customer']['ref'];
$minor = NicePay\Money::toMinor($payin['amount_received'], $payin['currency']); // what arrived, as an integer of that currency
$db->beginTransaction();
// The unique key on the pay-in id and the credit in ONE transaction: never twice.
$claim = $db->prepare('INSERT INTO credited_payins (payin_id, player, amount) VALUES (?, ?, ?) ON CONFLICT DO NOTHING');
$claim->execute([$payin['id'], $player, $payin['amount_received']]);
if ($claim->rowCount() === 1) {
$db->prepare('INSERT INTO wallets (player, balance_minor) VALUES (?, ?) ON CONFLICT (player) DO UPDATE SET balance_minor = balance_minor + excluded.balance_minor')
->execute([$player, $minor]);
}
$db->commit();
});
} catch (Throwable $e) {
// Not processed: forget the event id so the retry is handled, and answer 500.
$db->prepare('DELETE FROM processed_events WHERE event_id = ?')->execute([$event['id']]);
http_response_code(500);
exit;
}
// Rule 2: answer 2xx quickly (here the work above is one short transaction).
http_response_code(200);Credit exactly once
Every merchant needs this pattern: a unique key on the Nice Pay pay-in id in your own database, inserted in the same database transaction as the credit to your customer. If the insert conflicts, it was already credited: do nothing. The PHP sample above does exactly this with two tables; a retry, a redelivery and a race between two of your workers all end in one credit.
- Credit
amount_received, notamount. - For a USDT address without an invoice, each confirmed transfer is its own pay-in: three transfers, three pay-ins, three credits — each under its own id.
- For a USDT invoice, credit either each
crypto.transfer.confirmedor the finalpayin.succeeded, never both.
The signature
NP-Signature: t=1794900000,kid=wh_2026_11,sig=<base64 Ed25519 signature of "<t>.<raw body>">
NP-Event-Id: evt_01J…
NP-Delivery-Id: del_01J…- Our public keys are published as a JWKS at
https://api.mynicepanel.com/.well-known/webhook-keys.json. During a rotation it holds two keys;kidsays which one signed. The SDKs fetch and cache it, and fetch again (at most once a minute) when they see akidthey do not know. PHP has no memory between requests, so passcache_fileas the sample does. - Refuse a
tmore than 5 minutes from your clock. - The signing key lives in a hardware-backed key service; a leak of your database exposes nothing that can forge an event.
Webhook test vectors, also generated by our server and passed by both SDKs:
| Vector | Expected | Why |
|---|---|---|
valid | valid | Signed by the current key, verified 10 seconds later. |
valid-previous-key | valid | During a rotation the JWKS holds two keys; an event signed by either verifies. |
valid-unicode-and-spaces | valid | The raw body as received, including non-ASCII and double spaces: never parse and re-serialise before verifying. |
valid-fields-reordered | valid | The header's fields may come in any order. |
tampered-body | refuse invalid_signature | One character of the body changed. |
reserialised-body | refuse invalid_signature | The body parsed and serialised again (here: with indentation) no longer matches. |
timestamp-changed | refuse invalid_signature | t in the header changed after signing. |
too-old | refuse timestamp_out_of_range | Older than 300 seconds: refuse even though the signature is good. |
too-far-in-future | refuse timestamp_out_of_range | More than 300 seconds ahead of the verifier's clock. |
unknown-key | refuse unknown_key | A kid that is not in the JWKS (refetch the JWKS once, then refuse). |
missing-signature | refuse malformed_header | No sig field. |
not-a-number | refuse malformed_header | t is not an integer. |
The event
{
"id": "evt_01JD3QH2Y8ZKX4M9T6V0R1B2C3",
"object": "event",
"type": "payin.succeeded",
"livemode": true,
"api_version": "2026-12-01",
"sequence": 48213,
"created_at": "2026-11-23T10:00:00.000Z",
"data": { "object": { "id": "pi_01JD3QH2Y8ZKX4M9T6V0R1B2C3", "object": "payin", "status": "succeeded" } }
}data.object is the object exactly as the API returns it when the event was recorded: the same fields and the same public id — pi_… for a pay-in, po_… for a payout, st_… for a settlement, rep_… for a report, we_… for a webhook endpoint. Fetch it again with that id (GET/v1/settlements/{id} for a settlement event) to see its state now. (A report event carries no download_url: links are short-lived, so fetch the report for one.)
sequence is a gap-free, strictly increasing number per project and mode. Store the last one you processed: a gap means you missed something.
Event types
| Event type | What to do when you receive it |
|---|---|
payin.created | Informational. Nothing to credit yet. |
payin.processing | Informational: a reference was submitted, a provider reported progress, or a transfer is seen but unconfirmed. Do not credit yet. |
payin.succeeded | Re-fetch the pay-in; if it is succeeded, credit amount_received once (unique key on the pay-in id). Can arrive after failed/expired/cancelled: late money wins. |
payin.failed | Show the customer it failed. Keep the order open to money: a late payment still succeeds. |
payin.expired | The customer's time ran out. Do not cancel the order on your side for good — late money still succeeds. |
payin.cancelled | Cancelled by you. Late money can still succeed it. |
payin.reversed | A credited pay-in was not real money (e.g. a clawback). Reverse your credit by reversed_amount. |
crypto.transfer.detected | Informational: an on-chain transfer is seen but not confirmed. Never credit on this event. |
crypto.transfer.confirmed | A transfer to a customer's address confirmed and was credited to you. For an invoice, credit per transfer or on payin.succeeded — pick one. |
payout.processing | The payout is on its way or under review. Never pay the customer again by another route. |
payout.sent | Sent to the bank or chain; reference may be set. Still not final. |
payout.succeeded | Paid. Mark the withdrawal complete. |
payout.failed | Not paid; the amount and fee are back in your balance. Tell the customer or try another destination with a new merchant_payout_id. |
payout.reversed | Paid, then returned by the bank. The amount is back in your balance; contact the customer. |
settlement.approved | Your settlement request was approved. |
settlement.paid | Your settlement was sent to your destination. |
settlement.completed | Your settlement is complete. |
settlement.rejected | Your settlement was rejected; the amount is back in your balance. |
topup.succeeded | Your prefunding arrived and is in your balance. |
balance.released | Pending money became available. |
merchant.frozen | Your account was frozen: new payouts and settlement requests are refused with merchant_not_active until it is unfrozen. Contact your account manager. |
merchant.unfrozen | Your account is active again. |
webhook_endpoint.disabled | An endpoint failed for 3 days and was disabled. Fix it, re-enable it, and catch up with GET /v1/events. |
report.ready | The report is ready: fetch it and download from download_url (short-lived). |
Delivery and retries
POST, 10-second timeout, redirects are not followed. Any2xxis success.- Retries at roughly 30 s, 2 min, 10 min, 30 min, 1 h, 3 h, 6 h, 12 h, then every 12 h up to 72 h, with jitter. After that the delivery is
failed; redeliver it from the portal or withPOST/v1/events/{id}/redeliver. - An endpoint failing continuously for 3 days is disabled, your account owners are told, and
webhook_endpoint.disabledis recorded.
Catch up after downtime
Webhooks and the event log are the record. After an outage, read every event after the last sequence you processed:
samples/ts/catch-up.ts samples/php/catch-up.php// Catch up after downtime: read every event after the last sequence you processed.
// `sequence` is gap-free per project and mode, so a gap means you missed something.
// bun catch-up.ts 0
import { NicePay } from "@nicepay/sdk-ts";
const nicepay = new NicePay({
keyId: process.env["NICEPAY_KEY_ID"] ?? "",
secret: process.env["NICEPAY_KEY_SECRET"] ?? "",
...(process.env["NICEPAY_API_BASE"] ? { baseUrl: process.env["NICEPAY_API_BASE"] } : {}),
});
// In production: read it from your database, where your webhook handler stores it.
let lastSequence = Number(process.argv[2] ?? "0");
let seen = 0;
for (;;) {
const page = await nicepay.listEvents({ after_sequence: lastSequence, limit: 100 });
for (const event of page.data) {
if (event.sequence !== lastSequence + 1) console.log(`gap before #${String(event.sequence)}`);
// Handle it exactly as your webhook endpoint would (idempotent on event.id).
lastSequence = event.sequence;
seen += 1;
}
if (!page.has_more) break;
}
console.log(`caught up: ${String(seen)} events, last sequence ${String(lastSequence)}`);<?php
// Catch up after downtime: every event after the last sequence you processed.
// php catch-up.php 0
declare(strict_types=1);
require 'vendor/autoload.php';
$config = ['key_id' => getenv('NICEPAY_KEY_ID') ?: '', 'secret' => getenv('NICEPAY_KEY_SECRET') ?: ''];
if (getenv('NICEPAY_API_BASE')) {
$config['base_url'] = getenv('NICEPAY_API_BASE');
}
$nicepay = new NicePay\Client($config);
// In production: read it from your database, where your webhook handler stores it.
$lastSequence = (int) ($argv[1] ?? 0);
$seen = 0;
do {
$page = $nicepay->listEvents(['after_sequence' => $lastSequence, 'limit' => 100]);
foreach ($page['data'] as $event) {
if ($event['sequence'] !== $lastSequence + 1) {
echo "gap before #{$event['sequence']}\n";
}
// Handle it exactly as your webhook endpoint would (idempotent on $event['id']).
$lastSequence = $event['sequence'];
$seen++;
}
} while ($page['has_more']);
echo "caught up: {$seen} events, last sequence {$lastSequence}\n";Mistakes that lose money
- Crediting from the webhook body without fetching the pay-in, or without verifying the signature: anyone can post to your URL.
- No unique key on the pay-in id: a retry credits twice.
- Doing slow work before answering: the delivery times out, is retried, and if you are not idempotent you credit twice.
- Ignoring
webhook_endpoint.disabled: alert on it.