Skip to content
YusrDocs

SDKs and libraries#

The REST API works from any language that can send HTTPS requests. The official libraries save you the boilerplate: typed objects, automatic idempotency keys, safe retries, webhook verification and a polished payment widget for the browser.

LibraryPackageRuns onUse it for
Node.js@yusr/nodeNode.js 18+ (ESM and CommonJS)Your server: transactions, webhooks, events, settlements
Browser@yusr/jsBrowsers (and Node)Your checkout page: live status and the payment widget
PHPyusr/yusr-phpPHP 8.1+ with ext-curl and ext-jsonYour server, including Laravel
PythonUse requestsPython 3.9+Your server; see the recipe below

Every library talks to the same API, so you can mix them: for example a PHP backend with @yusr/js on the checkout page.

Node.js#

Install#

Shell
npm install @yusr/node

Configure#

JavaScript
import { Yusr } from '@yusr/node';
// CommonJS: const { Yusr } = require('@yusr/node');

const prisma = new Yusr(process.env.YUSR_SECRET_KEY, {
  baseUrl: 'https://api.yusr.ng', // or set the YUSR_API_BASE environment variable
  timeoutMs: 30_000, // per attempt
  maxRetries: 2, // network errors, 429 and 5xx on safe requests
});

Create a transaction and wait for payment#

JavaScript
const txn = await prisma.transactions.create({
  amount: 2_500_000, // ₦25,000.00 in kobo
  reference: 'order-1042',
  customer: { name: 'Ada Obi', email: 'ada@example.com' },
});

console.log(txn.payment.account_number, txn.payment.bank_name, txn.payment.amount);

// Optional: poll every 5 s until the status leaves "pending" (webhooks are the primary signal).
const final = await prisma.transactions.waitForPayment(txn.id, { intervalMs: 5000 });
console.log(final.status);

What it includes#

  • transactions: create, retrieve, list, listAutoPaging, findByReference, cancel, createClientToken, waitForPayment
  • sandbox.simulate for test-mode payments
  • webhookEndpoints and events, plus Yusr.webhooks.constructEvent / verify for signature checks
  • settlements, balance and banks
  • Amount helpers toKobo, fromKobo and formatNaira
  • Typed errors (see Errors) and full TypeScript types

Next: verify webhooks, poll safely, stream updates.

Browser: @yusr/js#

@yusr/js keeps your checkout page in sync with the payment as it happens, using short-lived client tokens so your secret key never reaches the browser.

Install#

Shell
npm install @yusr/js

Or load it with a script tag, which exposes a global Yusr:

HTML
<script src="https://unpkg.com/@yusr/js@1/dist/yusr.global.js"></script>

Drop-in payment widget#

Create the transaction and a client token on your server, then render the widget. It shows the amount, account number with a copy button, bank, account name, an expiry countdown and a live, screen-reader-friendly status.

HTML
<div id="pay"></div>
<script src="https://unpkg.com/@yusr/js@1/dist/yusr.global.js"></script>
<script>
  // transactionId, clientToken and transaction come from your server
  const { transactionId, clientToken, transaction } = window.CHECKOUT;
  Yusr.renderPaymentWidget('#pay', {
    clientToken,
    transactionId,
    transaction,
    baseUrl: 'https://api.yusr.ng',
    onPaid: () => (window.location.href = '/order/complete'),
  });
</script>

Build your own UI#

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

const sub = subscribeToTransaction({
  clientToken,
  transactionId,
  baseUrl: 'https://api.yusr.ng',
  onState(txn) {
    // Current state on every (re)connect, then after each event.
    statusEl.textContent = txn.status;
    receivedEl.textContent = formatNaira(txn.amount_received);
  },
  onError(err) {
    if (err.fatal) console.warn('Live updates stopped:', err.code);
  },
});

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

Theming#

The widget injects one small stylesheet (turn it off with injectStyles: false). Override its CSS variables to match your brand:

.yusr-widget {
  --yusr-accent: #0f766e;
  --yusr-bg: #ffffff;
  --yusr-fg: #0f172a;
  --yusr-muted: #64748b;
  --yusr-border: #e2e8f0;
  --yusr-radius: 16px;
  --yusr-font: 'Inter', system-ui, sans-serif;
}

The root element also carries data-status (pending, paid, expired …) and data-tone (neutral, success, warning, danger) for your own styles. See Realtime for a complete checkout page.

PHP#

Install#

Shell
composer require yusr/yusr-php

Requires PHP 8.1 or newer with the curl and json extensions.

Configure and create a transaction#

PHP
<?php
use Yusr\Money;
use Yusr\YusrClient;

$prisma = new YusrClient(getenv('YUSR_SECRET_KEY'), [
    'baseUrl' => 'https://api.yusr.ng', // or set YUSR_API_BASE
    'timeout' => 30,
    'maxRetries' => 2,
]);

$txn = $prisma->transactions->create([
    'amount' => 2500000, // ₦25,000.00 in kobo
    'reference' => 'order-1042',
    'customer' => ['name' => 'Ada Obi', 'email' => 'ada@example.com'],
]);

echo $txn['payment']['account_number'], PHP_EOL;
echo Money::format($txn['payment']['amount']), PHP_EOL; // ₦25,000.00

Responses are associative arrays that mirror the API's JSON. The client offers transactions, sandbox, webhookEndpoints, events, settlements, balance and banks, with auto-pagination through autoPagingIterator().

Laravel webhook route#

PHP
<?php
// routes/api.php
use Illuminate\Http\Request;
use Yusr\Exception\SignatureVerificationException;
use Yusr\Webhook;

Route::post('/webhooks/yusr', function (Request $request) {
    try {
        $event = Webhook::constructEvent(
            $request->getContent(), // the raw body
            (string) $request->header('X-Yusr-Signature', ''),
            (string) $request->header('X-Yusr-Timestamp', ''),
            config('services.yusr.webhook_secret'),
        );
    } catch (SignatureVerificationException $e) {
        return response('invalid signature', 400);
    }

    if ($event['type'] === 'transaction.paid') {
        dispatch(new \App\Jobs\FulfilOrder($event['data']['transaction']));
    }

    return response()->noContent();
});

Routes in routes/api.php skip Laravel's CSRF check. If you register the route in routes/web.php, exclude it from CSRF verification.

Python#

There is no official Python library yet. The API is small enough that a thin wrapper around requests covers everything:

Python
import os
import uuid
from typing import Optional

import requests


class YusrClient:
    def __init__(self, secret_key: str, base_url: str = "https://api.yusr.ng/v1"):
        self.base_url = base_url.rstrip("/")
        self.session = requests.Session()
        self.session.headers["Authorization"] = f"Bearer {secret_key}"

    def request(self, method: str, path: str, *, json=None, params=None, idempotency_key=None):
        headers = {"Idempotency-Key": idempotency_key} if idempotency_key else {}
        res = self.session.request(
            method, f"{self.base_url}{path}", json=json, params=params, headers=headers, timeout=30
        )
        body = res.json()
        if not res.ok:
            error = body["error"]
            raise RuntimeError(f"{error['code']}: {error['message']} (request {error.get('request_id')})")
        return body

    def create_transaction(self, params: dict, idempotency_key: Optional[str] = None) -> dict:
        return self.request(
            "POST", "/transactions", json=params, idempotency_key=idempotency_key or str(uuid.uuid4())
        )

    def retrieve_transaction(self, transaction_id: str) -> dict:
        return self.request("GET", f"/transactions/{transaction_id}")


prisma = YusrClient(os.environ["YUSR_SECRET_KEY"])
txn = prisma.create_transaction(
    {
        "amount": 2500000,
        "reference": "order-1042",
        "customer": {"name": "Ada Obi", "email": "ada@example.com"},
    },
    idempotency_key="checkout-order-1042",
)
print(txn["payment"]["account_number"], txn["payment"]["bank_name"])

For webhook signature verification in Python, use the standard-library function in Webhooks.

OpenAPI#

The API is described by an OpenAPI 3.1 document. Use it to generate a client in another language, import requests into an API tool, or validate your mocks:

Shell
curl https://api.yusr.ng/v1/openapi.json

The API reference is rendered from the same document.