Skip to content

About

Unofficial Bank 131 API client for Bun and Node

Resources

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

bank131-sdk

English · Русский

TypeScript client for the Bank 131 API. Runs on Bun and Node.js 22+.

  • Signed REST (RSA-SHA256, PKCS#1 v1.5) with the exact JSON bytes you send
  • Session payments and payouts, FPS, tokens, reports, NPD, webhooks
  • Browser widgets from bank131-sdk/widgets (Bank CDN; no partner private key)

Not an official Bank 131 package. Official PHP SDK: bank131/php-sdk.

Install

bun add bank131-sdk
# or
npm install bank131-sdk

Quick start

FPS (СБП) payment: create a session, confirm it, then take the QR / qr.nspk.ru link from action_required (or from sessions.status if you poll).

import { Bank131, Bank131ApiError } from "bank131-sdk";

const bank = new Bank131({
  project: process.env.BANK131_PROJECT!,
  privateKey: process.env.BANK131_PRIVATE_KEY_PEM!,
  bankPublicKey: process.env.BANK131_BANK_PUBLIC_KEY_PEM,
  environment: "demo", // "live" → https://proxy.bank131.ru
});

const created = await bank.payments.init(
  {
    payment_details: {
      type: "faster_payment_system",
      faster_payment_system: { description: "Order 42" },
    },
    amount_details: { amount: 10000, currency: "rub" }, // 100 RUB in kopecks
    payment_options: { return_url: "https://example.com/return" },
    customer: { reference: "user-123" },
  },
  { idempotencyKey: "order-42-pay" },
);

const sessionId = (created.session as { id?: string } | undefined)?.id;

// After webhook `ready_to_confirm` (skip if the Bank auto-confirms):
try {
  await bank.sessions.confirm({ session_id: sessionId });
} catch (err) {
  if (err instanceof Bank131ApiError) {
    console.error(err.code, err.statusCode, err.message);
  }
  throw err;
}

function fpsQr(payload: unknown): { img?: string; content?: string } | undefined {
  const root = payload as {
    session?: { acquiring_payments?: Array<{ customer_interaction?: { inform?: { qr?: { img?: string; content?: string } } } }> };
    acquiring_payments?: Array<{ customer_interaction?: { inform?: { qr?: { img?: string; content?: string } } } }>;
  };
  const payments = root.session?.acquiring_payments ?? root.acquiring_payments ?? [];
  for (const payment of payments) {
    const qr = payment.customer_interaction?.inform?.qr;
    if (qr?.content || qr?.img) return qr;
  }
}

// Webhook `action_required`, raw body + X-PARTNER-SIGN:
const event = bank.webhooks.constructEvent(rawBody, signatureHeader);
const qr = fpsQr(event);
qr?.img;      // QR image (desktop)
qr?.content;  // https://qr.nspk.ru/... — deeplink / payload for your own QR

// Without webhooks, poll:
const status = await bank.sessions.status({ session_id: sessionId });
const polled = fpsQr(status);

qr.content is the NSPK pay link (typically https://qr.nspk.ru/...). Show qr.img as-is on desktop, or encode qr.content yourself using the NSPK QR rules. Do not parse and re-stringify the webhook body before constructEvent.

Config

Option Required Default Notes
project yes — X-PARTNER-PROJECT
privateKey yes — Partner PEM (PKCS#8 or PKCS#1)
bankPublicKey for webhooks — Bank PEM; demo and live are different files
environment no "live" "demo" → https://demo.bank131.ru
baseUrl no from environment Override host
apiVersion no "v1" "v2" remaps field names on the wire
timeout no 30000 ms
submerchant no — X-PARTNER-SUBMERCHANT
fetch no global fetch Inject for tests or custom TLS
ca no — Requires a custom fetch; default fetch cannot attach a CA

Per-request options (last argument): idempotencyKey (4–64 chars, never auto-generated), apiVersion, signal, method.

API surface

Public TypeScript types use v1 names (payment_method, payments, acquiring_payments). If apiVersion is "v2", the client remaps those keys on the wire and back. Paths that exist only as /api/v1/… always stay on v1.

Resource Methods
bank.sessions create, confirm, cancel, capture, refund, status, multiInit
bank.payments init, start, initSync
bank.payouts RKO / nominal / fiscalization create-init-start (incl. multi)
bank.fps banks (GET + signed {} body), customerVerification
bank.tokens create, info, tokenize, tokenizeElements
bank.sberpay push
bank.reports accountBalance, accountStatement
bank.wallet balance
bank.npd accruals, notifications, taxpayer checks, requestStatus
bank.recurrent disable
bank.calculate fee / amount preview
bank.request(path, body?, options?) any other method
bank.webhooks.constructEvent(rawBody, signature) verify + parse

Amounts are integers in kopecks (10000 = 100 RUB).

Recurring MIT

  1. First successful payment with payment_options.recurrent: true. Token arrives in payment_finished → acquiring_payments[].recurrent.token.
  2. Charge later with payment_details.type: "recurrent" and initiator: "merchant" (MIT; Bank default). CIT is initiator: "client" and needs 3-D Secure / return_url.

customer.reference on the MIT charge must be identical to the payment that issued the token. A new id (mit-… instead of the original sbp-…) is a common FPS failure: session/init/payment and ready_to_confirm succeed, token/info still shows is_active: true, then session/confirm finishes as provider_internal_error / session_cancelled. Same on API v1 and v2. Bank 131 support: send the original SBP reference, not a new one.

On the MIT ready_to_confirm webhook, payment_details.type often stays faster_payment_system when the token is FPS-backed. That is expected. Confirm the session; there is no payer QR on MIT.

FPS token with a charge (usual path): type: "faster_payment_system" + recurrent: true. Token without a charge: type: "faster_payment_system_binding", amount: 100 (1 RUB, not captured), recurrent: true.

import type { InitRecurrentPaymentRequest } from "bank131-sdk";

const customer = { reference: "sbp-15c37acf8f18" };

// Save token (FPS payment with charge):
await bank.payments.init({
  payment_details: {
    type: "faster_payment_system",
    faster_payment_system: { description: "Bind" },
  },
  amount_details: { amount: 1000, currency: "rub" },
  payment_options: {
    recurrent: true,
    return_url: "https://example.com/return",
  },
  customer,
});

// MIT charge — same customer.reference, not a new mit-… id:
const mit: InitRecurrentPaymentRequest = {
  payment_details: {
    type: "recurrent",
    recurrent: { token: "…", initiator: "merchant" },
  },
  amount_details: { amount: 1000, currency: "rub" },
  customer,
};

await bank.payments.init(mit);

await bank.tokens.info({
  type: "recurrent_token",
  recurrent_token: { token: "…" },
});

await bank.recurrent.disable({ recurrent: { token: "…" } });

Errors

All thrown errors extend Bank131Error:

Class When
Bank131ApiError HTTP ≥ 400 or body status === "error" (statusCode, code, details)
Bank131TransportError Network, timeout, non-JSON HTTP body
Bank131SignatureError Missing key or bad webhook signature
Bank131ValidationError Bad config, idempotency length, webhook JSON/shape
import { Bank131Error } from "bank131-sdk";

try {
  await bank.fps.banks();
} catch (err) {
  if (err instanceof Bank131Error) {
    // API, transport, signature, or validation
  }
}

Signing

Every request body is JSON.stringify (compact), signed with RSA-SHA256 PKCS#1 v1.5, Base64 in X-PARTNER-SIGN, and those same bytes are the HTTP body. ECDSA is not supported.

fps/banks is GET with a signed {} body. Node’s fetch cannot send GET bodies; the SDK uses node:http / node:https for GET/HEAD.

Webhooks

const event = bank.webhooks.constructEvent(rawBody, req.headers["x-partner-sign"]);

Pass the raw body. Do not JSON.parse then stringify before verify. Extra JSON keys are kept (Bank fields expand over time). Unknown type values still verify.

Reply HTTP 200. The Bank retries 4xx/5xx for up to 30 minutes. Documented sender IPs (not enforced by the SDK): 84.201.171.246, 84.252.136.174.

If webhooks are off, poll bank.sessions.status.

Widgets (bank131-sdk/widgets)

Server: bank.tokens.create({ acquiring_widget: { session_id } }) → public_token.
Browser: load Bank CSS/JS from the CDN, never the partner private key.

import { PaymentForm, SbpPayment, CardTokenizer, SberPayPayment } from "bank131-sdk/widgets";

await PaymentForm.create({ publicToken, environment: "demo" });

Demo host: https://widget-demo.bank131.ru. Live: https://widget.bank131.ru.

TLS (Russian CAs)

Bank 131 TLS needs the Russian Trusted Root + Sub CA from gosuslugi.ru/crt.

export NODE_EXTRA_CA_CERTS=/path/to/russian-trusted-ca.pem

ca on the client is not applied to the default fetch; pass a custom fetch or use NODE_EXTRA_CA_CERTS.

PCI DSS

Card PAN / CVC / expiry are in-scope for PCI. Prefer the payment form or tokenizer widget. This SDK does not log request bodies; do not add logging that dumps bank_card.

Development

bun install
bun test
bun run build

See CONTRIBUTING.md and AGENTS.md.

Bank docs

About

Unofficial Bank 131 API client for Bun and Node

Resources

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages