payhero-devkit
v1.1.1
Published
A modular developer toolkit for PayHero APIs
Readme
payhero-devkit
A lightweight Node.js SDK for PayHero APIs, enabling developers to initiate STK Push payments, poll transaction statuses, and check wallet balances with a focus on simplicity and webhook-free workflows.
Features
This SDK provides the following methods:
- stkPush(data: StkPushRequest) – Initiates an STK push payment request.
- transactionStatus(reference: string) – Retrieves the status of a specific transaction.
- pollTransactionStatus(reference: string, options?: PollingOptions) – Polls transaction status until success or failure.
- servicewalletBalance(wallet_type?: WalletBalanceRequest) – Fetches the balance of the service wallet.
- paymentWalletBalance(walletChannelID: number) – Gets the balance of a specific payment wallet.
- serviceWalletTopup(data: ServiceWalletTopUpRequest) – Performs a service wallet top-up via STK push.
- walletWithdraw(data: WalletWithdrawRequest) – Processes a withdrawal from the wallet.
Installation
Install the SDK via npm:
npm install payhero-devkityarn add payhero-devkitpnpm add payhero-devkitbun add payhero-devkitObtain your authToken from the PayHero Developer Portal.
Importing in Your Project
JavaScript (CommonJS)
const { PayHeroClient } = require('payhero-devkit');TypeScript / ES Modules
import { PayHeroClient } from 'payhero-devkit';Example Usage
Initialize the Client
JavaScript:
const { PayHeroClient } = require('payhero-devkit');
const client = new PayHeroClient({ authToken: 'Basic your_base64_encoded_token' });TypeScript:
import { PayHeroClient } from 'payhero-devkit';
const client = new PayHeroClient({ authToken: 'Basic your_base64_encoded_token' });STK Push
JavaScript:
async function initiateStkPush() {
try {
const response = await client.stkPush({
phone_number: '25470000000',
amount: 1,
provider: 'm-pesa',
channel_id: '1234',
external_reference: 'Trans2-Test',
});
console.log('STK Push:', response);
} catch (error) {
console.error('Error:', error.message);
}
}
initiateStkPush();TypeScript:
import { PayHeroClient, StkPushRequest } from 'payhero-devkit';
async function initiateStkPush() {
try {
const payload: StkPushRequest = {
phone_number: '254700000000',
amount: 1,
provider: 'm-pesa',
channel_id: '0000',
external_reference: 'Trans2-Test',
};
const response = await client.stkPush(payload);
console.log('STK Push:', response);
} catch (error) {
console.error('Error:', (error as Error).message);
}
}
initiateStkPush();Poll Transaction Status
JavaScript:
async function pollTransaction() {
try {
const response = await client.pollTransactionStatus('transaction_reference_code', {
interval: 3000,
maxAttempts: 5,
});
console.log('Status:', response);
} catch (error) {
console.error('Error:', error.message);
}
}
pollTransaction();Get Transaction Status
JavaScript:
async function checkStatus() {
try {
const response = await client.transactionStatus('transaction_reference_code or mpesa code');
console.log('Status:', response);
} catch (error) {
console.error('Error:', error.message);
}
}
checkStatus();Payment Wallet Balance
JavaScript:
async function checkPaymentWalletBalance() {
try {
const response = await client.paymentWalletBalance('channel_id');
console.log('Balance:', response);
} catch (error) {
console.error('Error:', error.message);
}
}
checkPaymentWalletBalance();Get Service Wallet Balance
async function checkServiceWalletBalance() {
try {
const response = await client.serviceWalletBalance('channel_id');
console.log('Balance:', response);
} catch (error) {
console.error('Error:', error.message);
}
}
checkPaymentWalletBalance();Service Wallet Topup
async function topUp() {
try {
const response = await client.serviceWalletTopup({
phone_number: '2547000000',
amount: 1
});
console.log('STK Push:', response);
} catch (error) {
console.error('Error:', error.message);
}
}
initiateStkPush();Wallet Withdraw
async function withdraw() {
try {
const withdraw = await payhero.walletWithdraw({
amount: 500,
phone_number: "0712345678",
network_code: "63902 (MPesa) or 63903 (Airtel Money)",
channel: "mobile",
channel_id: 1001
});
console.log(withdraw);
} catch (error) {
console.error('Error:', error.message);
}
}Error Handling
All methods throw JavaScript errors when required fields are missing or requests fail. Use try...catch blocks for safer integration
Functions
The SDK provides the following functions via the PayHeroClient class:
| Function | Description | |-----------|-------------| | stkPush | Initiates an STK Push payment. | | pollTransactionStatus | Polls the status of a transaction. | | paymentWalletBalance | Retrieves the balance of a payment wallet. | | serviceWalletBalance | Retrives the balance of a serveice wallet | | serviceWalletTopup | Initiates an STK push and sends money to a service wallet | | transactionStatus | Gets the status of a transaction | | walletWithdraw | Withdraws money from a payment wallet to a mobile number|
Function Parameters and Responses
PayHeroClient Constructor
| Parameter | Type | Description | Required |
|------------|------|-------------|-----------|
| authToken | string | Base64-encoded PayHero API token | Yes |
stkPush
Initiates an STK Push payment
Request Parameters:
| Parameter | Type | Description | Required |
|------------|------|-------------|-----------|
| phone_number | string | Phone number (e.g., "25470000000") | Yes |
| amount | number | Payment amount (e.g., 1) | Yes |
| provider | string | Payment provider ("m-pesa or sasapay") | Yes |
| channel_id | nnumber | Channel ID (e.g., "1234") | Yes |
| external_reference | string | Unique transaction ID (e.g., "Trans2-Test") | Yes |
| customer_name | string | Customer name (e.g., "John Doe") | No |
| credential_id | string | Credential ID for provider | No |
| network_code | string | Network code for provider | No |
Response:
| Field | Type | Description |
|--------|------|-------------|
| success | boolean | Whether the request succeeded |
| status | string | Status (e.g., "QUEUED") |
| reference | string | Transaction reference (e.g., "dc71-...") |
| CheckoutRequestID | string | PayHero request ID (e.g., "ws_CO_...") |
| external_reference | string | Your transaction ID (e.g., "Trans2-Test") |
pollTransactionStatus
Polls the status of a transaction.
Parameters:
| Parameter | Type | Description | Required |
|------------|------|-------------|-----------|
| reference | string | Transaction reference from stkPush | Yes |
| options.interval | number | Polling interval (ms, default: 3000) | No |
| options.maxAttempts | number | Max polling attempts (default: 10) | No |
| options.timeout | number | Max amount of time to attempt (ms, default: 60000)
Response:
| Field | Type | Description |
|--------|------|-------------|
| success | boolean | Whether the request succeeded |
| status | string | Status (e.g., "SUCCESS", "FAILED") |
| reference | string | Transaction reference |
| third_party_reference | string | Provider reference (e.g., "TJEIA7F83V") |
paymentWalletBalance
Retrieves the balance of a payment wallet.
Parameters:
| Parameter | Type | Description | Required |
|------------|------|-------------|-----------|
| channel_id | number | Wallet channel ID (e.g., 1234) | Yes |
Response:
| Field | Type | Description |
|--------------------|-----------|--------------|
| id | number | Unique ID |
| transaction_type | string | Type of transaction associated with the wallet (Default, CustomerBuyGoodsOnline) |
| channel_type | string | The wallet’s channel type (Default, wallet) |
| account_id | number | ID of the associated PayHero account |
| short_code | string | Short code linked to the payment channel (e.g., 553125) |
| account_number | string | Account number associated with the wallet (e.g., 1234) |
| description | string | Description or label of the wallet (Default, SASAPAY WALLET) |
| is_active | boolean | Indicates if the wallet is active (true or false) |
| balance_plain | object | Nested object containing balance details |
| ├─ last_balance | number | Previous balance before the last update |
| ├─ balance | number | Current wallet balance |
| └─ last_reference| string | Reference of the last transaction affecting the balance |
| created_at | string | Timestamp when the wallet record was created |
| updated_at | string | Timestamp when the wallet record was last updated |
paymentWalletBalance
Parameters:
| Parameter | Type | Description |
|------------|------|-------------|
| wallet_type | string | Value: service_wallet |
Service Wallet Balance Response
| Field | Type | Description |
|---------------------|-----------|--------------|
| id | number | Unique identifier (e.g., 1234) |
| account_id | number | ID of the PayHero account that owns the wallet (e.g., 1234) |
| wallet_type | string | Type of wallet (Default, service_wallet) |
| currency | string | Currency used in the wallet (e.g., KES) |
| available_balance | number | Current available balance in the wallet |
| account_number | string or null | Account number linked to the wallet, if applicable |
| beneficiary | string or null | Beneficiary name or reference |
| wallet_status | string | Current status of the wallet (e.g., PENDING) |
| wallet_id | string or null | Unique wallet identifier from the provider |
| created_at | string | Timestamp when the wallet was created |
| updated_at | string | Timestamp when the wallet was last updated |
License
This project is licensed under the MIT License.
Contribution
Contributions are welcome! Submit issues or pull requests to the GitHub repository. Please follow the code style.
