@onepaynpm/onepay-sdk
v1.0.2
Published
Official OnePay payment gateway SDK for JavaScript applications
Maintainers
Readme
OnePay SDK
A JavaScript SDK for integrating OnePay payment gateway into web applications.
Installation
npm install onepay-sdkUsage
Basic Setup
import { OnePaySDK } from 'onepay-sdk';
const onePaySDK = new OnePaySDK({
debug: true, // Enable debug logging
apiBaseUrl: 'https://api.onepay.lk' // Optional: custom API base URL
});
// Initialize the SDK
await onePaySDK.initialize();Event Listeners
IMPORTANT: The correct way to add event listeners is to use the SDK instance directly, not on a ref or DOM element.
// ✅ CORRECT WAY
onePaySDK.addEventListener({
onSuccess: (result) => {
console.log('Payment successful:', result);
// Handle successful payment
},
onFail: (result) => {
console.log('Payment failed:', result);
// Handle failed payment
},
onClose: (result) => {
console.log('Payment modal closed:', result);
// Handle modal close
}
});
// ❌ INCORRECT WAY - Don't do this
// onePaySDKRef.current.addEventListener({ ... }) // This won't work!Processing Payments
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: '[email protected]',
transactionRedirectUrl: 'https://your-site.com/payment-success',
apptoken: 'your-app-token'
});Processing Subscriptions
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: '[email protected]',
phone: '+94123456789'
},
apptoken: 'your-app-token'
});Direct Payment (with existing gateway URL)
await onePaySDK.processDirectPayment({
directGatewayURL: 'https://payment-gateway-url',
directTransactionId: 'transaction-id'
});React Example
import React, { useEffect, useState } from 'react';
import { OnePaySDK, PaymentResult } from '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 - CORRECT WAY
onePaySDK.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: '[email protected]',
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
OnePaySDK Constructor Options
firebaseConfig: Firebase configuration objectapiBaseUrl: Custom API base URL (default: 'https://api.onepay.lk')debug: Enable debug logging (default: false)
Methods
initialize(): Initialize the SDKaddEventListener(listeners): Add event listenersremoveEventListener(type, listener): Remove event listenersprocessPayment(data): Process a standard paymentprocessSubscription(data): Process a subscriptionprocessDirectPayment(data): Process a direct paymentclosePaymentGateway(): Close the payment gatewayisInitialized(): Check if SDK is initialized
Event Types
onePaySuccess: Fired when payment is successfulonePayFail: Fired when payment failsonePayClose: Fired when payment modal is closed
Troubleshooting
Event Listeners Not Working
If your event listeners aren't firing, make sure you're using the SDK instance directly:
// ✅ This will work
onePaySDK.addEventListener({ ... });
// ❌ This won't work
onePaySDKRef.current.addEventListener({ ... });Firebase Listener Issues
The SDK uses Firebase to listen for transaction updates. Make sure your Firebase configuration is correct and the SDK is properly initialized before processing payments.
License
MIT
