SDKs and CLI

Official server-side clients for TypeScript, PHP and Python, with the same resources and method names in every language, plus a command-line tool and the checkout.js popup script.

  • Zero runtime dependencies
  • Webhook verification built in
Install
npm i @paymentsnp/sdk
# or: pnpm add, yarn add or bun add @paymentsnp/sdk
composer require paymentsnp/paymentsnp-php
pip install paymentsnp
Version 1.0.0 of each SDK.

Packages

Official SDKs, version 1.0.0
LanguagePackageRegistryRequirements
TypeScript and JavaScript@paymentsnp/sdknpmNode 18+, Bun, Deno and edge runtimes
PHPpaymentsnp/paymentsnp-phpPackagistPHP 7.4+, ext-curl, ext-json
PythonpaymentsnpPyPIPython 3.9+, standard library only

The SDKs, plugins and the integration guide also download as ZIP files from Dashboard > Downloads for owners, administrators and developers.

TypeScript and JavaScript

  • Zero runtime dependencies. Uses the global fetch and Web Crypto, so it runs on Node 18+, Bun, Deno and edge runtimes such as Vercel Edge and Cloudflare Workers.
  • ESM and CommonJS builds with bundled TypeScript types.
  • Automatic retries with backoff, idempotent checkout creation and typed errors.
  • Webhook verification on Web Crypto, and the paymentsnp CLI.
import { Paymentsnp, toPaisa } from "@paymentsnp/sdk";

const pnp = new Paymentsnp({ apiKey: process.env.PAYMENTSNP_API_KEY! });

const session = await pnp.checkout.sessions.create({
  order_id: "ORD-1001",
  amount_minor: toPaisa("1,500.00"), // 150000 paisa
  currency: "NPR",
  success_url: "https://shop.example.com/thanks",
  cancel_url: "https://shop.example.com/cart",
});
// Redirect the customer to session.checkout_url, then wait for the
// payment.succeeded webhook (or poll checkout.sessions.retrieve).
new Paymentsnp({
  apiKey: "np_test_…",                       // required; must start with np_test_ or np_live_
  baseUrl: "https://api.paymentnp.com/v1",   // default
  timeoutMs: 30000,                          // per attempt
  maxRetries: 2,
  fetch: customFetch,                        // optional
});

CommonJS: const { Paymentsnp } = require("@paymentsnp/sdk");. Field names are the API's own snake_case names in both params and responses, so the API reference applies as-is.

PHP

PHP 7.4 or newer with ext-curl and ext-json, and no other dependencies. Responses are the API's JSON decoded to arrays.

<?php
$paymentsnp = new \Paymentsnp\PaymentsnpClient('np_test_...');

$session = $paymentsnp->checkout->sessions->create([
    'order_id' => 'ORD-1001',
    'amount_minor' => \Paymentsnp\Money::toPaisa('1,250.00'), // 125000
    'currency' => 'NPR',
    'customer' => ['email' => 'buyer@example.com', 'name' => 'Sita Sharma'],
    'success_url' => 'https://shop.example.com/orders/ORD-1001',
    'cancel_url' => 'https://shop.example.com/cart',
], ['idempotency_key' => 'checkout-ORD-1001']);

header('Location: ' . $session['checkout_url']);
<?php
// Without Composer (WHMCS modules and similar), copy the folder and:
require_once '/path/to/paymentsnp-php/init.php';

The init.php loader is what lets the SDK run inside hosts without Composer, such as WHMCS modules.

Python

Python 3.9 or newer, standard library only, and typed with py.typed and TypedDicts in paymentsnp.types. Responses are dicts with the API's field names.

from paymentsnp import Paymentsnp, to_paisa

client = Paymentsnp(api_key="np_test_...")

session = client.checkout.sessions.create(
    {
        "order_id": "ORD-1001",
        "amount_minor": to_paisa("1,250.00"),  # 125000
        "currency": "NPR",
        "customer": {"email": "buyer@example.com", "name": "Sita Sharma"},
        "success_url": "https://shop.example.com/orders/ORD-1001",
        "cancel_url": "https://shop.example.com/cart",
    },
    idempotency_key="checkout-ORD-1001",
)
print(session["checkout_url"])

import is a Python keyword, so the import methods are import_settlement and import_bulk, the same names the other SDKs use.

Methods and scopes

Every SDK covers the API-key routes. Method names are camelCase in TypeScript and PHP and snake_case in Python.

SDK resources
ResourceMethodsScopeRoutes
checkout.sessionscreate, retrieve, expirecheckout:create, checkout:readPOST and GET /v1/checkout/sessions
paymentslist, retrieve, summary, listRefundspayments:readGET /v1/payments
paymentsrefundrefunds:writePOST /v1/payments/:id/refunds
invoiceslist, retrieve, pdfinvoices:readGET /v1/invoices
invoicescreate, update, finalize, send, markPaid, void, markUncollectible, duplicateinvoices:writePOST and PATCH /v1/invoices
reconciliationlist, reportreconciliation:readGET /v1/reconciliation
reconciliationimport, importBulkreconciliation:writePOST /v1/reconciliation/import

The full route list, with what each one does, is on the API overview.

Errors and retries

Every API error is raised as a subclass of PaymentsnpError carrying the HTTP status, the API's error code, the message, the request ID and, on 429, the Retry-After seconds.

Error classes
ClassWhenTypical codes
AuthenticationError401unauthorized, api_key_expired
PermissionError403insufficient_scope, api_key_ip_denied, environment_mismatch
InvalidRequestError400, 404, 409, 422invalid_request, not_found, idempotency_conflict
RateLimitError429rate_limited, with the Retry-After seconds
ApiError5xxinternal_error
ConnectionErrorNo responseNetwork failure or timeout
SignatureVerificationErrorWebhook checkSignature or timestamp did not verify
import { PermissionError, RateLimitError } from "@paymentsnp/sdk";
try {
  await pnp.payments.list();
} catch (error) {
  if (error instanceof PermissionError && error.code === "insufficient_scope") { /* add payments:read */ }
  else if (error instanceof RateLimitError) console.log(`retry in ${error.retryAfter}s`);
  else throw error;
}
try {
    $paymentsnp->payments->retrieve($id);
} catch (\Paymentsnp\InvalidRequestError $e) {
    error_log($e->getErrorCode() . ' ' . $e->getRequestId());
}
import paymentsnp

try:
    client.payments.retrieve(payment_id)
except paymentsnp.InvalidRequestError as e:
    print(e.status, e.code, e.request_id)
Retries
DefaultUp to 2 retries with exponential backoff and jitter. On a 429 the SDK waits for Retry-After, capped at 60 seconds.
RetriedGET requests and checkout session creation, on network errors, timeouts, 429 and 5xx. TypeScript also retries checkout expire.
Other writesInvoice and reconciliation writes are never sent twice. With an idempotency key, the TypeScript SDK retries them only when the request never reached the server.
Never4xx errors are never retried.

Money helpers

Amounts are integer paisa. The helpers convert with string and integer maths only, accept lakh-style commas and refuse more than two decimals.

toPaisa("1,234.50");   // 123450
toPaisa("12,34,567");  // 123456700 (lakh commas allowed)
toPaisa("1.234");      // throws RangeError (more than 2 decimals)
formatNpr(123450);     // "NPR 1,234.50"
\Paymentsnp\Money::toPaisa('1,234.50'); // 123450 (string math; floats are rejected)
\Paymentsnp\Money::formatNpr(123450);   // "NPR 1,234.50"
from paymentsnp import to_paisa, format_npr

to_paisa("1,234.50")  # 123450; floats raise TypeError
format_npr(123450)    # "NPR 1,234.50"

The paymentsnp CLI

Installing @paymentsnp/sdk adds a paymentsnp command (npx paymentsnp …). It reads the key from PAYMENTSNP_API_KEY; passing --api-key still works but prints a warning, because a key typed on the command line ends up in your shell history.

export PAYMENTSNP_API_KEY=np_test_...
paymentsnp checkout create --amount 1500.00 --order ORD-1 --success-url https://shop.example.com/thanks --cancel-url https://shop.example.com/cart
paymentsnp checkout get <session_id>
paymentsnp checkout expire <session_id>
paymentsnp payments list --limit 10
paymentsnp payments get <payment_id>
paymentsnp invoices list --status open

# Local webhook testing (secret from --secret or PAYMENTSNP_WEBHOOK_SECRET)
paymentsnp webhooks sign --secret whsec_... --file body.json
paymentsnp webhooks verify --secret whsec_... --header 't=...,v1=...' --file body.json
  • --json prints the raw API response; without it you get a table with amounts as NPR ….
  • --amount is in rupees. webhooks verify checks only the signature, not its age, so you can verify captured bodies later.
  • Exit codes: 0 success, 1 API or verification error, 2 usage error.

checkout.js

A small script with no dependencies that opens hosted checkout in a centred popup, so the customer stays on your page. Create the checkout on your server first, then open its checkout_url from a click.

<script src="https://paymentsnp.com/checkout.js"></script>
<button onclick="Paymentnp.open({ checkoutUrl: 'CHECKOUT_URL' })">
  Pay now
</button>
window.Paymentnp.open options
checkoutUrlRequired. The checkout_url your server received.
onSuccessCalled with { session_id, status }. A hint to update your page, not proof of payment.
onCancelCalled with { session_id, status } when the customer cancels.
onCloseCalled with status: "closed" when the customer closes the popup without finishing.
  • If the browser blocks the popup, the current tab goes to checkout and returns to your success_url or cancel_url.
  • The result message is checked for origin and source. It is posted only to one of your approved embed domains, or to your return URL's origin when you have not set any. Add domains in Settings, up to 20 per environment.
  • Checkout never runs in an iframe.

Still confirm every payment on your server with a webhook or an API read.