# payrexx-js SDK

[![npm version](https://badge.fury.io/js/payrexx-js.svg)](https://badge.fury.io/js/payrexx-js)
[![TypeScript](https://img.shields.io/badge/%3C%2F%3E-TypeScript-%230074c1.svg)](http://www.typescriptlang.org/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

## Overview

This is an **unofficial** JavaScript/TypeScript client library for the Payrexx API, supporting API version **1.0 - 1.11**. It enables easy integration with Payrexx payment services from your Node.js applications with full TypeScript support.

**Based on the official PHP SDK** (`payrexx/payrexx`) and provides feature parity with full TypeScript support. See the [official PHP SDK](https://github.com/payrexx/payrexx-php) for more information.

> **Developed by Martin IS IT Services** - This is an independent implementation and is not officially affiliated with or endorsed by Payrexx AG.

---

## Features

- ✅ **Full TypeScript support** with comprehensive type definitions
- ✅ **Node.js focused** - Optimized for server-side applications with native crypto support
- ✅ **Promise-based API** with async/await support
- ✅ **Comprehensive error handling** with detailed error information
- ✅ **All Payrexx API endpoints** - Gateways, Transactions, Subscriptions, Invoices, Payouts, QR Codes
- ✅ **QR Code generation** - Built-in QR code image generation with multiple formats
- ✅ **Swiss-specific features** - Multi-language support, Swiss payment methods
- ✅ **Built-in validation** and helper methods
- ✅ **Complete documentation** and examples

---

## Installation

### Using npm

```bash
npm install payrexx-js
```

### Using yarn

```bash
yarn add payrexx-js
```

### Using pnpm

```bash
pnpm add payrexx-js
```

---

## Requirements

- **Node.js:** 16.0 or higher (for Node.js environments)
- **TypeScript:** 4.5 or higher (optional, but recommended)
- **Server Environment:** Node.js runtime required (uses native crypto module)

---

## Quick Start

### Basic Usage

```typescript
import { Payrexx, Gateway, PayrexxException } from 'payrexx-js'

// Initialize the client
const payrexx = new Payrexx({
  instance: 'your-instance-name', // e.g., 'demo' for https://demo.payrexx.com
  apiSecret: 'your-api-secret',   // Find this in your Payrexx instance admin panel
  version: '1.11'                 // Optional, defaults to latest
})

// Create a payment gateway
async function createPayment() {
  try {
    const gateway = new Gateway({
      amount: 10000,        // 100.00 CHF in cents
      currency: 'CHF',
      successRedirectUrl: 'https://example.com/success',
      failedRedirectUrl: 'https://example.com/failed',
      referenceId: 'ORDER-123'
    })

    // Add customer information
    gateway.addField('email', 'customer@example.com')
    gateway.addField('forename', 'John')
    gateway.addField('surname', 'Doe')

    // Create the payment gateway
    const response = await payrexx.create(gateway)
    const createdGateway = response.data[0]

    console.log('Payment Link:', createdGateway.link)
    console.log('Gateway ID:', createdGateway.id)
    
    return createdGateway
  } catch (error) {
    if (error instanceof PayrexxException) {
      console.error('Payrexx Error:', error.message)
      console.error('Error Code:', error.code)
    } else {
      console.error('Unexpected error:', error)
    }
  }
}
```

### JavaScript (CommonJS)

```javascript
const { Payrexx, Gateway } = require('payrexx-js')

const payrexx = new Payrexx({
  instance: 'your-instance-name',
  apiSecret: 'your-api-secret'
})

// Rest of the code is the same...
```

---

## API Reference

### Client Configuration

```typescript
const payrexx = new Payrexx({
  instance: string,           // Required: Your Payrexx instance name
  apiSecret: string,          // Required: Your API secret
  apiBaseDomain?: string,     // Optional: Custom API domain (for platform accounts)
  version?: string,           // Optional: API version (defaults to '1.11')
  timeout?: number,           // Optional: Request timeout in milliseconds
  headers?: Record<string, string> // Optional: Custom HTTP headers
})
```

### API Methods

All methods return a `Promise<PayrexxApiResponse<T>>` where `T` is the response type.

#### Gateway Operations

```typescript
// Create a payment gateway
const response = await payrexx.create(gateway)

// Get all gateways
const gateways = await payrexx.getAll(new Gateway())

// Get specific gateway
const gateway = new Gateway()
gateway.id = 123456
const response = await payrexx.getOne(gateway)

// Update gateway
const updatedGateway = await payrexx.update(gateway)

// Delete gateway
await payrexx.delete(gateway)
```

#### Transaction Operations

```typescript
import { Transaction } from 'payrexx-js'

// Refund a transaction
const transaction = new Transaction(123456)
transaction.setAmount(5000) // Partial refund: 50.00 CHF
const response = await payrexx.refund(transaction)

// Capture a pre-authorized transaction
await payrexx.capture(transaction)

// Get transaction details
const response = await payrexx.getOne(transaction)
```

#### QR Code Operations

```typescript
import { QRCode } from 'payrexx-js'

// Create a QR code for payments
const qrCode = new QRCode({
  referenceId: 'QR-ORDER-001',
  title: 'Product Purchase',
  amount: 2999, // 29.99 CHF in cents
  currency: 'CHF',
  validity: 60 // Valid for 60 minutes
})

// Add customer fields
qrCode
  .addField('email', 'customer@example.com')
  .addField('forename', 'John')
  .addField('surname', 'Doe')

// Create QR code via API
const response = await payrexx.create(qrCode)
const createdQR = response.data[0]

console.log('Payment Link:', createdQR.link)
console.log('QR Image URL:', createdQR.qr)

// Generate QR code images locally
const pngBuffer = await qrCode.generateQRImage(createdQR.link, 'png', {
  width: 300,
  margin: 2,
  errorCorrectionLevel: 'M'
})

// Generate data URL for browsers
const dataUrl = await qrCode.generateQRDataURL(createdQR.link)
```

### Gateway Configuration

```typescript
const gateway = new Gateway({
  amount: 10000,              // Amount in cents (required)
  currency: 'CHF',            // Currency code (required)
  sku: 'PRODUCT-123',         // Product SKU
  vatRate: 7.7,              // VAT rate percentage
  referenceId: 'ORDER-456',   // Your reference ID
  validity: 60,              // Validity in minutes
})

// Fluent API methods
gateway
  .setAmount(15000)
  .setCurrency('EUR')
  .setSuccessRedirectUrl('https://example.com/success')
  .setFailedRedirectUrl('https://example.com/failed')
  .setPsp([4])               // Specific payment provider
  .setPm(['mastercard'])     // Specific payment methods
  .setPreAuthorization(true) // Enable pre-authorization
  .setSubscriptionState(true) // Enable subscription
  .addField('email', 'customer@example.com')
```

### Multi-Language Support

Payrexx supports multi-language content for Swiss markets:

```typescript
gateway.setPurpose({
  1: 'Produktkauf (DE)',     // German
  2: 'Product Purchase (EN)', // English  
  3: 'Achat de produit (FR)', // French
  4: 'Acquisto prodotto (IT)' // Italian
})

// Multi-language basket items
gateway.setBasket([
  {
    name: {
      1: 'Produkt Name (DE)',
      2: 'Product Name (EN)',
      3: 'Nom du produit (FR)',
      4: 'Nome del prodotto (IT)'
    },
    quantity: 1,
    amount: 5000
  }
])
```

### Error Handling

The SDK provides comprehensive error handling for both client-side validation and API responses:

```typescript
import { PayrexxException } from 'payrexx-js'

try {
  // Client-side validation (throws immediately)
  const gateway = new Gateway({
    amount: 1000,
    currency: 'CHF'
  })
  
  gateway.validate() // Throws Error if required fields missing
  
  // API call
  const response = await payrexx.create(gateway)
  
  // Check API response status
  if (response.status === 'error') {
    console.log('API Error:', response.message)
    return
  }
  
  // Success
  console.log('Gateway created:', response.data[0])
  
} catch (error) {
  if (error instanceof PayrexxException) {
    console.log('Payrexx Error:', error.message)
    console.log('Error Code:', error.code)
  } else {
    console.log('Validation Error:', error.message)
  }
}
```

### Subscription Payments

```typescript
// Create recurring payment gateway
const gateway = new Gateway({
  amount: 2999,        // 29.99 CHF monthly
  currency: 'CHF'
})

gateway
  .setSubscriptionState(true)
  .setSubscriptionInterval('P1M')    // Monthly billing
  .setSubscriptionPeriod('P1Y')      // For 1 year
  .setSubscriptionCancellationInterval('P3M') // 3 months notice

const response = await payrexx.create(gateway)
```

### Platform Accounts

For platform accounts with custom domains:

```typescript
const payrexx = new Payrexx({
  instance: 'client',              // Subdomain part
  apiSecret: 'your-api-secret',
  apiBaseDomain: 'platform.yourcompany.com' // Custom domain
})
```

---

## 📚 Documentation

### Quick Links
- [📖 **Full Documentation**](./docs/) - Complete guides and API reference
- [🚀 **Quick Start**](./docs/getting-started/quick-start.md) - Get started in 5 minutes
- [⚡ **Frontend Integration**](./docs/integration/frontend-integration.md) - Next.js & Nuxt.js guide
- [📋 **API Reference**](./docs/api/) - Detailed API documentation

## Examples

Check the `/examples` directory for comprehensive working examples organized by category:

### Basic Examples (`examples/basic/`)
- **Quick Start** - `npm run quick-start` - Simple payment gateway creation
- **Gateway Creation** - `npm run gateway` - Complete gateway with customer fields
- **Invoice Management** - `npm run invoice` - Invoice creation and management
- **Transaction Operations** - `npm run transaction` - Transaction status and operations
- **QR Terminal** - `npm run qr-terminal` - QR code generation with terminal display

### Advanced Features (`examples/advanced/`)
- **Subscriptions** - `npm run subscription` - Recurring payment setup
- **Basket Items** - `npm run basket` - Multi-item checkout with detailed basket
- **Pre-Authorization** - `npm run pre-auth` - Hold funds without charging

### Payment Methods (`examples/payment-methods/`)
- **Specific Methods** - `npm run payment-methods` - Restrict to specific payment methods

### Webhooks (`examples/webhooks/`)
- **Signature Check** - `npm run webhook-check` - Verify webhook authenticity

All examples include proper error handling, TypeScript support, and are ready to run with your credentials.

---

## TypeScript Support

This SDK is built with TypeScript and provides complete type definitions:

```typescript
import { 
  Payrexx,
  Gateway, 
  Transaction,
  QRCode,
  PayrexxException,
  GatewayResponse,
  TransactionResponse,
  QRCodeResponse,
  Currency,
  PayrexxConfig
} from 'payrexx-js'

// Full IntelliSense support
const config: PayrexxConfig = {
  instance: 'demo',
  apiSecret: 'secret'
}

const payrexx = new Payrexx(config)
const response: PayrexxApiResponse<GatewayResponse> = await payrexx.create(gateway)
```

---

## Important Notes

**Node.js Only**: This SDK is designed for Node.js server environments and uses native Node.js modules like `crypto`. It cannot run in browsers due to these dependencies.

For client-side payment integration, use:
- Payrexx's hosted payment pages (gateway links)
- Payrexx's JavaScript widget for embedding payment forms
- Direct API calls from your server to create payment sessions

---

## API Documentation

For detailed information about the Payrexx API endpoints and data models, please refer to the official documentation:
- **Payrexx API Docs**: https://developers.payrexx.com/reference/rest-api
- **PHP SDK Reference**: https://github.com/payrexx/payrexx-php

---

## Compatibility with Official PHP SDK

This JavaScript SDK provides **complete feature parity** with the [official Payrexx PHP SDK v2.0.2](https://github.com/payrexx/payrexx-php), supporting all API endpoints and operations.

### 📊 Feature Comparison

| Feature | JS SDK | PHP SDK | Status | Notes |
|---------|--------|---------|--------|--------|
| **Gateway Management** | ✅ | ✅ | ✅ Complete | Create, update, delete, getOne operations |
| **Transaction Operations** | ✅ | ✅ | ✅ Complete | Charge, refund, capture, cancel, getAll, getOne |
| **Subscription Management** | ✅ | ✅ | ✅ Complete | Create, cancel, update recurring payments |
| **Invoice Management** | ✅ | ✅ | ✅ Complete | Create, delete, getOne invoice operations |
| **Payout Management** | ✅ | ✅ | ✅ Complete | Create, getOne payout operations |
| **QR Code Management** | ✅ | ✅ | ✅ Complete | Create, delete, getOne + local image generation |
| **QR Code Scanning** | ✅ | ✅ | ✅ Complete | Delete scan operations |
| **Bills** | ✅ | ✅ | ✅ Complete | Create, update, delete, getAll, getOne |
| **Payment Methods** | ✅ | ✅ | ✅ Complete | getAll available payment methods |
| **Payment Providers** | ✅ | ✅ | ✅ Complete | getAll available payment service providers |
| **Design Management** | ✅ | ✅ | ✅ Complete | Create, update, delete, getAll, getOne |
| **Auth Tokens** | ✅ | ✅ | ✅ Complete | Create authentication tokens |
| **Pages** | ✅ | ✅ | ✅ Complete | getOne page operations |
| **Signature Check** | ✅ | ✅ | ✅ Complete | Webhook signature verification |

### 🚀 Additional JS SDK Features

| Feature | JS SDK | PHP SDK | Notes |
|---------|--------|---------|--------|
| **Local QR Generation** | ✅ | ❌ | Generate QR code images locally (PNG, SVG, Base64) |
| **TypeScript Support** | ✅ | ❌ | Full type definitions and IntelliSense |
| **Promise-based API** | ✅ | ❌ | Modern async/await syntax |
| **Built-in Validation** | ✅ | ❌ | Client-side validation before API calls |

### 📋 API Method Support

All API methods from the PHP SDK are fully supported:

- `create()` - Create new resources
- `update()` - Update existing resources  
- `delete()` - Delete resources
- `cancel()` - Cancel subscriptions/transactions
- `getAll()` - List resources with pagination
- `getOne()` - Get single resource by ID
- `charge()` - Charge transactions
- `refund()` - Refund transactions (full/partial)
- `capture()` - Capture pre-authorized transactions

### 🎯 API Version Compatibility

- **Supported Versions**: 1.0 through 1.11 (same as PHP SDK)
- **Default Version**: 1.11 (latest)
- **Backward Compatibility**: Full support for older API versions

---

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request. This is a community-maintained project inspired by the official PHP SDK.

### Development Setup

```bash
git clone https://github.com/misits/payrexx-js.git
cd payrexx-js
npm install

# Build the project
npm run build

# Run tests
npm test

# Development mode with watch
npm run dev
```

---

## License

MIT License - see the [LICENSE](LICENSE) file for details.

---

## Support

- **Issues**: https://github.com/misits/payrexx-js/issues
- **Developer**: Martin IS IT Services - dev@misits.ch
- **Official Payrexx Support**: https://support.payrexx.com/de/support/home
- **API Documentation**: https://developers.payrexx.com/reference/rest-api

---

## Disclaimer

This is an **unofficial** SDK created by Martin IS IT Services. For official support, please refer to Payrexx's official documentation and support channels.

The SDK is based on the official PHP SDK structure and aims to provide feature parity with full JavaScript/TypeScript support. This implementation is not affiliated with or endorsed by Payrexx AG.