@vantagepay/vantagepay
v0.18.0
Published
VantagePay API wrapper and SDK for integrating into VantagePay payment, consumer and merchant services.
Readme
VantagePay SDK for TypeScript/JavaScript
@vantagepay/vantagepay is the official TypeScript/JavaScript SDK for integrating with VantagePay APIs.
It provides:
- typed API modules backed by VantagePay model types
- automatic HTTP retries for transient failures
- automatic token refresh using
refreshToken - real-time payment status updates via SignalR
- event publishing for session and payment lifecycle signals
This package is client-focused. Administrative API-key capabilities are available in the .NET SDK (VantagePay.SDK) and are not part of this package.
Table of Contents
- Installation
- Client Types
- Basic Usage
- Configuration and Construction
- Authentication and Tokens
- Error Handling
- Public API Surface
- Payments and Signals
- Server-side Admin Usage
- Additional Modules
Installation
npm install @vantagepay/vantagepayClient Types
This package exposes one top-level client:
VantagePayfor client-facing integrations (web/mobile/POS-style app integrations).
Important:
- there is no
VantagePayAdminClientin TypeScript. - for server-side admin API-key workflows, use the .NET SDK.
Basic Usage
import { VantagePay } from '@vantagepay/vantagepay'
const client = new VantagePay({
baseUrl: 'https://sandbox-api.vantagepay.dev/',
})
await client.auth.login('233548306110', 'Password123!')
const currencies = await client.lookups.getCurrencies()
const summary = await client.reports.getTransactionSummary('GHS')
await client.close()Configuration and Construction
Available VantagePay constructor options:
import { VantagePay } from '@vantagepay/vantagepay'
const client = new VantagePay({
baseUrl: 'https://sandbox-api.vantagepay.dev/',
headers: { 'X-EXAMPLE-HEADER': 'Test' },
language: 'en',
retries: 3,
consoleLogging: false,
logBatchSize: 100,
logBatchInterval: 60000,
})Notes:
baseUrldefaults tohttp://localhost:5000.close()flushes logs, stops payment status checks, unsubscribes events, and aborts in-flight requests.
Authentication and Tokens
Login and token storage
import { ApiTokens } from '@vantagepay/vantagepay'
const tokenResponse = await client.auth.login('233548306110', 'Password123!')
console.log(tokenResponse.accessToken)
console.log(ApiTokens.accessToken)
console.log(ApiTokens.refreshToken)Restore existing tokens
import { ApiTokens } from '@vantagepay/vantagepay'
ApiTokens.accessToken = secureStore.get('accessToken') || null
ApiTokens.refreshToken = secureStore.get('refreshToken') || nullSession helpers
const isLoggedIn = client.auth.isLoggedIn()
await client.auth.refresh()
await client.auth.logout()Token claim helpers
client.auth.getCurrentUserReference()
client.auth.getCurrentConsumerReference()
client.auth.getCurrentMerchantReference()
client.auth.getCurrentBusinessReference()
client.auth.getCurrentTerminalReference()
client.auth.getCurrentUserName()
client.auth.getMobileNumber()
client.auth.getEmailAddress()
client.auth.getRedirectAction()Error Handling
All API methods throw ApiError for HTTP/API failures.
import { ApiError } from '@vantagepay/vantagepay'
try {
await client.auth.login('user', 'wrong-password')
} catch (error) {
if (error instanceof ApiError) {
console.error(error.statusCode)
console.error(error.message)
console.error(error.result)
if (error.statusCode === 401 && error.result?.mustChangePassword) {
await client.auth.changePassword('OldPassword', 'NewPassword123!')
}
if (error.statusCode === 401 && (error.result?.mustValidatePhoneNumber || error.result?.mustValidateEmailAddress)) {
await client.auth.resendOtp()
await client.auth.validateOtp('123456')
}
} else {
throw error
}
}Public API Surface
VantagePay modules:
| Module | Purpose |
|---|---|
| auth | Login/logout, refresh, OTP, password, face/liveness checks, token claim helpers |
| lookups | Countries, currencies, languages, banks, wallet operators, categories, product types, address resolution |
| consumers | Consumer profile operations, files, limits, debit orders, feedback/support |
| merchants | Merchant profile operations, OTP verify, merchant user flows, product catalog and merchant product management, POS setup/config |
| payments | Payment initiation, status monitoring, tokenization, interactive payment submissions |
| notifications | In-app message retrieval and lifecycle |
| qrCodes | QR decode and QR image generation |
| reports | Recent transactions, summaries, daily and detailed transaction reporting |
| system | Health ping |
| content | Client content and contact-details retrieval (cached) |
| log | Structured application logging with batching |
| events | PubSub event bus for session and payment signals |
Example API calls:
const banks = await client.lookups.getBanks()
const consumer = await client.consumers.getConsumer()
const merchant = await client.merchants.getMerchant()
const productTypes = await client.merchants.getActiveProductTypes()
const messages = await client.notifications.getMessages()
const recent = await client.reports.getRecentTransactions(10, true)
await client.system.ping()Payments and Signals
Basic payment submission
const status = await client.payments.pay({
yourReference: 'ORDER-1001',
paymentSources: {
mobileWallets: [{
mobileWalletOperator: 'MTN',
msisdn: '233555666112',
amountInCents: 5000,
currency: 'GHS',
}],
},
paymentDestinations: {
merchants: [{
merchantReference: 'merchant-reference',
amountInCents: 5000,
currency: 'GHS',
paymentType: 'BuyingGoods',
}],
},
})Subscribing to payment/session signals
import {
OnSessionStarted,
OnSessionExpired,
OnAutomaticRefresh,
OnApiRetry,
OnPaymentStatusUpdate,
OnPaymentComplete,
OnRequiresPin,
OnRequiresConfirmation,
OnRequires3DSecure,
OnComplete3DSecure,
OnRequiresAddress,
} from '@vantagepay/vantagepay'
const sub1 = client.events.subscribe(OnPaymentStatusUpdate, (_, data) => {
console.log('status update', data)
})
const sub2 = client.events.subscribe(OnPaymentComplete, (_, data) => {
console.log('payment complete', data.paymentReference)
})
client.events.subscribe(OnRequiresPin, async (_, data) => {
await client.payments.submitPinCode(data.transactionReference, '1234')
})
client.events.subscribe(OnRequiresConfirmation, async (_, data) => {
await client.payments.submitConfirmation(data.transactionReference, true)
})
client.events.subscribe(OnRequiresAddress, async (_, data) => {
await client.payments.submitAddress(data.transactionReference, {
addressType: 'BILL',
addressLine1: '10 Main Road',
city: 'Johannesburg',
countryIsoCode: 'ZAF',
postalCode: '2196',
})
})
client.events.subscribe(OnRequires3DSecure, (_, data) => {
window.open(data.url)
})
client.events.subscribe(OnComplete3DSecure, () => {
console.log('3DS completed')
})
client.events.subscribe(OnSessionStarted, () => console.log('session started'))
client.events.subscribe(OnSessionExpired, () => console.log('session expired'))
client.events.subscribe(OnAutomaticRefresh, (_, token) => console.log('refreshed', token))
client.events.subscribe(OnApiRetry, (_, data) => console.log('retry', data.retryCount))
client.events.unsubscribe(sub1)
client.events.unsubscribe(sub2)Manual status-check control
await client.payments.startPaymentStatusChecking() // external/incoming payment listener
await client.payments.stopPaymentStatusChecking('payment-ref') // one payment
await client.payments.stopPaymentStatusChecking() // all paymentsTokenization and notifications
const cardToken = await client.payments.createCardToken({
cardNumber: '5200000000000114',
nameOnCard: 'John Doe',
expiryMonth: 9,
expiryYear: 2028,
})
await client.payments.sendEmailPaymentNotification('payment-reference', '[email protected]')
await client.payments.sendSmsPaymentNotification('payment-reference', '233548306110')Payment helpers
client.payments.getRequiredPinLength('VDF') // 6
client.payments.getRequiredPinLength('MTN') // 4
client.payments.luhnCheck('5200000000000114') // trueServer-side Admin Usage
This TypeScript package does not expose admin API-key modules.
For administrative workflows (for example user administration, KYC/KYB administration, template management, and admin payment/refund orchestration), use the .NET SDK VantagePay.SDK with VantagePayAdminClient.
Additional Modules
QR utilities
const decoded = await client.qrCodes.decode('000201010211...')
const qrBase64 = await client.qrCodes.generate('https://example.com/pay', 500)Content
const clientContent = await client.content.getClientContent()
const contactDetails = await client.content.getContactDetails()Structured logging
client.log.info('User {Username} logged in from {Country}', 'john', 'GHA')
client.log.warn('Payment {PaymentRef} is delayed', 'PAY-123')
await client.log.flush()