# Node.js SDK

> Install and use the official Node.js SDK, @tappay-mn/node, for the TapPay API.

Source: https://docs.tappay.mn/sdks/node/

The official Node.js SDK `@tappay-mn/node` calls the TapPay API for you. It signs requests with HMAC, sends an `Idempotency-Key`, retries safely, pages through lists and verifies webhooks, so you do not write HTTP by hand. Use it on your server with your [secret key](https://docs.tappay.mn/glossary.md#secret-key).

## Install {#install}

> **Warning:** **Coming soon**
>
> The SDKs are not yet published to npm, Packagist or PyPI, so the install command does not work yet. Until then, call the API over HTTP directly. The examples in the guides and the [API reference](https://docs.tappay.mn/reference.md) include a curl version.

Add the package to your project.

```bash
npm i @tappay-mn/node
```

## Supported versions {#supported-versions}

The SDK supports these runtime versions. A runtime leaves the list one minor version after its end of life.

| SDK | Package | Version | Install | Supported runtimes | Registry | Source |
| - | - | - | - | - | - | - |
| Node.js | `@tappay-mn/node` | 3.1.0 | `npm install @tappay-mn/node` | Node.js 22, 24, 26 | [npm](https://www.npmjs.com/package/@tappay-mn/node) | [gitlab.com/node-platform/nodepay-node](https://gitlab.com/node-platform/nodepay-node) |

## Quickstart {#quickstart}

Take a first test [payment](https://docs.tappay.mn/glossary.md#payment) in five minutes with a [sandbox](https://docs.tappay.mn/glossary.md#sandbox) key. Each step is a full script that you can run on its own.

1. Create an [invoice](https://docs.tappay.mn/glossary.md#invoice) for the order. The response has the `invoiceId` and the `intentId`.

```js title="Node.js"
import { TapPay } from '@tappay-mn/node';

const tappay = new TapPay({ apiKey: 'sk_test_YOUR_SECRET_KEY' });
const invoice = await tappay.invoices.create({
  body: {
    terminalId: 'YOUR_TERMINAL_ID',
    amount: 1000,
    description: 'Order #1001',
    orderId: `order-${crypto.randomUUID()}`,
  },
});
console.log(JSON.stringify(invoice));
```

2. Create a [checkout session](https://docs.tappay.mn/glossary.md#checkout-session) for the invoice and send the [customer](https://docs.tappay.mn/glossary.md#customer) to its `url`.

```js title="Node.js"
import { TapPay } from '@tappay-mn/node';

const tappay = new TapPay({ apiKey: 'sk_test_YOUR_SECRET_KEY' });
const checkoutSession = await tappay.checkoutSessions.create({
  body: {
    invoiceId: 'INVOICE_ID',
    terminalId: 'YOUR_TERMINAL_ID',
    returnUrl: 'https://example.com/return',
    cancelUrl: 'https://example.com/cancel',
  },
});
console.log(JSON.stringify(checkoutSession));
```

3. In the sandbox, let the [simulator](https://docs.tappay.mn/glossary.md#simulator) pay the intent. In [production](https://docs.tappay.mn/glossary.md#production) the customer pays.

```js title="Node.js"
import { TapPay } from '@tappay-mn/node';

const tappay = new TapPay({ apiKey: 'sk_test_YOUR_SECRET_KEY' });
const result = await tappay.sandbox.simulateIntent({ id: 'INTENT_ID', body: { channel: 'QR', outcome: 'SUCCEEDED' } });
console.log(JSON.stringify(result));
```

4. Verify the webhook over the raw body with `constructEvent`.

```js title="Node.js"
import { readFileSync } from 'node:fs';
import { TapPay, SignatureVerificationError } from '@tappay-mn/node';

const tappay = new TapPay({ apiKey: 'sk_test_YOUR_SECRET_KEY' });
// Your web framework gives you these: the raw body, the headers and the path of your endpoint.
const { rawBody, headers, path } = JSON.parse(readFileSync(0, 'utf8'));
try {
  const event = tappay.webhooks.constructEvent(rawBody, headers, { secrets: [process.env.TAPPAY_WEBHOOK_SECRET], path });
  console.log(event.id ? 'valid' : 'invalid');
} catch (e) {
  if (!(e instanceof SignatureVerificationError)) throw e;
  console.log('invalid');
}
```

5. The [event](https://docs.tappay.mn/glossary.md#event) carries only ids. Read the object itself with `events.retrieveObject` before you hand over goods.

```js title="Node.js"
import { TapPay } from '@tappay-mn/node';

const tappay = new TapPay({ apiKey: 'sk_test_YOUR_SECRET_KEY' });
// In your webhook handler pass the event from constructEvent. Here it is built from the payment of step 3.
const event = { id: 'evt_example', type: 'payment.succeeded', objectId: 'PAYMENT_ID' };
const payment = await tappay.events.retrieveObject(event);
console.log(JSON.stringify(payment));
```

6. [Refund](https://docs.tappay.mn/glossary.md#refund) the payment if the customer returns the order.

```js title="Node.js"
import { TapPay } from '@tappay-mn/node';

const tappay = new TapPay({ apiKey: 'sk_test_YOUR_SECRET_KEY' });
const refund = await tappay.refunds.create({ paymentId: 'PAYMENT_ID', body: { amount: '1000', reason: 'Customer returned the item' } });
console.log(JSON.stringify(refund));
```

## Configuration {#configuration}

Pass options to the constructor. An option you leave out is read from the environment. The environment, sandbox or production, follows the key prefix: `sk_test_` is the sandbox and `sk_live_` is production, so you never set the base URL in code.

| Option | Environment variable | Default | Meaning |
| - | - | - | - |
| `apiKey` | `TAPPAY_SECRET_KEY` | required | Secret key. A [publishable key](https://docs.tappay.mn/glossary.md#publishable-key) `pk_…` is rejected. |
| `baseUrl` | `TAPPAY_BASE_URL` | from the key | Only for tests against your own stack. Never in production. |
| `signingSecret` | `TAPPAY_SIGNING_SECRET` | none | Signs each request with HMAC when your system uses the API key + HMAC [signature](https://docs.tappay.mn/glossary.md#signature) method. |
| `timeoutMs` | — | `30000` | Time limit of one call in milliseconds. |
| `maxRetries` | — | `2` | Retries after a network error, `429` or `5xx`. |
| `maxRetryAfterMs` | — | `60000` | Upper limit for `Retry-After`. Above it the SDK does not wait. |
| `nodeVersion` | — | `2026-09-27` | The `TapPay-Version` header. Each SDK version pins one [API version](https://docs.tappay.mn/glossary.md#api-version), and this option overrides it. |

```js
import { TapPay } from '@tappay-mn/node';

// Options you leave out are read from TAPPAY_SECRET_KEY, TAPPAY_BASE_URL and TAPPAY_SIGNING_SECRET.
const tappay = new TapPay({
  apiKey: process.env.TAPPAY_SECRET_KEY,
  signingSecret: process.env.TAPPAY_SIGNING_SECRET,
  timeoutMs: 15000,
  maxRetries: 3,
  maxRetryAfterMs: 30000,
  nodeVersion: '2026-09-27',
});

// Per call: the second argument.
const invoice = await tappay.invoices.retrieve({ id: 'YOUR_INVOICE_ID' }, { timeoutMs: 5000, nodeVersion: '2026-09-27' });
```

## Idempotency and retries {#idempotency-and-retries}

Every POST that creates something is sent with an `Idempotency-Key`. The SDK makes a new key for each call and sends the same key on each retry of that call, so a retry never creates a second invoice or refund. You can pass your own key, as shown in [Idempotency](https://docs.tappay.mn/concepts/idempotency.md). The SDK retries a network error, `429` and `5xx` with exponential backoff and respects `Retry-After`.

## Errors {#errors}

Each API error is a subclass of `TapPayError` with `status`, `code`, `message`, `requestId` and `docsUrl`. The code is a `XXX-NNN` value from the [error catalog](https://docs.tappay.mn/errors.md).

| Class | When |
| - | - |
| `InvalidRequestError` | 400, 422 |
| `AuthenticationError` | 401 |
| `PermissionError` | 403 |
| `NotFoundError` | 404 |
| `ConflictError` | 409 |
| `IdempotencyError` | 409 `VAL-010`, same key with a different body |
| `RateLimitError` | 429 |
| `ApiError` | 5xx and other answers |
| `ConnectionError` | network error |
| `TimeoutError` | the call took longer than the time limit |

```js
import { TapPay, NotFoundError, TapPayError } from '@tappay-mn/node';

const tappay = new TapPay({ apiKey: process.env.TAPPAY_SECRET_KEY });
try {
  await tappay.invoices.retrieve({ id: 'YOUR_INVOICE_ID' });
} catch (err) {
  if (err instanceof NotFoundError) console.log('not found', err.code, err.requestId);
  else if (err instanceof TapPayError) console.log(err.status, err.code, err.docsUrl);
  else throw err;
}
```

## Pagination {#pagination}

A list call returns a page with `data`, `hasMore` and `nextCursor`. The iterator fetches the next pages as you go.

```js
import { TapPay } from '@tappay-mn/node';

const tappay = new TapPay({ apiKey: process.env.TAPPAY_SECRET_KEY });
// Every page, fetched as you go.
for await (const payment of tappay.payments.list({ query: { limit: 50 } })) {
  console.log(payment.id, payment.status);
}
// Only the first page.
const page = await tappay.payments.list({ query: { limit: 10 } }).firstPage();
console.log(page.data.length, page.hasMore, page.nextCursor);
```

## Webhooks {#webhooks}

Verify each webhook over the raw body, before any JSON parsing. During a [secret rotation](https://docs.tappay.mn/guides/webhooks.md#rotate-the-secret) pass the new and the previous secret: either one may match. The event is thin, so read the object with `events.retrieveObject`. Read the [webhook guide](https://docs.tappay.mn/guides/webhooks.md) for the whole flow.

```js
import express from 'express';
import { TapPay, SignatureVerificationError } from '@tappay-mn/node';

const tappay = new TapPay({ apiKey: process.env.TAPPAY_SECRET_KEY });
const app = express();

// express.raw keeps the body as bytes. A parsed JSON body fails with RAW_BODY_REQUIRED.
app.post('/webhooks/tappay', express.raw({ type: 'application/json' }), async (req, res) => {
  let event;
  try {
    event = tappay.webhooks.constructEvent(req.body, req.headers, {
      // During a rotation both secrets are valid: the new one and the previous one.
      secrets: [process.env.TAPPAY_WEBHOOK_SECRET, process.env.TAPPAY_WEBHOOK_SECRET_PREVIOUS].filter(Boolean),
      path: req.originalUrl,
    });
  } catch (err) {
    if (err instanceof SignatureVerificationError) return void res.sendStatus(400);
    throw err;
  }
  // The event is thin: read the object itself with GET before you act on it.
  const object = await tappay.events.retrieveObject(event);
  console.log(event.type, object.status);
  res.sendStatus(200);
});
```

## POS client {#pos-client}

`PosClient` calls the POS API of a card [terminal](https://docs.tappay.mn/glossary.md#terminal) with a partner credential. It gets and renews the token and signs each request. Read the [POS API reference](https://docs.tappay.mn/reference/pos/auth/token.md) and the [POS terminal guide](https://docs.tappay.mn/guides/pos-terminal.md).

```js
import { PosClient } from '@tappay-mn/node';

const pos = new PosClient({
  clientId: process.env.POS_CLIENT_ID,
  clientSecret: process.env.POS_CLIENT_SECRET,
  apiKey: process.env.POS_API_KEY,
  signingSecret: process.env.POS_SIGNING_SECRET,
  environment: 'sandbox',
});

const qr = await pos.payments.createQr({
  body: {
    pos_reference: 'pos-1001',
    narrative: 'Order #1001',
    amount: 1000,
    currency: 'MNT',
    card_terminal: { terminal_code: 'T-SANDBOX-POS', merchant_code: 'M-SANDBOX-POS' },
  },
});
// Do not trust the callback: read the payment from the API.
const payment = await pos.payments.retrieve({ paymentId: qr.payment_id });
console.log(payment.status);
```

## Versioning {#versioning}

The SDK follows semantic versioning. A major version may break your code, and minor and patch versions do not. Each SDK version pins one `TapPay-Version`. The release notes are on the [npm page](https://www.npmjs.com/package/@tappay-mn/node) and in the `CHANGELOG.md` of the package. The [Changelog](https://docs.tappay.mn/changelog.md) lists the SDK versions for each API version.

## Browser {#browser}

Never use your secret key in a browser. The SDK throws `ConfigurationError` with the code `BROWSER_SECRET_KEY` when you create `TapPay` in a browser. In the browser use the [checkout script](https://docs.tappay.mn/guides/checkout.md) with a publishable key.
