@patalink/node-api-client
v1.1.0
Published
Official PataLink API client - Simple, secure payment integration
Maintainers
Readme
@patalink/node-api-client
The official server-side Node.js SDK for PataLink. Integrate Mobile Money collections, instant B2C payouts (MTN Rwanda), real-time wallet balances, and webhook processing with automatic end-to-end payload encryption (AES-256-CBC + HMAC-SHA256).
⚡ Features
- Inbound Collections: Accept customer payments via MTN Mobile Money USSD prompt and card checkout (PesaPal).
- Instant B2C Disbursements: Send payouts directly to any MTN Mobile Money number in Rwanda (
078.../079...). - Live Wallet Balances: Check available cleared funds, pending amounts, and total volume before initiating payouts.
- Automated Encryption: Payload encryption (AES-256-CBC) and HMAC signing are handled seamlessly under the hood.
- Built-in Polling Utilities: Convenient
waitForCompletionandwaitForWithdrawalCompletionwith live progress callbacks. - Universal ESM & CJS: Full support for ES Modules (
import), CommonJS (require), and TypeScript.
📦 Installation
npm install @patalink/node-api-clientRequires Node.js 18.0.0 or higher.
🔑 Authentication & Prerequisites
To use this SDK in production:
- Create an account at patalink.me.
- Complete KYC identity verification in your dashboard (required for API keys and automated payouts).
- Navigate to Dashboard → Settings → Security & API Keys to copy:
- API Key: Starts with
pt_live_...(orpt_test_...for sandbox) - Encryption Key: 32-byte Base64-encoded string
- API Key: Starts with
Store these securely in your environment variables:
PATALINK_API_KEY=pt_live_your_api_key_here
PATALINK_ENCRYPTION_KEY=your_base64_encryption_key_here
PATALINK_BASE_URL=https://api.patalink.me🚀 Quick Start
Initialize the client once in your application:
import { createClient } from '@patalink/node-api-client';
const client = createClient({
apiKey: process.env.PATALINK_API_KEY!,
encryptionKey: process.env.PATALINK_ENCRYPTION_KEY!,
baseUrl: process.env.PATALINK_BASE_URL || 'https://api.patalink.me'
});CommonJS syntax is also fully supported:
const { createClient } = require('@patalink/node-api-client');📖 Usage Examples
1. Inbound Collections (Customer Payments)
Trigger a payment prompt on the customer's phone (MTN MoMo) or generate a checkout redirect for card payments (PesaPal):
// 1. Initiate payment request
const payment = await client.createPayment({
amount: 5000, // Amount in RWF (min 100 RWF)
paymentMethod: 'MTN', // 'MTN' or 'PesaPal'
phoneNumber: '0788820857', // Customer Mobile Money number
customerName: 'Alice Umutoni', // Optional
customerEmail: '[email protected]', // Optional
callbackUrl: 'https://example.com/done' // Required for Card payments
});
console.log('Payment Initiated! Transaction ID:', payment.transactionId);
// 2. Poll until customer confirms payment with their MoMo PIN
const verified = await client.waitForCompletion(payment.transactionId, {
maxAttempts: 30, // Poll up to 30 times
interval: 2500, // Check every 2.5 seconds
onProgress: (attempt, status) => {
console.log(`Poll #${attempt}: Status is ${status}`);
}
});
if (verified.status === 'success') {
console.log('✅ Payment confirmed! Deliver goods or grant access.');
} else {
console.log('❌ Payment failed or expired.');
}2. Instant B2C Disbursements (Payouts)
Send funds directly from your PataLink cleared wallet balance to any MTN Mobile Money number in Rwanda:
// 1. Dispatch payout
const payout = await client.createWithdrawal({
amount: 25000, // Amount in RWF (min 1,000, max 2,000,000)
destinationNumber: '0788820857', // MTN Rwanda number (078... / 079...)
network: 'MTN', // Network (default: 'MTN')
reference: 'PAYOUT-ORD-9021', // Optional: Your internal reference
recipientNote: 'Weekly Creator Earnings',// Optional: Note to recipient
idempotencyKey: 'payout-uuid-v4' // Optional: Prevents duplicate transfers
});
console.log('Payout Submitted:', payout.id, 'Status:', payout.status);
// 2. Poll until terminal status (paid or failed)
const finalPayout = await client.waitForWithdrawalCompletion(payout.id, {
maxAttempts: 30,
interval: 2000,
onProgress: (attempt, status) => {
console.log(`Disbursement Poll #${attempt}: ${status}`);
}
});
if (finalPayout.status === 'paid') {
console.log('✅ Funds delivered to recipient mobile wallet!');
}3. Check Wallet Balances & Account Info
Verify your merchant cleared balance before initiating payouts:
const account = await client.getAccountInfo();
console.log('User ID: ', account.id);
console.log('Available Cleared: ', account.availableBalance, 'RWF');
console.log('Total Gross Volume:', account.walletBalance, 'RWF');
console.log('Pending Funds: ', account.pendingBalance, 'RWF');
// Example: Guard payout against insufficient balance
if (account.availableBalance < 50000) {
throw new Error('Insufficient cleared balance to perform payout');
}4. Webhook Listener (Express / Node.js)
Configure a webhook endpoint in your server to receive asynchronous real-time events for collections and disbursements:
import express from 'express';
const app = express();
app.use(express.json());
app.post('/api/webhooks/patalink', (req, res) => {
const { event, data } = req.body;
// Handle Payout Events (Disbursements)
if (event === 'withdrawal.paid') {
console.log(`✅ Payout Delivered: ${data.withdrawalId} (${data.amount} RWF)`);
// Update order status in your database
} else if (event === 'withdrawal.failed') {
console.log(`❌ Payout Failed: ${data.withdrawalId} - Reason: ${data.failureReason}`);
}
// Handle Collection Events (Inbound Payments)
else if (event === 'payment.completed' || req.body.status === 'success') {
const txnId = req.body.transactionId || data?.transactionId;
console.log(`💰 Inbound Payment Confirmed: ${txnId}`);
// Fulfill customer order
}
// Always respond with 200 OK immediately
res.status(200).send('OK');
});
app.listen(3000, () => console.log('Webhook server running on port 3000'));🧪 Sandbox & Testing
You can test full workflows in the sandbox without touching real money:
- Use an API key starting with
pt_test_.... - Use test phone number
0788820857. - Withdrawal Simulation Conventions:
- Amounts ending in
99(e.g.,1099 RWF) simulate a failed disbursement. - Amounts ending in
55(e.g.,1555 RWF) stay pending for testing timeout handling. - All other amounts automatically transition to paid.
- Amounts ending in
Try out live requests in the interactive PataLink Developer Playground before writing code.
📚 API Reference
createClient(config: ClientConfig): PataLinkClient
| Option | Type | Required | Description |
|---|---|---|---|
| apiKey | string | Yes | Your PataLink API key (pt_live_... or pt_test_...) |
| encryptionKey | string | Yes | 32-byte Base64 encryption key from dashboard |
| baseUrl | string | No | API endpoint (defaults to https://api.patalink.me) |
| timeout | number | No | Request timeout in milliseconds (default: 30000) |
Client Methods
client.createPayment(request: PaymentRequest): Promise<PaymentResponse>client.getTransactionStatus(transactionId: string): Promise<TransactionStatus>client.waitForCompletion(transactionId: string, options?): Promise<TransactionStatus>client.createWithdrawal(request: WithdrawalRequest): Promise<WithdrawalResponse>client.getWithdrawalStatus(withdrawalId: string): Promise<WithdrawalStatus>client.waitForWithdrawalCompletion(withdrawalId: string, options?): Promise<WithdrawalStatus>client.getAccountInfo(): Promise<AccountInfo>client.listTransactions(options?): Promise<{ transactions, total }>client.listWithdrawals(options?): Promise<{ withdrawals, total }>
🔒 Security
All transaction initiation requests to PataLink are protected by AES-256-CBC payload encryption and signed with an HMAC-SHA256 signature generated using your secret encryption key. This SDK handles encryption and signing automatically for every request.
📄 License
MIT © PataLink
