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.ts";
interface Message {
readonly op?: "ready" | "live" | "ping";
readonly object?: string;
readonly id?: string;
readonly type?: string;
readonly sequence?: number;
readonly data?: { readonly object: Readonly<Record<string, unknown>> };
}
const wanted = Number(process.argv[2] ?? "3");
const types = ["payin.created", "payin.succeeded"];
let received = 0;
let lastSequence: number | null = null; // the last event handled; a reconnect resumes after it
let attempts = 0;
let done = false;
async function connect(): Promise<void> {
// A token works once and lives 60 seconds: ask for a new one for every connection.
const token = await nicepay<{ token: string; url: string }>("POST", "/v1/stream/tokens", { body: { types } });
const socket = new WebSocket(`${token.url}${token.url.includes("?") ? "&" : "?"}token=${encodeURIComponent(token.token)}`);
socket.addEventListener("open", () => {
attempts = 0;
// After a disconnect: replay what was missed, then go live.
if (lastSequence !== null) socket.send(JSON.stringify({ op: "resume", after_sequence: lastSequence }));
});
socket.addEventListener("message", (m) => {
const msg = JSON.parse(String(m.data)) as Message;
if (msg.op === "ping") {
socket.send(JSON.stringify({ op: "pong" })); // every 20 seconds
} else if (msg.op === "ready" && lastSequence === null) {
lastSequence = msg.sequence ?? null; // live from here
console.log("live");
} else if (msg.object === "event" && typeof msg.sequence === "number" && (lastSequence === null || msg.sequence > lastSequence)) {
lastSequence = msg.sequence;
received += 1;
console.log(`#${String(msg.sequence)} ${String(msg.type)} ${String(msg.data?.object["id"])}`);
if (received >= wanted) {
done = true;
socket.close(1000, "done");
}
}
});
socket.addEventListener("close", () => {
if (!done) reconnect();
});
}
/** After a disconnect: wait (back-off with jitter), then a new token and a new connection; "resume" picks up where the last one stopped. */
function reconnect(): void {
const wait = Math.min(30_000, 1000 * 2 ** attempts) * (0.5 + Math.random() / 2);
attempts += 1;
setTimeout(() => {
connect().catch((error: unknown) => {
console.error("stream error", error);
reconnect();
});
}, wait);
}
await connect();How it works
POST /v1/stream/tokensReference
- Scope:
events:read - 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 example above does all of this with the platform's own WebSocket: a new token per connection, pongs, reconnecting with back-off, and resuming after the last sequence it handled. There is no PHP example: PHP request handlers are not long-lived; use webhooks.