Skip to content

Unofficial JavaScript/TypeScript SDK for Payrexx API - Node.js compatible payment gateway integration

License

Notifications You must be signed in to change notification settings

misits/payrexx-js

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

2 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

payrexx-js SDK

npm version TypeScript License: 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 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

npm install payrexx-js

Using yarn

yarn add payrexx-js

Using pnpm

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

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)

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

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

// 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

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

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

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:

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:

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

// 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:

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

πŸ“š Documentation

Quick Links

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:

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:


Compatibility with Official PHP SDK

This JavaScript SDK provides complete feature parity with the official Payrexx PHP SDK v2.0.2, 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

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 file for details.


Support


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.

About

Unofficial JavaScript/TypeScript SDK for Payrexx API - Node.js compatible payment gateway integration

Topics

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published