# ABA PayWay SDK - Agent Skills

This directory contains individual skill files for AI coding assistants (GitHub Copilot, Claude, Cursor, etc.) to help with ABA PayWay SDK integration.

## Structure

Each skill is organized in its own directory with comprehensive examples:

```
skills/
├── aba-payway-qr/                      # QR code payment generation
│   └── SKILL.md
├── aba-payway-transaction-detail/      # Check payment status & details
│   └── SKILL.md
├── aba-payway-check-transaction/       # Quick status check (within 7 days)
│   └── SKILL.md
├── aba-payway-transaction-list/        # Get filtered transaction lists
│   └── SKILL.md
├── aba-payway-transaction-close/       # Cancel/close transactions
│   └── SKILL.md
├── aba-payway-refund/                  # Issue full/partial refunds
│   └── SKILL.md
├── aba-payway-pre-auth-complete/       # Complete pre-authorized transactions
│   └── SKILL.md
├── aba-payway-purchase/                # Web checkout/purchase flows
│   └── SKILL.md
├── aba-payway-token-purchase/          # Purchase using saved tokens (COF/AOF)
│   └── SKILL.md
├── aba-payway-payment-link/            # Create shareable payment links
│   └── SKILL.md
├── aba-payway-link-account/            # Link ABA bank accounts (Account on File)
│   └── SKILL.md
├── aba-payway-remove-account/          # Remove linked account tokens
│   └── SKILL.md
├── aba-payway-link-card/               # Link credit/debit cards (Card on File)
│   └── SKILL.md
├── aba-payway-remove-card/             # Remove linked card tokens
│   └── SKILL.md
├── aba-payway-exchange-rate/           # Get foreign exchange rates
│   └── SKILL.md
└── aba-payway-hash/                    # Hash calculation & verification
    └── SKILL.md
```

## Available Skills

### 1. QR Payment (`qr-payment`)
**Name:** `aba-payway-qr`

Generate dynamic QR codes for payments using the KHQR standard. Includes examples for:
- Basic QR generation
- Display options (image, deep link, QR string)
- React/Next.js integration
- Express.js API endpoints
- Restaurant, e-commerce, and invoice payments

### 2. Transaction Detail (`transaction-detail`)
**Name:** `aba-payway-transaction-detail`

Retrieve and verify payment transaction details (any age). Includes examples for:
- Payment status checking
- Webhook handlers
- Payment verification
- Full transaction history
- Next.js API routes
- **Rate limit:** 10 requests/minute

### 3. Check Transaction (`check-transaction`)
**Name:** `aba-payway-check-transaction`

Quick status check for recent transactions (within 7 days). Includes examples for:
- High-frequency status polling
- Real-time payment verification
- E-commerce checkout flows
- WebSocket real-time updates
- Bulk status checking
- **Rate limit:** 600 requests/second

### 4. Transaction List (`transaction-list`)
**Name:** `aba-payway-transaction-list`

Get filtered lists of transactions with pagination. Includes examples for:
- Daily sales reports
- Reconciliation reports
- Admin dashboards
- CSV exports
- Multi-page fetching
- Date/amount/status filtering
- **Rate limit:** 50 requests/minute
- **Date range:** Maximum 3 days

### 5. Transaction Close (`transaction-close`)
**Name:** `aba-payway-transaction-close`

Cancel or close pending transactions. Includes examples for:
- Order cancellation
- Timeout handling
- Bulk cancellation
- Duplicate prevention

### 6. Transaction Refund (`refund`)
**Name:** `aba-payway-refund`

Issue full or partial refunds for completed transactions. Includes examples for:
- Full refunds
- Partial refunds
- E-commerce order cancellation
- Item returns
- Bulk refund processing
- Automated refunds
- **Rate limit:** 500 requests/second
- **Requirement:** RSA public key encryption

### 7. Pre-Auth Complete (`pre-auth-complete`)
**Name:** `aba-payway-pre-auth-complete`

Complete pre-authorized transactions by capturing reserved funds. Includes examples for:
- Hotel checkout (complete after stay)
- Car rental returns (final charges)
- Restaurant bills with tips
- Service completion payments
- Card payments up to 10% above original amount
- Error handling for amount limits
- **Requirement:** RSA public key encryption
- **Note:** Can only complete each pre-auth once

### 8. Purchase/Checkout (`purchase`)
**Name:** `aba-payway-purchase`

Create web-based checkout flows with hosted payment pages. Includes examples for:
- Card payments
- KHQR payments
- Wallet integration (Alipay, WeChat)
- View types (hosted, popup, bottom sheet)
- Pre-authorization
- Google Pay integration

### 9. Payment Link (`payment-link`)
**Name:** `aba-payway-payment-link`

Create shareable payment links for accepting payments. Includes examples for:
- Basic payment links
- Payment links with images
- Payout split (marketplace)
- Time-limited links
- Subscription payments
- Invoice payments
- Bulk link creation
- **Requirement:** RSA public key encryption

### 10. Exchange Rate (`exchange-rate`)
**Name:** `aba-payway-exchange-rate`

Get current foreign exchange rates from ABA Bank. Includes examples for:
- Currency conversion
- Multi-currency pricing
- Rate caching strategies
- Scheduled rate updates
- React/Next.js integration
- **12 currencies:** AUD, SGD, EUR, GBP, MYR, THB, HKD, CNY, CAD, KRW, JPY, VND

### 11. Token Purchase (`token-purchase`)
**Name:** `aba-payway-token-purchase`

Process payments using saved card or account tokens from COF/AOF features. Includes examples for:
- Purchase using card tokens
- Purchase using account tokens
- Subscription billing
- Recurring payments
- One-click checkout
- Pre-authorization
- React hooks integration
- Express.js API endpoints
- Error handling for token expiry
- **Requirement:** Card on File or Account on File feature enabled

### 12. Link Account (`link-account`)
**Name:** `aba-payway-link-account`

Generate QR codes or deeplinks for account linking using Account on File (AOF). Includes examples for:
- QR code generation for account linking
- ABA Mobile deeplink integration
- Account linking workflows
- Return URL handling
- React/Next.js integration
- Express.js API endpoints
- **Requirement:** Account on File feature enabled

### 13. Remove Account Token (`remove-account`)
**Name:** `aba-payway-remove-account`

Remove a customer's linked account token from your platform. Includes examples for:
- Account token removal
- Confirmation workflows
- Error handling (invalid tokens, missing parameters)
- React/Next.js integration
- Express.js API endpoints
- Account management UI
- **Requirement:** Account on File feature enabled
- **Warning:** Action cannot be undone

### 14. Link Card (`link-card`)
**Name:** `aba-payway-link-card`

🔴 **CRITICAL:** Must use `enctype="multipart/form-data"` on forms. See [docs/LINK-CARD-REQUIREMENTS.md](../docs/LINK-CARD-REQUIREMENTS.md)

Generate card linking forms for Card on File (COF) feature. Includes examples for:
- Credit/debit card linking (Visa, Mastercard, JCB, UPI)
- Secure HTML form rendering with proper Content-Type
- Required fields: merchant_id, return_param, hash
- Card token management
- Return URL handling
- React iframe integration
- Express.js API endpoints
- **Requirement:** Card on File feature enabled
- **Critical:** Forms must have `enctype="multipart/form-data"` attribute

### 15. Remove Card Token (`remove-card`)
**Name:** `aba-payway-remove-card`

Remove a customer's linked card token from your platform. Includes examples for:
- Card token removal
- Confirmation workflows
- Error handling (invalid tokens, hash errors)
- React/Next.js/Vue.js integration
- Express.js API endpoints
- Card management UI
- Bulk card removal
- **Requirement:** Card on File feature enabled
- **Warning:** Action cannot be undone

### 16. Hash Calculation (`hash`)
**Name:** `aba-payway-hash`

Calculate HMAC SHA-512 hashes for API authentication and webhook verification. Includes examples for:
- Webhook signature verification
- Manual API request construction
- Multi-merchant platforms
- Testing hash generation
- Security best practices
- Admin workflows

## Installation

Skills are automatically installed when you run:

```bash
npm install aba-payway-sdk

# Install for GitHub Copilot / VS Code
npx aba-payway-sdk skills add copilot

# Install for other agents
npx aba-payway-sdk skills add claude
npx aba-payway-sdk skills add cursor
```

## Configuration

### Basic Setup

All skills use the `PayWayClient` which can be configured in multiple ways:

```typescript
import { PayWayClient } from 'aba-payway-sdk';

// Option 1: Using environment variables (recommended)
const client = new PayWayClient();
// Set PAYWAY_MERCHANT_ID and PAYWAY_API_KEY in .env

// Option 2: Using configuration object
const client = new PayWayClient({
  merchantId: 'ec000002',
  apiKey: 'your-api-key',
  sandbox: true
});
```

### Configuration Options

```typescript
interface PayWayConfig {
  merchantId?: string;     // Merchant ID (or set PAYWAY_MERCHANT_ID env var)
  apiKey?: string;         // API key (or set PAYWAY_API_KEY env var)
  rsaPublicKey?: string;   // RSA public key for refund/payment link (or set PAYWAY_RSA_PUBLIC_KEY)
  baseURL?: string;        // Custom API URL (or set PAYWAY_BASE_URL env var)
  sandbox?: boolean;       // Enable sandbox mode (or set PAYWAY_SANDBOX=true)
  debug?: boolean;         // Enable debug logging (or set DEBUG_PAYWAY=true)
}
```

### Environment Variables

Create a `.env` file in your project root:

```bash
# Required
PAYWAY_MERCHANT_ID=ec000002
PAYWAY_API_KEY=your-api-key-here

# Optional
PAYWAY_RSA_PUBLIC_KEY=your-rsa-public-key  # For refund & payment link APIs
PAYWAY_SANDBOX=true                         # Use sandbox environment
PAYWAY_BASE_URL=https://custom-url.com      # Custom base URL

# Debug Mode
DEBUG_PAYWAY=true                           # Log all requests & responses
```

### Debug Mode

Enable debug mode to see detailed logs of all API requests and responses during development:

```typescript
// Option 1: Enable in configuration
const client = new PayWayClient({
  merchantId: 'ec000002',
  apiKey: 'your-api-key',
  sandbox: true,
  debug: true  // Logs all API calls with URLs, parameters, and responses
});

// Option 2: Use environment variable
// Set DEBUG_PAYWAY=true in your .env file
```

**Debug Output Example:**
```
[PayWay SDK Debug] Initializing PayWay Client: {
  "merchantId": "ec000002",
  "sandbox": true,
  "baseURL": "https://checkout-sandbox.payway.com.kh",
  "debug": true
}

[PayWay SDK Debug] Request: {
  "method": "POST",
  "url": "https://checkout-sandbox.payway.com.kh/api/payment-gateway/v1/pwt/generate-qr",
  "data": {
    "merchant_id": "ec000002",
    "tran_id": "ORDER-123",
    "amount": "10.00",
    "hash": "***HIDDEN***"
  }
}

[PayWay SDK Debug] Response: {
  "status": 200,
  "data": {
    "status": {"code": "0", "message": "Success"},
    "qr_code": "..."
  }
}
```

**Features:**
- 🔍 Logs all HTTP requests with method, URL, and parameters
- 📥 Logs all HTTP responses with status and data
- 🔒 Automatically sanitizes sensitive data (API keys, hashes shown as `***HIDDEN***`)
- 🎯 Available across all SDK services
- 🐛 Perfect for debugging API integration issues

**Note:** Only enable debug mode in development environments. Disable in production to avoid logging sensitive information.

## Skill Locations

After installation, skills are placed in:

- **VS Code/Copilot**: `~/.copilot/skills/aba-payway-*/`
- **Claude**: `~/.claude/skills/aba-payway-*/`
- **Cursor**: `~/.cursor/skills/aba-payway-*/`

## How AI Agents Use Skills

AI coding assistants use **progressive disclosure** to load skills efficiently:

1. **Discovery**: AI knows which skills exist from YAML frontmatter
2. **Loading**: Full instructions load when relevant to your request
3. **Resources**: Additional examples loaded as needed

Skills activate automatically based on your prompts - no manual selection needed.

## VS Code Integration

For VS Code users, skills follow the official [Agent Skills standard](https://code.visualstudio.com/docs/copilot/customization/agent-skills):

- Located in `~/.copilot/skills/` (personal skills)
- Each skill has `SKILL.md` with YAML frontmatter
- Works with GitHub Copilot in VS Code, CLI, and coding agent
- Portable across different AI agents

## Usage Examples

When working with the AI assistant:

**QR Payments:**
```
"Generate a QR code for a $25 payment with items"
"Create a payment QR for my Express API"
```

**Transaction Status:**
```
"Check if transaction ORDER-123 was paid"
"Add webhook handler to verify payments"
```

**Transaction Cancellation:**
```
"Cancel a pending transaction"
"Add timeout cancellation for expired orders"
```

**Web Checkout:**
```
"Create a checkout page with PayWay"
"Integrate PayWay hosted payment form"
```

## Skill Format

Each skill follows the Agent Skills standard:

```markdown
---
name: skill-name
description: Brief description for AI discovery
---

# Skill Title

Detailed instructions, guidelines, and examples...
```

## Benefits

✅ **Specialized knowledge** - Each endpoint has focused documentation  
✅ **Rich examples** - Real-world code for common use cases  
✅ **Framework coverage** - Examples for Express, Next.js, React  
✅ **Best practices** - Security, error handling, and optimization  
✅ **Progressive loading** - Only relevant content loads  
✅ **Portable** - Works across multiple AI coding assistants  

## Contributing

To add a new skill:

1. Create a directory in `skills/`
2. Add `SKILL.md` with YAML frontmatter
3. Include comprehensive examples
4. Follow the existing skill structure

## Learn More

- [Agent Skills Documentation](https://code.visualstudio.com/docs/copilot/customization/agent-skills)
- [Agent Skills Standard](https://agentskills.io/)
- [ABA PayWay API Documentation](https://payway.ababank.com/)
