Nice Paydocs API version 2026-12-01 OpenAPI

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

FieldNotes
urlHTTPS, port 443 or 8443, a public host name
event_typesoptional list of event types; empty means all
descriptionoptional, 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.

runs in CI 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

  1. 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.
  2. Answer 2xx fast, then do the work. Anything but 2xx within 10 seconds is a failed delivery and is retried.
  3. Be idempotent on the event id. A retried or redelivered event has the same id (NP-Delivery-Id changes per attempt; NP-Event-Id does not).
  4. Do not assume order. Events can arrive out of order. Use sequence, or fetch the object.
  5. Before giving value, fetch the object by id. The SDKs' handlePayinEvent fetches the pay-in again and calls your function only when it really succeeded.
runs in CI 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)}`);
});

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.

The signature

Text
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…

Webhook test vectors, also generated by our server and passed by both SDKs:

VectorExpectedWhy
validvalidSigned by the current key, verified 10 seconds later.
valid-previous-keyvalidDuring a rotation the JWKS holds two keys; an event signed by either verifies.
valid-unicode-and-spacesvalidThe raw body as received, including non-ASCII and double spaces: never parse and re-serialise before verifying.
valid-fields-reorderedvalidThe header's fields may come in any order.
tampered-bodyrefuse invalid_signatureOne character of the body changed.
reserialised-bodyrefuse invalid_signatureThe body parsed and serialised again (here: with indentation) no longer matches.
timestamp-changedrefuse invalid_signaturet in the header changed after signing.
too-oldrefuse timestamp_out_of_rangeOlder than 300 seconds: refuse even though the signature is good.
too-far-in-futurerefuse timestamp_out_of_rangeMore than 300 seconds ahead of the verifier's clock.
unknown-keyrefuse unknown_keyA kid that is not in the JWKS (refetch the JWKS once, then refuse).
missing-signaturerefuse malformed_headerNo sig field.
not-a-numberrefuse malformed_headert is not an integer.

The event

JSON
{
  "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 typeWhat to do when you receive it
payin.createdInformational. Nothing to credit yet.
payin.processingInformational: a reference was submitted, a provider reported progress, or a transfer is seen but unconfirmed. Do not credit yet.
payin.succeededRe-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.failedShow the customer it failed. Keep the order open to money: a late payment still succeeds.
payin.expiredThe customer's time ran out. Do not cancel the order on your side for good — late money still succeeds.
payin.cancelledCancelled by you. Late money can still succeed it.
payin.reversedA credited pay-in was not real money (e.g. a clawback). Reverse your credit by reversed_amount.
crypto.transfer.detectedInformational: an on-chain transfer is seen but not confirmed. Never credit on this event.
crypto.transfer.confirmedA 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.processingThe payout is on its way or under review. Never pay the customer again by another route.
payout.sentSent to the bank or chain; reference may be set. Still not final.
payout.succeededPaid. Mark the withdrawal complete.
payout.failedNot paid; the amount and fee are back in your balance. Tell the customer or try another destination with a new merchant_payout_id.
payout.reversedPaid, then returned by the bank. The amount is back in your balance; contact the customer.
settlement.approvedYour settlement request was approved.
settlement.paidYour settlement was sent to your destination.
settlement.completedYour settlement is complete.
settlement.rejectedYour settlement was rejected; the amount is back in your balance.
topup.succeededYour prefunding arrived and is in your balance.
balance.releasedPending money became available.
merchant.frozenYour account was frozen: new payouts and settlement requests are refused with merchant_not_active until it is unfrozen. Contact your account manager.
merchant.unfrozenYour account is active again.
webhook_endpoint.disabledAn endpoint failed for 3 days and was disabled. Fix it, re-enable it, and catch up with GET /v1/events.
report.readyThe report is ready: fetch it and download from download_url (short-lived).

Delivery and retries

Catch up after downtime

Webhooks and the event log are the record. After an outage, read every event after the last sequence you processed:

runs in CI 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)}`);

Mistakes that lose money