# PayWay Cambodia SDK

Official Node.js SDK for PayWay Cambodia Payment Gateway API.

[![npm version](https://img.shields.io/npm/v/aba-payway-sdk.svg)](https://www.npmjs.com/package/aba-payway-sdk)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

## Features

- ✅ QR Code Payment Generation
- ✅ Web Purchase (Checkout Page)
- ✅ Payment Link Creation
- ✅ Transaction Detail Retrieval
- ✅ Transaction List (Filtered & Paginated)
- ✅ Check Transaction (Quick Status)
- ✅ Refund (Full & Partial)
- ✅ Exchange Rate Fetching
- ✅ Close/Cancel Transactions
- ✅ Hash Calculation Utilities
- ✅ Full TypeScript Support
- ✅ Sandbox Mode for Testing
- 🤖 AI Agent Skills for Claude, Copilot, Cursor & more

## Installation

```bash
npm install aba-payway-sdk
```

### 🤖 Install AI Agent Skills (Optional)

Enhance your AI coding assistant with PayWay SDK knowledge:

```bash
# Install skill for your preferred AI agent
npx aba-payway-sdk skills add claude

# Supported agents: claude, cursor, copilot, codex, opencode
npx aba-payway-sdk skills add claude cursor copilot

# List installed skills
npx aba-payway-sdk skills list
```

After installing, your AI assistant (GitHub Copilot, Claude, Cursor, etc.) will provide accurate PayWay integration code suggestions, best practices, and troubleshooting help.

## Quick Start

```javascript
const { PayWayClient } = require('aba-payway-sdk');

// Initialize with credentials
const payway = new PayWayClient({
  merchantId: 'your-merchant-id',
  apiKey: 'your-api-key',
  baseUrl: 'https://api.payway.com.kh'
});

// Generate QR code
const response = await payway.createQR({
  amount: 10,
  currency: 'USD',
  customerInfo: {
    email: 'customer@example.com',
    phone: '012345678'
  }
});

console.log('QR Image:', response.qrImage);
console.log('Transaction ID:', response.status.tran_id);
```

## API Reference

### Create QR Code

Generate a QR code for payment:

```javascript
const result = await payway.createQR({
  amount: 10.50,
  currency: 'USD',
  items: [
    { name: 'Item 1', quantity: 1, price: 10.50 }
  ],
  payer: {
    firstName: 'John',
    lastName: 'Doe',
    email: 'john@example.com',
    phone: '012345678'
  },
  callbackUrl: 'https://example.com/callback'
});
```

### Get Transaction Detail

Retrieve transaction details including status and history:

```javascript
const details = await payway.getTransactionDetail({
  tranId: '17394277693'
});

console.log('Payment Status:', details.data.payment_status);
console.log('Amount:', details.data.payment_amount);
console.log('Bank Reference:', details.data.bank_ref);

// Check status
if (details.data.payment_status === 'APPROVED') {
  console.log('Payment confirmed!');
}
```

**Payment Status Values:**
- `APPROVED` - Payment completed successfully
- `PRE-AUTH` - Payment held under pre-authorization
- `PENDING` - Awaiting completion
- `DECLINED` - Payment declined
- `REFUNDED` - Payment refunded
- `CANCELLED` - Transaction cancelled

**Note:** Limited to 10 requests per minute. Does not support real-time status checks during payment processing.

### Create Purchase (Web Checkout)

Create a web-based purchase that redirects customers to PayWay's checkout page:

```javascript
const purchaseData = await payway.createPurchase({
  amount: 25.00,
  currency: 'USD',
  firstName: 'John',
  lastName: 'Doe',
  email: 'john@example.com',
  phone: '012345678',
  items: [
    { name: 'Premium Plan', quantity: 1, price: 25.00 }
  ],
  tranId: 'ORDER-12345',
  continueSuccessUrl: 'https://yoursite.com/success',
  returnUrl: 'https://yoursite.com/return',
  callbackUrl: 'https://yoursite.com/api/webhook'
});

// Redirect user to checkout
console.log('Checkout URL:', purchaseData.checkout_url);
// Or use the form HTML
console.log('Form HTML:', purchaseData.form_html);
```

**Key Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `amount` | number | Yes | Transaction amount |
| `currency` | string | No | 'USD' or 'KHR' (default: 'USD') |
| `firstName` | string | Yes | Customer first name |
| `lastName` | string | Yes | Customer last name |
| `email` | string | Yes | Customer email |
| `phone` | string | Yes | Customer phone number |
| `items` | array | No | List of items being purchased |
| `tranId` | string | No | Custom transaction ID (auto-generated if not provided) |
| `continueSuccessUrl` | string | Yes | URL to redirect after successful payment |
| `returnUrl` | string | No | URL when customer cancels/returns |
| `callbackUrl` | string | No | Webhook URL for payment notifications |

**Use Cases:**
- E-commerce checkout pages
- Subscription payments
- Online services
- Digital products
- Any scenario requiring full web checkout

### Create Payment Link

Create a shareable payment link that customers can use to pay:

```javascript
const paymentLink = await payway.createPaymentLink({
  title: 'Product Purchase',
  amount: 50.00,
  currency: 'USD',
  description: 'Premium subscription',
  payment_limit: 10, // Max 10 payments allowed
  expired_date: Date.now() + 7 * 24 * 60 * 60 * 1000, // 7 days
  return_url: 'https://example.com/payment-callback',
  merchant_ref_no: 'LINK-001'
});

console.log('Payment Link:', paymentLink.data.payment_link);
console.log('Link ID:', paymentLink.data.id);
console.log('Status:', paymentLink.data.status); // OPEN
```

**Key Features:**
- Shareable payment URLs
- Multiple payment methods (cards, KHQR, wallets)
- Optional image upload (max 3MB)
- Payment limits and expiration dates
- Payout split for marketplaces
- **Requires:** RSA public key encryption

### Close Transaction

Cancel a pending transaction:

```javascript
const result = await payway.closeTransaction({
  tranId: 'ORDER-12345'
});

if (result.status.code === '00') {
  console.log('Transaction cancelled successfully');
}
```

**Response Codes:**
- `00` - Success (transaction cancelled)
- `1` - Wrong hash (authentication failed)
- `5` - Transaction not found
- `26` - Invalid merchant

## 🤖 AI Agent Skills

Supercharge your development workflow! Install PayWay SDK knowledge for your AI coding assistant:

```bash
# Install for your AI agent
npx aba-payway-sdk skills add claude

# Supported agents
npx aba-payway-sdk skills add claude cursor copilot codex opencode
```

**What you get:**
- ✅ Accurate code suggestions for PayWay integration
- ✅ Built-in best practices and security patterns
- ✅ Context-aware error handling examples
- ✅ Real-world integration patterns

**Example:** After installing the skill, ask your AI assistant:
> "Create a PayWay QR code for a $50 payment"

Your AI will generate complete, production-ready code with proper error handling and security best practices.

**CLI Commands:**
```bash
aba-payway-sdk skills add <agent>     # Install skill
aba-payway-sdk skills list             # List installed
aba-payway-sdk skills remove <agent>   # Remove skill
aba-payway-sdk skills help             # Show help
```

## Links

- **GitHub**: https://github.com/seabnavin19/payway-sdk
- **npm**: https://www.npmjs.com/package/aba-payway-sdk
- **Issues**: https://github.com/seabnavin19/payway-sdk/issues

## License

MIT