Skip to content
YusrDocs

Realtime#

Realtime pushes payment events to a browser or server over a WebSocket, the instant they happen. Use it to flip your checkout page from "Waiting for your transfer" to "Payment received" without polling and without the customer refreshing.

The socket carries exactly the same events and payloads as webhooks. The difference is who listens:

WebhooksRealtimePolling
ListenerYour serverA browser, app or serverYour code, on a timer
DeliveryPushed, signed, retried for about 22 hoursPushed while connectedPulled
Best forFulfilling ordersLive checkout UX, ops dashboardsScripts, fallbacks

How it works#

Your server creates the transaction and a client token#

A client token (ct_…) is a short-lived credential that can only read one transaction. It expires after 30 minutes, so it's safe to send to the browser. Your secret key never leaves your server.

The browser subscribes#

The checkout page opens a socket with the client token and subscribes to the channel transaction:<id>. On every (re)connection it receives the transaction's current state.

Yusr pushes events#

When the transfer arrives, the socket receives a transaction.paid event (or underpaid, overpaid, expired and so on) within moments of the webhook being created.

Create a client token#

curl -X POST https://api.yusr.ng/v1/transactions/txn_01JA9Q3K7M2V8X4N6P0R2T5W7Y/client-token \
  -H "Authorization: Bearer $YUSR_SECRET_KEY"

The API responds with 201 Created:

JSON
{
  "object": "client_token",
  "token": "ct_eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ0eG5fMDFKQTlRM0s3TTJWOFg0TjZQMFIyVDVXN1kifQ.4mT9yq0pV8sQkX2bN6cL1rD5fH3jW7zA0eG9uK2oP4s",
  "transaction": "txn_01JA9Q3K7M2V8X4N6P0R2T5W7Y",
  "expires_at": "2026-10-06T14:30:00.000Z"
}

Create a token whenever you render the checkout page. If the customer is still on the page after 30 minutes, ask your server for a fresh one.

Use @yusr/js in the browser#

@yusr/js is a small browser library that handles the socket for you: it connects, subscribes, reconnects with backoff and re-subscribes, and always hands you the latest state.

Shell
npm install @yusr/js

Drop-in payment widget#

renderPaymentWidget renders an accessible "Pay by bank transfer" card with copy buttons, an expiry countdown and a live status that switches to Payment received when the money arrives.

Here is a complete checkout page. Your server renders it with the transaction and a fresh client token:

HTML
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Pay for order #1042 · Acme Stores</title>
  </head>
  <body>
    <main>
      <h1>Pay for order #1042</h1>
      <p>Transfer the exact amount below from any Nigerian bank app.</p>
      <div id="pay"></div>
    </main>

    <!-- Rendered by your server: never put your secret key here. -->
    <script>
      window.CHECKOUT = {
        transactionId: 'txn_01JA9Q3K7M2V8X4N6P0R2T5W7Y',
        clientToken: 'ct_…',
        transaction: {/* the transaction object returned by POST /v1/transactions */},
      };
    </script>
    <script src="https://unpkg.com/@yusr/js@1/dist/yusr.global.js"></script>
    <script>
      const { transactionId, clientToken, transaction } = window.CHECKOUT;

      Yusr.renderPaymentWidget('#pay', {
        clientToken,
        transactionId,
        transaction, // renders instantly; live state replaces it once connected
        baseUrl: 'https://api.yusr.ng',
        onPaid: () => {
          // UX only: your webhook handler is what actually fulfils the order.
          window.location.href = '/orders/1042/thank-you';
        },
        onError: (err) => {
          if (err.fatal) console.warn('Live updates stopped:', err.code);
        },
      });
    </script>
  </body>
</html>

Theme the widget with CSS variables such as --yusr-accent and --yusr-radius, or hide it and build your own UI with the subscription below. Displaying payment details has layout guidance for custom designs.

Your own UI#

subscribeToTransaction gives you the state and events and leaves rendering to you.

JavaScript
import { subscribeToTransaction, formatNaira } from '@yusr/js';

const sub = subscribeToTransaction({
  clientToken,
  transactionId,
  baseUrl: 'https://api.yusr.ng',
  onState(txn) {
    // The current state on every (re)connect, then after each event. Never goes backwards.
    statusEl.textContent = txn.status;
    receivedEl.textContent = formatNaira(txn.amount_received);
  },
  onEvent(evt) {
    // Same payload as the webhook body: { id, type, created_at, mode, data: { transaction } }
    if (evt.type === 'transaction.paid' || evt.type === 'transaction.overpaid') showSuccess();
  },
  onStatusChange(status) {
    // 'connecting' | 'connected' | 'reconnecting' | 'disconnected'
    connectionBadge.dataset.state = status;
  },
  onError(err) {
    // err.fatal === true means the subscription stopped, for example because the token expired.
    if (err.fatal) refreshTokenAndResubscribe();
  },
});

// When the customer leaves the page:
sub.unsubscribe();

Listen on your server#

A server can subscribe with its secret key, either to one transaction or to the merchant channel, which receives every event for your account in that mode. This is handy for an internal operations screen or a point-of-sale display.

# Realtime is a WebSocket protocol, which curl can't speak.
# Use the event log for the same events over plain HTTP:
curl -G https://api.yusr.ng/v1/events \
  -H "Authorization: Bearer $YUSR_SECRET_KEY" \
  --data-urlencode "limit=10"

Protocol reference#

Realtime runs on Socket.IO (protocol v4), so any Socket.IO client works. Use this reference to integrate without @yusr/js.

Connect#

SettingValue
URLThe API origin, wss://api.<your domain> (no /v1 in the URL)
Socket.IO path/v1/realtime
transports["websocket"]
auth{ "token": "<client token or secret key>" }

A client token (ct_…) can subscribe only to its own transaction. A secret key (sk_test_… or sk_live_…) can subscribe to any transaction and to merchant, and must only be used from servers. An invalid or expired token fails the handshake with a connect_error whose message is authentication_failed. Each account can hold up to 500 open connections; beyond that, new connections fail with rate_limited.

JavaScript
import { io } from 'socket.io-client';

const socket = io('https://api.yusr.ng', {
  path: '/v1/realtime',
  transports: ['websocket'],
  auth: { token: clientToken },
});

socket.on('connect_error', (err) => console.error(err.message)); // "authentication_failed"

Subscribe#

Emit subscribe with a channel and an acknowledgement callback:

ChannelWho may subscribeReceives
transaction:<id>Client token for that transaction, or a secret keyEvents for one transaction
merchantSecret key onlyEvery event for the account, in the key's mode
JavaScript
socket.on('connect', () => {
  // Subscribe on every (re)connect: subscriptions don't survive a reconnection.
  socket.emit('subscribe', { channel: `transaction:${transactionId}` }, (ack) => {
    if (!ack.ok) return console.error(ack.error.code, ack.error.message);
    render(ack.transaction); // the current state, so nothing is missed while offline
  });
});

A successful acknowledgement for a transaction channel includes the current transaction:

JSON
{
  "ok": true,
  "channel": "transaction:txn_01JA9Q3K7M2V8X4N6P0R2T5W7Y",
  "transaction": {
    "id": "txn_01JA9Q3K7M2V8X4N6P0R2T5W7Y",
    "object": "transaction",
    "status": "pending"
  }
}

(The transaction field holds the complete transaction object; it's shortened here.) For merchant the acknowledgement is { "ok": true, "channel": "merchant" }. Failures look like this:

JSON
{
  "ok": false,
  "error": {
    "code": "permission_denied",
    "message": "Client tokens can only subscribe to their transaction."
  }
}
Error codeCause
permission_deniedA client token tried to subscribe to merchant or to another transaction.
invalid_requestThe channel isn't merchant or transaction:<id>.
not_foundNo such transaction for this account and mode.
internal_errorTemporary failure. Retry the subscription.

To stop receiving a channel, emit unsubscribe with { "channel": "…" }; the acknowledgement is { "ok": true }.

Receive events#

The server emits event with a payload identical to the webhook body:

JavaScript
socket.on('event', (evt) => {
  // { id, type, created_at, mode, data: { transaction } }
  if (evt.data.transaction?.id === transactionId) render(evt.data.transaction);
});

Events are not signed on the socket, because the connection itself is authenticated. Deduplicate by id if you act on them, as you would with webhooks.

Connection lifecycle#

  • The server pings every 25 seconds; Socket.IO clients answer automatically. Dead connections are dropped.
  • After a reconnect, subscribe again. The acknowledgement carries the latest state, which covers any event you missed while disconnected.
  • When a client token expires, the next connection attempt fails with authentication_failed. Fetch a new token from your server and reconnect.
  • Close the socket when the customer leaves the checkout page.

Testing realtime in the sandbox#

Open your checkout page with a test transaction, then simulate a payment from the dashboard or the API. The page receives the same event a real transfer would produce.