Search Documentation
Search across all documentation pages, APIs and guides.
JavaScript SDK
The official OnePay SDK for JavaScript applications. It wraps the same checkout flow as OnePayJS in a typed class with proper event listeners, and adds first-class support for subscriptions. Published on npm as @onepaynpm/onepay-sdk, currently at version 1.0.3, with zero external dependencies.
window.onePayData and global event listeners by hand. Also the only documented way to process subscriptions client-side.Installation
npm install @onepaynpm/onepay-sdk
Basic setup
Create an OnePaySDK instance and initialize it once when your app loads.
import { OnePaySDK } from '@onepaynpm/onepay-sdk';const onePaySDK = new OnePaySDK({debug: true, // Enable debug loggingapiBaseUrl: 'https://api.onepay.lk' // Optional, defaults to this});// Initialize the SDK before processing any paymentawait onePaySDK.initialize();
Adding event listeners
.current property will not work.// Correct wayonePaySDK.addEventListener({onSuccess: (result) => {console.log('Payment successful:', result);// handle the successful payment},onFail: (result) => {console.log('Payment failed:', result);// handle the failed payment},onClose: (result) => {console.log('Payment modal closed:', result);// handle the customer closing the modal},});// This will not work// onePaySDKRef.current.addEventListener({ ... })
Processing a payment
Call processPayment with the same fields used by OnePayJS. This opens the secure payment overlay and resolves once the flow starts.
await onePaySDK.processPayment({currency: 'LKR',amount: 1000,appid: 'your-app-id',hashToken: 'your-hash-token',orderReference: 'ORDER-123',customerFirstName: 'John',customerLastName: 'Doe',customerPhoneNumber: '+94123456789',customerEmail: 'john@example.com',transactionRedirectUrl: 'https://your-site.com/payment-success',apptoken: 'your-app-token',});
Processing a subscription
The SDK also exposes processSubscription, which sets up a recurring billing schedule directly, including trial periods. This is the only documented client-side path to subscription billing; the rest of OnePay's recurring billing is handled server-side through Card on File.
await onePaySDK.processSubscription({currency: 'LKR',amount: 500,appid: 'your-app-id',name: 'Monthly Subscription',interval: 'month',interval_count: 1,days_until_due: 7,trial_period_days: 14,customer_details: {first_name: 'John',last_name: 'Doe',email: 'john@example.com',phone: '+94123456789',},apptoken: 'your-app-token',});
Subscription parameters
| Field | Type | Description |
|---|---|---|
currency | string | Three-letter currency code, e.g. LKR. |
amount | number | The amount charged on each billing cycle. |
name | string | A label for the subscription plan, shown to the customer. |
interval | string | Billing interval unit, e.g. "month". |
interval_count | number | How many intervals between charges. 1 with interval: "month" means monthly. |
days_until_due | number | Grace period in days before an unpaid invoice is considered overdue. |
trial_period_days | number | Number of free trial days before the first charge. |
customer_details | object | Customer's first_name, last_name, email, and phone. |
Direct payment with an existing gateway URL
If you already have a redirect_url and transaction ID from a server-side call to the Payment API, you can open the payment overlay directly without calling processPayment again.
await onePaySDK.processDirectPayment({directGatewayURL: 'https://payment-gateway-url',directTransactionId: 'transaction-id',});
React example
A complete pattern for wiring the SDK into a React component, including initialization, event listeners, and a disabled state while a payment is processing.
import React, { useEffect, useState } from 'react';import { OnePaySDK, PaymentResult } from '@onepaynpm/onepay-sdk';const PaymentComponent: React.FC = () => {const [onePaySDK] = useState(new OnePaySDK({ debug: true }));const [isInitialized, setIsInitialized] = useState(false);const [isProcessing, setIsProcessing] = useState(false);useEffect(() => {const initializeSDK = async () => {try {await onePaySDK.initialize();setIsInitialized(true);// Set up event listeners, the correct wayonePaySDK.addEventListener({onSuccess: (result: PaymentResult) => {console.log('Payment successful:', result);setIsProcessing(false);},onFail: (result: PaymentResult) => {console.log('Payment failed:', result);setIsProcessing(false);},onClose: (result: PaymentResult) => {console.log('Payment modal closed:', result);setIsProcessing(false);},});} catch (error) {console.error('Failed to initialize OnePay SDK:', error);}};initializeSDK();}, [onePaySDK]);const handlePayment = async () => {if (!isInitialized) return;setIsProcessing(true);try {await onePaySDK.processPayment({currency: 'LKR',amount: 1000,appid: 'your-app-id',hashToken: 'your-hash-token',orderReference: `ORDER-${Date.now()}`,customerFirstName: 'John',customerLastName: 'Doe',customerPhoneNumber: '+94123456789',customerEmail: 'john@example.com',transactionRedirectUrl: window.location.origin + '/payment-success',apptoken: 'your-app-token',});} catch (error) {console.error('Payment processing error:', error);setIsProcessing(false);}};return (<div><button onClick={handlePayment} disabled={!isInitialized || isProcessing}>{isProcessing ? 'Processing...' : 'Pay Now'}</button></div>);};
API reference
Constructor options
| Option | Type | Description |
|---|---|---|
firebaseConfig | object | Firebase configuration object. The SDK uses Firebase internally to listen for transaction updates in real time. |
apiBaseUrl | string | Custom API base URL. Defaults to https://api.onepay.lk. |
debug | boolean | Enables debug logging to the console. Defaults to false. |
Methods
| Method | Description |
|---|---|
initialize() | Initializes the SDK. Call this once before processing any payment. |
addEventListener(listeners) | Registers onSuccess, onFail, and onClose handlers on the SDK instance. |
removeEventListener(type, listener) | Removes a previously registered event listener. |
processPayment(data) | Opens the secure payment overlay for a standard one-time payment. |
processSubscription(data) | Sets up a recurring billing subscription. |
processDirectPayment(data) | Opens the payment overlay using a gateway URL and transaction ID you already obtained server-side. |
closePaymentGateway() | Programmatically closes the payment overlay. |
isInitialized() | Returns whether the SDK has completed initialization. |
Event types
| Event | Fires when |
|---|---|
onePaySuccess | The payment completes successfully. |
onePayFail | The payment fails or is declined. |
onePayClose | The customer closes the payment modal without completing payment. |
Troubleshooting
Event listeners not firing
If your listeners never trigger, double check that you are calling addEventListener on the SDK instance itself, not on a ref's .current value.
// Correct wayonePaySDK.addEventListener({ /* ... */ });// This does not workonePaySDKRef.current.addEventListener({ /* ... */ });
Firebase listener issues
The SDK uses Firebase internally to listen for transaction status updates. If payments seem to hang or events never fire, check that your Firebase configuration is correct and that initialize() has resolved before you call processPayment.
On This Page