Skip to content

Latest commit

 

History

History
397 lines (311 loc) · 12 KB

File metadata and controls

397 lines (311 loc) · 12 KB

Hyperpay PTSP Node.js Client

Official TypeScript/Node.js client for Hyperpay PTSP payment gateway integration. Create payment links, check transaction status, and manage payments with a type-safe, Promise-based API.

Table of Contents

Overview

  • Purpose: Create Hyperpay PTSP payment links, check status, and manage transactions
  • Authentication: HTTP Basic Auth and API Key
  • Transport: Axios HTTP client
  • Type Safety: Full TypeScript support with DTOs

Requirements

  • Node.js 14.0.0 or higher
  • TypeScript 5.0+ (for development)

Installation

Option 1: Install from NPM (Recommended)

npm install @hyperpay/hyperpay-ptsp

Option 2: Install from GitHub

npm install https://github.com/HyperpayOpenSource/hyperpay-ptsp-nodejs

Or add to your package.json:

{
  "dependencies": {
    "@hyperpay/hyperpay-ptsp": "^1.0.0"
  }
}

Environment Variables

Set these in your .env file or system environment:

# Environment: 'production' or 'sandbox' (default: 'sandbox')
PAYMENT_LINK_ENVIRONMENT=sandbox

# Required: Basic Auth credentials
PAYMENT_LINK_BASIC_AUTH_USERNAME=your-username
PAYMENT_LINK_BASIC_AUTH_PASSWORD=your-password

# Optional: Request timeout in milliseconds (default: 15000)
PAYMENT_LINK_TIMEOUT=15000

Environment URLs (managed by the package):

  • Production: https://ptsp.hyperpay.com
  • Sandbox: https://ptsp-stg.hyperpay.com

Quick Start

TypeScript

import { 
  HyperpayPtspService, 
  CreatePaymentLinkRequest, 
  Config 
} from '@hyperpay/hyperpay-ptsp';

// Initialize from environment variables
const service = new HyperpayPtspService();

// Or initialize with custom config
const config = new Config('username', 'password', 'sandbox', 15000);
const service = new HyperpayPtspService(config);

// Create a payment link
const request = new CreatePaymentLinkRequest();
request.customerName = 'John Doe';
request.customerEmail = 'john@example.com';
request.amount = 250.00;
request.currency = 'SAR';
request.paymentOperation = 'pay';
request.merchantReference = 'INV-' + Date.now();

try {
  const response = await service.createPaymentLink(request);
  console.log('Payment Link:', response.paymentLink);
} catch (error) {
  console.error('Error:', error.message);
}

JavaScript (CommonJS)

const { 
  HyperpayPtspService, 
  CreatePaymentLinkRequest 
} = require('@hyperpay/hyperpay-ptsp');

const service = new HyperpayPtspService();

const request = new CreatePaymentLinkRequest();
request.customerName = 'John Doe';
request.customerEmail = 'john@example.com';
request.amount = 250.00;
request.currency = 'SAR';
request.paymentOperation = 'pay';
request.merchantReference = 'INV-' + Date.now();

service.createPaymentLink(request)
  .then(response => {
    console.log('Payment Link:', response.paymentLink);
  })
  .catch(error => {
    console.error('Error:', error.message);
  });

Usage Examples

Create Payment Link

import { HyperpayPtspService, CreatePaymentLinkRequest } from '@hyperpay/hyperpay-ptsp';

const service = new HyperpayPtspService();

const request = new CreatePaymentLinkRequest();
request.customerName = 'Jane Smith';
request.customerEmail = 'jane@example.com';
request.customerMobile = '00966512345678';
request.lang = 'en'; // or 'ar'
request.amount = 150.50;
request.currency = 'SAR';
request.paymentOperation = 'pay'; // 'pay' or 'authorize'
request.merchantReference = 'INV-' + Date.now();
request.tokenization = 'yes'; // Enable for recurring payments
request.expirationDate = '2026-12-31 23:59:59';
request.paymentMethods = ['VISA', 'MASTER', 'MADA'];
request.sendEmail = true;
request.sendSms = true;

try {
  const response = await service.createPaymentLink(request);
  
  console.log('Payment Link URL:', response.paymentLink);
  console.log('Payment Link Token:', response.paymentLinkToken);
  console.log('Response Code:', response.responseCode);
  console.log('Response Message:', response.responseMessage);
} catch (error) {
  console.error('Error:', error.message);
}

Using Fluent Setters

const request = new CreatePaymentLinkRequest()
  .setCustomerName('John Doe')
  .setCustomerEmail('john@example.com')
  .setAmount(100.00)
  .setCurrency('SAR')
  .setPaymentOperation('pay')
  .setMerchantReference('INV-' + Date.now())
  .setSendEmail(true);

const response = await service.createPaymentLink(request);

Get Payment Status

import { HyperpayPtspService } from '@hyperpay/hyperpay-ptsp';

const service = new HyperpayPtspService();

try {
  const status = await service.getStatusByMerchantReference('INV-123456');
  
  console.log('Response Code:', status.responseCode);
  console.log('Response Message:', status.responseMessage);
  console.log('Hyperpay ID:', status.hyperpayId);
  console.log('Payment Method:', status.paymentMethod);
  console.log('Amount:', status.amount);
  console.log('Currency:', status.currency);
  console.log('Customer Name:', status.customerName);
  console.log('Transaction Date:', status.transactionDate);
  console.log('Is Successful:', status.isSuccessful());
  
  // For tokenized payments
  if (status.cardToken) {
    console.log('Card Token:', status.cardToken);
    console.log('Agreement ID:', status.agreementId);
  }
} catch (error) {
  console.error('Error:', error.message);
}

Get Payment Link by Token

import { HyperpayPtspService } from '@hyperpay/hyperpay-ptsp';

const service = new HyperpayPtspService();

try {
  const paymentLink = await service.getPaymentLinkByToken(
    'c7e7f6957bf1bb6f6ba5ca1f93db1849',
    'hb_YourApiKeyHere'
  );
  
  console.log('Payment Link:', paymentLink.paymentLink);
  console.log('Status:', paymentLink.status);
  console.log('Amount:', paymentLink.amount);
  console.log('Currency:', paymentLink.currency);
  console.log('Customer Name:', paymentLink.customerName);
  console.log('Merchant Reference:', paymentLink.merchantReference);
} catch (error) {
  console.error('Error:', error.message);
}

API Reference

CreatePaymentLinkRequest

Field Type Required Description
customerName string Customer's full name
customerEmail string Customer's email address
customerMobile string Customer's mobile (international format)
lang string Language code (en or ar, default: en)
amount number Transaction amount (e.g., 250.00)
currency string ISO currency code (e.g., SAR, USD, AED)
paymentOperation string pay (immediate) or authorize (two-step)
merchantReference string Your unique transaction identifier
tokenization string yes or no (enable for recurring payments)
expirationDate string Link expiration (format: YYYY-MM-DD HH:mm:ss)
paymentMethods string[] Allowed methods (e.g., ['VISA', 'MASTER', 'MADA'])
sendEmail boolean Send link via email (default: false)
sendSms boolean Send link via SMS (default: false)

CreatePaymentLinkResponse

  • paymentLink - The payment URL to share with customers
  • paymentLinkToken - Unique payment link identifier
  • responseCode - Status code (00001 = success)
  • responseMessage - Human-readable status message

PaymentStatusResponse

  • responseCode - Transaction status code (00000 = success)
  • responseMessage - Status message
  • hyperpayId - Hyperpay transaction ID
  • paymentMethod - Payment method used (e.g., VISA, MASTER)
  • merchantReference - Your transaction reference
  • amount - Transaction amount
  • currency - Currency code
  • customerName - Customer's name
  • customerEmail - Customer's email
  • customerMobile - Customer's mobile
  • paymentOperation - pay or authorize
  • acquirerResponseCode - Bank response code
  • transactionDate - ISO 8601 timestamp
  • rrn - Retrieval Reference Number
  • authorizationCode - Authorization code
  • cardToken - Tokenized card (if tokenization enabled)
  • agreementId - Agreement ID for recurring payments
  • isSuccessful() - Method to check if transaction succeeded

PaymentLinkResponse

  • paymentLink - Payment link URL
  • paymentLinkToken - Token identifier
  • merchantReference - Your reference
  • amount - Transaction amount
  • currency - Currency code
  • status - Payment link status
  • customerName - Customer's name
  • customerEmail - Customer's email
  • customerMobile - Customer's mobile

Error Handling

The package throws HyperpayPtspException for all API and validation errors:

import { HyperpayPtspException } from '@hyperpay/hyperpay-ptsp';

try {
  const response = await service.createPaymentLink(request);
} catch (error) {
  if (error instanceof HyperpayPtspException) {
    console.error('Error Message:', error.message);
    console.error('HTTP Status Code:', error.statusCode);
    console.error('API Response Code:', error.responseCode);
    
    // Example error message format:
    // "[10002] Duplicate Merchant Reference | The merchant reference has already been taken."
  } else {
    console.error('Unexpected error:', error);
  }
}

Common Error Codes

Code Description
00000 Success
00001 Processed Successfully
10000 Validation Error
10002 Duplicate Merchant Reference
60000 Transaction Declined
60001 Insufficient Funds

For a complete list of error codes, see the Integration Documentation.

TypeScript Support

This package is written in TypeScript and includes full type definitions:

import { 
  Config,
  HyperpayPtspService,
  HyperpayPtspException,
  CreatePaymentLinkRequest,
  CreatePaymentLinkResponse,
  PaymentStatusResponse,
  PaymentLinkResponse
} from '@hyperpay/hyperpay-ptsp';

// Full IntelliSense and type checking
const service: HyperpayPtspService = new HyperpayPtspService();
const request: CreatePaymentLinkRequest = new CreatePaymentLinkRequest();
const response: CreatePaymentLinkResponse = await service.createPaymentLink(request);

Features

Full TypeScript Support - Complete type definitions and IntelliSense
Promise-Based API - Modern async/await syntax
DTOs with Fluent Setters - Type-safe request/response objects
Environment Management - Production and Sandbox support
Comprehensive Error Handling - Detailed error messages with field validation
Tokenization Support - Enable recurring payments
Multiple Payment Methods - VISA, Mastercard, MADA, and more
Express Examples - Ready-to-use API server examples

Express.js Integration

Check the examples/express-demo.ts file for a complete Express.js API implementation with endpoints for:

  • Creating payment links
  • Checking payment status
  • Retrieving payment link details

Links

License

MIT

Support

For issues and support, please visit the GitHub Issues page.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.