zenpays-sdk
v0.2.0
Published
Official ZenPays JavaScript SDK for payment processing
Maintainers
Readme
ZenPays JavaScript SDK
Official JavaScript/TypeScript SDK for the ZenPays payment platform.
Installation
npm install zenpays
# or
pnpm add zenpays
# or
yarn add zenpaysRequirements
- Node.js 18.0.0 or higher
- Modern browser with Web Crypto API support
Quick Start
import { ZenPays } from 'zenpays'
const zenpays = new ZenPays({
apiKey: 'zp_test_your_api_key',
secretSalt: 'your_secret_salt',
})
// Create a payment intent
const intent = await zenpays.payments.createPaymentIntent({
amount: 1000,
currency: 'USD',
customerEmail: '[email protected]',
})
console.log(intent.paymentPageUrl)Configuration
import { ZenPays } from 'zenpays'
const zenpays = new ZenPays({
// Required: Your API key (zp_live_* for production, zp_test_* for sandbox)
apiKey: 'zp_test_your_api_key',
// Required for authenticated requests: Secret salt for HMAC signature
secretSalt: 'your_secret_salt',
// Optional: Override the base URL (auto-detected from API key prefix)
baseUrl: 'https://api.zenpayz.com',
// Optional: API version (default: 'v1')
apiVersion: 'v1',
// Optional: Request timeout in milliseconds (default: 30000)
timeout: 30000,
})Environment Detection
The SDK automatically detects the environment based on your API key prefix:
zp_live_*→ Production (https://api.zenpayz.com)zp_test_*→ Sandbox (https://sandbox.api.zenpayz.com)
API Reference
Payments
// Create a payment intent
const intent = await zenpays.payments.createPaymentIntent({
amount: 1000,
currency: 'USD',
customerEmail: '[email protected]',
customerPhone: '+1234567890',
metadata: { orderId: 'order_123' },
})
// Get payment intent details
const details = await zenpays.payments.getPaymentIntent('pi_xxx')
// List transactions
const transactions = await zenpays.payments.listTransactions({
status: 'completed',
limit: 10,
})Refunds
// Create a refund
const refund = await zenpays.refunds.create({
transactionId: 'txn_xxx',
amount: 500,
reason: 'Customer request',
})
// Get refund details
const refundDetails = await zenpays.refunds.get('ref_xxx')Payouts
// Create a payout
const payout = await zenpays.payouts.create({
amount: 10000,
currency: 'USD',
beneficiaryId: 'ben_xxx',
})
// List payouts
const payouts = await zenpays.payouts.list({ status: 'completed' })Wallet
// Get wallet balance
const balance = await zenpays.wallet.getBalance('USD')
// Get all balances
const balances = await zenpays.wallet.getAllBalances()
// List wallet transactions
const walletTxns = await zenpays.wallet.listTransactions({
from: '2024-01-01',
to: '2024-12-31',
})Customers
// Create a customer
const customer = await zenpays.customers.create({
email: '[email protected]',
firstName: 'John',
lastName: 'Doe',
})
// Get customer details
const customerDetails = await zenpays.customers.get('cust_xxx')
// Search customers
const results = await zenpays.customers.search('[email protected]')Merchants
// Get merchant profile
const profile = await zenpays.merchants.getProfile()
// List API keys
const apiKeys = await zenpays.merchants.listApiKeys()
// Configure webhooks
const webhook = await zenpays.merchants.createWebhook({
url: 'https://your-site.com/webhooks',
events: ['payment.completed', 'refund.created'],
})Checkout
// Create a checkout session
const session = await zenpays.checkout.createSession({
amount: 5000,
currency: 'USD',
successUrl: 'https://your-site.com/success',
cancelUrl: 'https://your-site.com/cancel',
})
// Get on-ramp providers
const providers = await zenpays.checkout.getOnRampProviders('USD')Analytics
// Get dashboard overview
const overview = await zenpays.analytics.getDashboardOverview('30d')
// Get revenue trends
const trends = await zenpays.analytics.getRevenueTrends('30d', 'day')
// Generate a report
const report = await zenpays.analytics.generateReport({
type: 'transactions',
from: '2024-01-01',
to: '2024-12-31',
})Error Handling
The SDK throws typed errors for different scenarios:
import {
ZenPaysError,
AuthenticationError,
ValidationError,
NotFoundError,
RateLimitError,
NetworkError,
} from 'zenpays'
try {
await zenpays.payments.createPaymentIntent({ amount: 1000, currency: 'USD' })
} catch (error) {
if (error instanceof AuthenticationError) {
console.error('Invalid API key')
} else if (error instanceof ValidationError) {
console.error('Validation failed:', error.message)
} else if (error instanceof RateLimitError) {
console.error('Rate limited. Retry after:', error.retryAfter, 'seconds')
} else if (error instanceof NotFoundError) {
console.error('Resource not found')
} else if (error instanceof NetworkError) {
console.error('Network error:', error.message)
} else if (error instanceof ZenPaysError) {
console.error('API error:', error.message, error.code)
}
}TypeScript Support
The SDK is written in TypeScript and includes full type definitions:
import type {
PaymentIntent,
CreatePaymentIntentRequest,
Transaction,
Customer,
WalletBalance,
PaginatedResponse,
} from 'zenpays'Utilities
The SDK includes helpful utility functions:
import {
formatCurrency,
formatDisplayDate,
validateEmail,
validatePhone,
validateAmount,
maskSensitive,
} from 'zenpays'
// Format currency
formatCurrency(1234.56, 'USD') // '$1,234.56'
// Format date
formatDisplayDate(new Date(), { format: 'long' }) // 'January 15, 2024, 3:30 PM'
// Validate inputs
validateEmail('[email protected]') // true
validatePhone('+1234567890') // true
validateAmount(100) // true
// Mask sensitive data
maskSensitive('4242424242424242') // '4242********4242'Developer Resources
API Documentation
For comprehensive API documentation, guides, and examples, visit:
- API Documentation: https://docs.zenpayz.com/
Postman Collection
We provide a pre-configured Postman collection with all 53 Merchant API endpoints ready to use:
- Local: Included in this package at
./postman/zenpay-merchant-service.postman_collection.json - Dashboard: Also available in the Merchant Dashboard under Developer Tools → Documentation
- Features:
- All authentication methods pre-configured (JWT and API Key + HMAC)
- Example request bodies for every endpoint
- Auto-capture of tokens on login
- Environment variables for easy switching between sandbox and production
The collection includes endpoints for:
- Authentication (login, 2FA, password management)
- Merchant Profile & Settings
- API Keys Management
- Webhooks Configuration
- Transactions & Analytics
- Payouts
- KYC Document Management
- Team Management
Authentication
The ZenPays platform uses two authentication methods:
API Key + HMAC Signature (for SDK/API integration - this SDK handles it automatically)
- Headers:
Authorization,x-timestamp,x-signature,x-secret-salt - The SDK generates signatures automatically when you provide
secretSalt
- Headers:
JWT Access Token (for merchant dashboard endpoints)
- Used after login for session-based authentication
License
MIT
