Node.js SDK
Official Node.js/TypeScript SDK for PayGate.
Node.js SDK
The official Node.js SDK for PayGate provides a convenient way to access the PayGate API from applications written in JavaScript or TypeScript.
Requirements: Node.js 18 or later. TypeScript 4.7+ recommended.
Installation
npm install @paygate/nodeyarn add @paygate/nodepnpm add @paygate/nodeQuick Start
import PayGate from '@paygate/node'
const paygate = new PayGate('sk_test_...')
// Create a payment
const payment = await paygate.payments.create({
amount: 5000,
currency: 'GHS',
payment_method: 'mobile_money',
provider: 'mtn',
phone: '0241234567'
})
console.log(payment.id)Configuration
API Key
// Using environment variable (recommended)
const paygate = new PayGate(process.env.PAYGATE_SECRET_KEY!)
// Or pass directly
const paygate = new PayGate('sk_test_...')Options
const paygate = new PayGate('sk_test_...', {
// API version (defaults to latest)
apiVersion: '2024-01-01',
// Request timeout in ms (default: 30000)
timeout: 60000,
// Maximum retries for failed requests (default: 3)
maxRetries: 5,
// Custom base URL (for testing)
baseUrl: 'https://api.sandbox.paygate.com.gh'
})Payments
Create a Payment
const payment = await paygate.payments.create({
amount: 5000,
currency: 'GHS',
payment_method: 'mobile_money',
provider: 'mtn',
phone: '0241234567',
description: 'Order #1234',
metadata: {
order_id: '1234',
customer_email: 'customer@example.com'
}
})Retrieve a Payment
const payment = await paygate.payments.retrieve('pay_abc123')List Payments
const payments = await paygate.payments.list({
limit: 10,
status: 'succeeded'
})
// Iterate through pages
for await (const payment of paygate.payments.list({ limit: 100 })) {
console.log(payment.id)
}Cancel a Payment
const payment = await paygate.payments.cancel('pay_abc123')Customers
Create a Customer
const customer = await paygate.customers.create({
email: 'customer@example.com',
name: 'John Doe',
phone: '0241234567',
metadata: {
user_id: '123'
}
})Update a Customer
const customer = await paygate.customers.update('cus_abc123', {
name: 'Jane Doe'
})Subscriptions
Create a Subscription
const subscription = await paygate.subscriptions.create({
customer: 'cus_abc123',
plan: 'plan_xyz789',
phone: '0241234567',
provider: 'mtn'
})Cancel a Subscription
const subscription = await paygate.subscriptions.cancel('sub_abc123')Webhooks
Verify Webhook Signature
import { Webhook } from '@paygate/node'
const endpointSecret = 'whsec_...'
// Express.js example
app.post('/webhooks', express.raw({ type: 'application/json' }), (req, res) => {
const signature = req.headers['x-paygate-signature'] as string
try {
const event = Webhook.constructEvent(
req.body,
signature,
endpointSecret
)
switch (event.type) {
case 'payment.succeeded':
const payment = event.data.object
console.log(`Payment ${payment.id} succeeded!`)
break
case 'payment.failed':
console.log('Payment failed')
break
}
res.json({ received: true })
} catch (err) {
console.error('Webhook error:', err.message)
res.status(400).send(`Webhook Error: ${err.message}`)
}
})Error Handling
import PayGate, { PayGateError } from '@paygate/node'
try {
const payment = await paygate.payments.create({
amount: 5000,
currency: 'GHS',
payment_method: 'mobile_money',
provider: 'mtn',
phone: '0241234567'
})
} catch (error) {
if (error instanceof PayGateError) {
console.error('Status:', error.statusCode)
console.error('Type:', error.type)
console.error('Code:', error.code)
console.error('Message:', error.message)
}
}Error Types
| Type | Description |
|---|---|
authentication_error | Invalid API key |
invalid_request_error | Invalid parameters |
rate_limit_error | Too many requests |
api_error | Server error |
payment_error | Payment-specific error |
TypeScript
The SDK is written in TypeScript and includes full type definitions:
import PayGate, { Payment, Customer } from '@paygate/node'
const paygate = new PayGate('sk_test_...')
// Types are automatically inferred
const payment: Payment = await paygate.payments.create({
amount: 5000,
currency: 'GHS',
payment_method: 'mobile_money',
provider: 'mtn',
phone: '0241234567'
})
// Type-safe access
console.log(payment.status) // 'pending' | 'processing' | 'succeeded' | 'failed'Idempotency
Use idempotency keys to safely retry requests:
const payment = await paygate.payments.create({
amount: 5000,
currency: 'GHS',
payment_method: 'mobile_money',
provider: 'mtn',
phone: '0241234567'
}, {
idempotencyKey: 'order_1234_payment'
})Invoices
Create an Invoice
const invoice = await paygate.invoices.create({
customer: 'cus_abc123',
description: 'Monthly subscription',
due_date: '2024-12-31',
line_items: [
{
description: 'Premium Plan',
quantity: 1,
unit_amount: 9999
}
]
})Send an Invoice
const invoice = await paygate.invoices.send('inv_abc123')Pay an Invoice
const invoice = await paygate.invoices.pay('inv_abc123', {
payment_method: 'mobile_money',
provider: 'mtn',
phone: '0241234567'
})Coupons
Create a Coupon
// Percentage discount
const coupon = await paygate.coupons.create({
code: 'SUMMER20',
percent_off: 20,
duration: 'once',
max_redemptions: 100
})
// Fixed amount discount
const coupon = await paygate.coupons.create({
code: 'FLAT50',
amount_off: 5000,
currency: 'GHS',
duration: 'repeating',
duration_in_months: 3
})Validate a Coupon
const validation = await paygate.coupons.validate('SUMMER20')
if (validation.valid) {
console.log(`Discount: ${validation.coupon.percent_off}%`)
}QR Codes
Create a QR Code
// Static QR (variable amount)
const qr = await paygate.qrCodes.create({
name: 'Store Counter',
type: 'static',
description: 'In-store payment'
})
// Dynamic QR (fixed amount)
const qr = await paygate.qrCodes.create({
name: 'Product Payment',
type: 'dynamic',
amount: 45000,
currency: 'GHS'
})
console.log(qr.payment_url)
console.log(qr.image_url)Reports
Generate a Report
const report = await paygate.reports.create({
report_type: 'payments',
name: 'Monthly Payments',
parameters: {
start_date: '2024-11-01',
end_date: '2024-11-30'
},
format: 'csv'
})
// Poll for completion
const completed = await paygate.reports.retrieve(report.id)
if (completed.status === 'completed') {
console.log(`Download: ${completed.file_url}`)
}Events
List Events
const events = await paygate.events.list({
type: 'payment.*',
limit: 50
})
for (const event of events.data) {
console.log(`${event.type}: ${event.id}`)
}Retrieve an Event
const event = await paygate.events.retrieve('evt_abc123')
console.log(event.data.object)Settings
Settlement Schedule
// Get current schedule
const schedule = await paygate.settings.settlementSchedule.retrieve()
// Update schedule
const updated = await paygate.settings.settlementSchedule.update({
frequency: 'daily',
preferred_day: null,
minimum_amount: 10000
})Transaction Limits
// Get limits
const limits = await paygate.settings.transactionLimits.retrieve()
// Update limits
const updated = await paygate.settings.transactionLimits.update({
max_single_payment: 1000000,
daily_payment_limit: 5000000,
monthly_payment_limit: 50000000
})Two-Factor Authentication
Enable 2FA
// Start 2FA setup
const setup = await paygate.twoFactor.setup()
console.log(setup.qr_code_url)
console.log(setup.secret)
// Verify and enable
const result = await paygate.twoFactor.verify({
code: '123456'
})
console.log(result.backup_codes)Disable 2FA
await paygate.twoFactor.disable({
code: '123456' // Or backup code
})