Live stream (WebSocket)
For a screen that should update the moment something happens — a cashier dashboard, a "waiting for your payment" page on your side — open a WebSocket and receive the same event envelopes as webhooks.
Note: the stream is a convenience and at most once: a disconnect can lose events. Anything that moves money runs from webhooks or from
GET/v1/events, never from the stream alone.
runs in CI
samples/ts/stream.ts// Live updates over WebSocket (e.g. for a cashier screen). A convenience: it may miss
// events, so anything that moves money still runs from webhooks or catch-up.
// bun stream.ts 3 print 3 events, then stop
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 wanted = Number(process.argv[2] ?? "3");
let received = 0;
const stream = nicepay.stream({
types: ["payin.created", "payin.succeeded"],
onEvent: (event) => {
received += 1;
console.log(`#${String(event.sequence)} ${event.type} ${String(event.data.object["id"])}`);
if (received >= wanted) stream.close();
},
onError: (error) => {
console.error("stream error", error);
},
});
// The SDK fetches a single-use token, answers pings, and after a disconnect
// reconnects with a new token and resumes after the last sequence it delivered.
await stream.start();
console.log("live");How it works
POST /v1/stream/tokensReference
- Scope:
events:read - SDK:
createStreamToken() - Success: HTTP 201
- Ask for a token; the optional
typeslimits the stream to those event types. The answer carries atokenand theurlto connect to. The token lives 60 seconds and works once. - Connect to
url?token=…. The server sends{"op":"ready","sequence":N}— live from sequence N. - To replay what you missed, send
{"op":"resume","after_sequence":N}: up to 10,000 events are replayed in order, then{"op":"live"}and live events follow. - The server sends
{"op":"ping"}every 20 seconds; answer{"op":"pong"}. - A consumer that does not keep up is closed with code 4008 rather than buffered without bound. Reconnect with a new token and resume.
The TypeScript SDK does all of this: tokens, pongs, reconnecting with back-off, and resuming after the last sequence it delivered. The PHP SDK has no stream client: PHP request handlers are not long-lived; use webhooks.