@mnpay/bonum
v1.5.0
Published
Client library for the Bonum payment gateway — invoices, QR payments, card tokenization and subscriptions.
Maintainers
Readme
@mnpay/bonum
Client library for the Bonum payment gateway. Supports invoices, QR-code payments, card tokenization, recurring subscriptions, and NEO digital wallet messaging.
- Production API:
https://apis.bonum.mn - Test API:
https://testapi.bonum.mn
Installation
npm install @mnpay/bonumyarn add @mnpay/bonumUsage
import { useBonum } from '@mnpay/bonum'
const bonum = useBonum({
appSecret: 'your-app-secret',
terminalId: 'your-terminal-id',
isTestEnv: false, // set true to use test environment
})Configuration
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| appSecret | string | Yes | Application secret key |
| terminalId | string | Yes | Terminal identifier |
| baseUrl | string | No | Override API base URL |
| checksumKey | string | No | MERCHANT_CHECKSUM_KEY issued out-of-band by Bonum (distinct from appSecret). Required to call verifyWebhookChecksum — it throws when unset. |
| language | 'mn' \| 'en' | No | Default response language (Accept-Language header). When unset, no language header is sent. Override per request via createInvoice({ language }). |
| isTestEnv | boolean | No | Use test environment URL |
Access tokens are managed automatically — the client fetches and refreshes tokens via an interceptor before each request.
Authentication
getToken()
Fetches a new access token using appSecret and terminalId. Called automatically by the interceptor; you rarely need to call this manually.
Response:
| Field | Type | Description |
|-------|------|-------------|
| tokenType | 'Bearer' | Token type |
| accessToken | string | Access token |
| expiresIn | number | Token lifetime in seconds |
| refreshToken | string | Refresh token |
| refreshExpiresIn | number | Refresh token lifetime in seconds |
| unit | 'SECONDS' | Unit for expiry values |
refreshToken()
Refreshes the access token using the stored refresh token. Called automatically when the access token expires.
Response:
| Field | Type | Description |
|-------|------|-------------|
| accessToken | string | New access token |
Payment Providers
getPaymentProviders()
Returns the list of payment providers and their enabled status.
Response: PaymentProviderItem[]
| Field | Type | Description |
|-------|------|-------------|
| provider | 'QPAY' \| 'E_COMMERCE' \| 'WE_CHAT' \| 'SONO_SHOP' | Provider identifier |
| enabled | boolean | Whether the provider is currently active |
Invoices
createInvoice(data)
Creates a payment invoice and returns a followUpLink to redirect the customer to.
Request:
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| amount | number | Yes | Invoice amount |
| callback | string | Yes | Webhook URL called when payment status changes |
| transactionId | string | Yes | Unique merchant-side transaction ID |
| expiresIn | number | Yes | Invoice expiry duration in seconds |
| providers | PaymentProvider[] | No | Limit to specific payment providers |
| items | InvoiceItem[] | No | Line items to display on the invoice |
| extras | InvoiceExtra[] | No | Extra input fields shown to the customer |
| language | 'mn' \| 'en' | No | Per-invoice display language, sent as the Accept-Language header. Falls back to the client-level language; when neither is set, no language header is sent. |
InvoiceItem:
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| title | string | Yes | Item name |
| amount | number | Yes | Item price |
| count | number | Yes | Quantity |
| image | string | No | Item image URL |
| remark | string | No | Additional note |
Response:
| Field | Type | Description |
|-------|------|-------------|
| invoiceId | string | Created invoice ID |
| followUpLink | string | URL to redirect the customer to for payment |
Example:
const { data } = await bonum.createInvoice({
amount: 19900,
callback: 'https://yoursite.com/webhook/bonum',
transactionId: 'TXN-001',
expiresIn: 300,
})
// Redirect customer to:
console.log(data.followUpLink)getInvoiceStatus({ invoiceId })
⚠️ Test environment only — do NOT use in production. Bonum only exposes invoice status polling in the test environment. In production, track payment outcomes via the
PAYMENTwebhook (see Webhooks) rather than polling this endpoint.
Returns the current status of an invoice.
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| invoiceId | string | Yes | Invoice ID from createInvoice |
setInvoicePaid({ invoiceId })
Marks an invoice as paid. Typically called from a webhook handler after confirming payment.
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| invoiceId | string | Yes | Invoice ID to mark as paid |
QR Code Payments
createQrCode(data)
Creates a QR code for payment. The customer scans the QR with a supported banking app.
Request:
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| amount | number | Yes | Payment amount |
| transactionId | string | Yes | Unique merchant-side transaction ID |
| expiresIn | number | Yes | QR code expiry in seconds |
Response:
| Field | Type | Description |
|-------|------|-------------|
| invoiceId | string | Invoice ID for this QR payment |
| qrCode | string | Raw QR code string |
| qrImage | string | Base64-encoded QR code image |
| links | QrDeepLink[] | Deep links for supported banking apps |
QrDeepLink:
| Field | Type | Description |
|-------|------|-------------|
| name | string | Bank/app name |
| description | string | Description |
| logo | string | Logo URL |
| link | string | Deep link URL |
| appStoreId | string | iOS App Store ID |
| androidPackageName | string | Android package name |
invoiceByQrCode({ qrCode })
Creates an invoice using data from a scanned QR code.
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| qrCode | string | Yes | Raw QR code string scanned by the customer |
payByCardTokenQr({ qrCode, transactionId, cardToken })
Pays a QR code invoice using a stored card token.
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| qrCode | string | Yes | QR code to pay |
| transactionId | string | Yes | Unique merchant-side transaction ID |
| cardToken | string | Yes | Card token from createCardToken |
Card Tokenization
createCardToken(data)
Initiates card tokenization. Returns a followUpLink to redirect the customer to for card entry.
Request:
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| callback | string | Yes | Webhook URL called after tokenization completes |
| transactionId | string | Yes | Unique merchant-side transaction ID |
| payment | { amount: number } | No | Charge the card immediately on tokenization |
| subscription | CardTokenSubscription | No | Attach the token to a subscription plan |
| items | InvoiceItem[] | No | Line items to display |
CardTokenSubscription:
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| planId | number | Yes | Subscription plan ID |
| cycleValue | string | Yes | Billing cycle value (e.g. day of month) |
| cycles | number \| null | No | Total billing cycles (null = unlimited) |
| payNow | boolean | No | Charge on tokenization |
| custEmail | string | No | Customer email for receipts |
Response:
| Field | Type | Description |
|-------|------|-------------|
| followUpLink | string | URL to redirect the customer to for card entry |
| id | string | Token request ID |
purchaseWithCardToken({ cardToken, amount, currency, transactionId })
Makes a purchase using a stored card token.
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| cardToken | string | Yes | Stored card token |
| amount | number | Yes | Charge amount |
| currency | string | Yes | Currency code |
| transactionId | string | Yes | Unique merchant-side transaction ID |
Response:
| Field | Type | Description |
|-------|------|-------------|
| id | number | Transaction ID |
| status | 'SUCCESS' \| 'FAILED' \| 'QUEUED' | Transaction status |
| completedAt | string | Completion timestamp |
| description | string | Result description |
| cardStatus | 'ACTIVE' \| 'INACTIVE' \| null | Card status |
| respCode | string \| null | Response code |
rollbackPurchase({ id, cardToken })
Refunds an already-completed card-token purchase in full (PDF §4.3:
GET /mpay-service/merchant/transaction/rollback/{id}). The refund always applies
to the full amount of the original purchase identified by id, so no amount is sent.
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| id | string | Yes | Transaction ID of the original purchase to roll back |
| cardToken | string | Yes | Card token used in the original purchase (sent as X-CARD-TOKEN) |
Subscriptions
listPaymentPlans()
Returns all available subscription plans.
Response: PaymentPlan[]
| Field | Type | Description |
|-------|------|-------------|
| planId | number | Plan ID |
| name | string | Plan name |
| remark | string | Plan description |
| recurringType | 'WEEKLY' \| 'MONTHLY' \| 'YEARLY' | Billing frequency |
| amount | number | Recurring charge amount |
| status | 'ACTIVE' \| 'INACTIVE' | Plan availability |
| cardCount | number | Number of cards enrolled |
| retryCount | number | Payment retry count on failure |
| createdAt | string | Plan creation timestamp |
subscribe({ cardToken, planId, cycleValue, cycles?, payNow?, custEmail? })
Subscribes a card to a payment plan.
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| cardToken | string | Yes | Card token to subscribe |
| planId | number | Yes | Subscription plan ID |
| cycleValue | number \| string | Yes | Billing cycle value |
| cycles | number \| null | No | Total cycles (null = unlimited) |
| payNow | boolean | No | Charge immediately on subscription |
| custEmail | string | No | Customer email for receipts |
Response: SubscriptionData (see below)
getSubscriptions({ cardToken })
Returns all subscriptions associated with a card token.
Response: SubscriptionData[]
SubscriptionData:
| Field | Type | Description |
|-------|------|-------------|
| subscriptionId | number | Subscription ID |
| subscribedAt | string | Subscription creation timestamp |
| cardMask | string | Masked card number |
| plan | PaymentPlan | The associated plan |
| nextBillAt | string | Next billing date |
| lastBilledAt | string | Last billing date |
| status | 'ACTIVE' \| 'INACTIVE' \| 'CANCELLED' | Subscription status |
unsubscribe({ subscriptionId, planId? })
Cancels a subscription.
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| subscriptionId | string | Yes | Subscription ID to cancel |
| planId | string | No | Plan ID (if required by the plan) |
deleteSubscription({ subscriptionId, planId? })
Permanently deletes a subscription record.
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| subscriptionId | string | Yes | Subscription ID to delete |
| planId | string | No | Plan ID (if required) |
changeSubscriptionTokenNewCard({ subscriptionId, callback, transactionId, items? })
Updates a subscription with a new card — initiates a new tokenization flow.
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| subscriptionId | string | Yes | Subscription to update |
| callback | string | Yes | Webhook URL after new card is tokenized |
| transactionId | string | Yes | Unique merchant-side transaction ID |
| items | InvoiceItem[] | No | Line items to display |
Response:
| Field | Type | Description |
|-------|------|-------------|
| followUpLink | string | URL to redirect customer to for new card entry |
changeSubscriptionTokenExisting({ subscriptionId, newCardToken })
Updates a subscription with an already-tokenized card.
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| subscriptionId | string | Yes | Subscription to update |
| newCardToken | string | Yes | Existing card token to use |
Note:
executeSubscriptionPaymentis@internaland intentionally undocumented. Subscription charges are automatic — Bonum fires theSUBSCRIPTION-PAYMENTwebhook on each recurring charge. Do not call it directly; rely on the webhook instead.
NEO (Digital Wallet)
The NEO methods communicate with a separate NEO / M-Chat base URL, passed per-request.
getNeoUserData({ requestId, mChatBaseUrl })
Retrieves NEO user account data for a given share request.
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| requestId | string | Yes | Share request ID |
| mChatBaseUrl | string | Yes | M-Chat service base URL |
sendNeoMessage({ phoneNumber, message, neoBaseUrl })
Sends a message to a user through the NEO messaging service.
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| phoneNumber | string | Yes | Recipient phone number |
| message | string | Yes | Message content |
| neoBaseUrl | string | Yes | NEO service base URL |
Webhook Verification
verifyWebhookChecksum(rawBody, headerChecksum)
Verifies the x-checksum-v2 webhook signature using the configured checksumKey.
Synchronous — no API call. Throws when checksumKey is not configured.
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| rawBody | string | Yes | Exact raw request body as received on the wire |
| headerChecksum | string | Yes | The x-checksum-v2 header value |
Webhooks
Bonum delivers status updates as signed webhooks. In production this is the authoritative
way to learn the outcome of a payment, card tokenization, or recurring charge — prefer it over
polling getInvoiceStatus (which is test-environment only).
Verifying the signature
Each webhook carries an x-checksum-v2 header (HmacSHA256 over the raw request body). When the
client is configured with checksumKey (the MERCHANT_CHECKSUM_KEY Bonum issues out-of-band —
not your appSecret), verify with the SDK method:
const bonum = useBonum({ terminalId, appSecret, checksumKey })
const ok = bonum.verifyWebhookChecksum(rawBody, req.headers['x-checksum-v2'])
if (!ok) throw new Error('Invalid Bonum webhook checksum')verifyWebhookChecksum throws when checksumKey is not configured, so a misconfiguration
never masquerades as an invalid signature.
The underlying pure function is also exported if you manage the key yourself:
import { validateWebhookChecksum } from '@mnpay/bonum'
const ok = validateWebhookChecksum(rawBody, checksumKey, req.headers['x-checksum-v2'])Important:
rawBodymust be the exact bytes received on the wire — capture it before any JSON parsing (readRawBodyin h3/Nitro,express.raw,req.text()in Next.js). Re-serializing a parsed body changes key order/escaping and the HMAC will never match.
Parsing the payload
bonumWebhookSchema is a Zod discriminated union (discriminated on type) covering all three
documented webhook kinds, each in a SUCCESS / FAILED variant. The parsed type is exported as
BonumWebhook.
| type | When it fires | Body |
|--------|---------------|------|
| PAYMENT | A regular invoice was paid / failed (PDF §3.3) | Transaction detail (invoiceId, amount, currency, transactionId, terminalId, …) |
| CARD-TOKEN | A card tokenization completed / failed (PDF §4.1) | Token + bank info |
| SUBSCRIPTION-PAYMENT | An automatic recurring charge ran (PDF §5.3) | subscriptionId, invoiceId, planId, transactionId, amount, currency, completedAt |
import { bonumWebhookSchema } from '@mnpay/bonum'
const event = bonumWebhookSchema.parse(req.body)
switch (event.type) {
case 'PAYMENT':
// reconcile invoice payment
break
case 'CARD-TOKEN':
// store the card token from the tokenization result
break
case 'SUBSCRIPTION-PAYMENT':
// record the recurring charge
break
}