npm package: @onepaynpm/onepay-sdk
Description: Official OnePay payment gateway SDK for JavaScript applications
Author: OnePay Team
Latest version: 1.0.3

# OnePay SDK

A JavaScript SDK for integrating OnePay payment gateway into web applications.

## Installation

```bash
npm install onepay-sdk
```

## Usage

### Basic Setup

```javascript
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.

```javascript
// ✅ 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

```javascript
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 Subscriptions

```javascript
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'
});
```

### Direct Payment (with existing gateway URL)

```javascript
await onePaySDK.processDirectPayment({
  directGatewayURL: 'https://payment-gateway-url',
  directTransactionId: 'transaction-id'
});
```

## React Example

```tsx
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: '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

### OnePaySDK Constructor Options

- `firebaseConfig`: Firebase configuration object
- `apiBaseUrl`: Custom API base URL (default: 'https://api.onepay.lk')
- `debug`: Enable debug logging (default: false)

### Methods

- `initialize()`: Initialize the SDK
- `addEventListener(listeners)`: Add event listeners
- `removeEventListener(type, listener)`: Remove event listeners
- `processPayment(data)`: Process a standard payment
- `processSubscription(data)`: Process a subscription
- `processDirectPayment(data)`: Process a direct payment
- `closePaymentGateway()`: Close the payment gateway
- `isInitialized()`: Check if SDK is initialized

### Event Types

- `onePaySuccess`: Fired when payment is successful
- `onePayFail`: Fired when payment fails
- `onePayClose`: 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:

```javascript
// ✅ 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