npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

mpesa-servc

v1.0.0

Published

M-Pesa payment service with comprehensive API integration and certificate-based security

Readme

Secure M-Pesa Service - Updated Implementation

Overview

This is a secure Node.js service for integrating with Safaricom M-Pesa APIs, now fully aligned with official documentation and enhanced with certificate-based security.

New Features Added

1. B2Pochi API Support

  • Complete implementation of B2Pochi API for payments to customer business wallets (Pochi La Biashara)
  • Dedicated controller and service methods
  • Proper validation and error handling

2. Certificate-Based Password Encryption

  • Integration with certificate files from cert folder
  • Automatic password encryption using RSA PKCS1 padding
  • Support for both sandbox and production certificates
  • Certificate validation utilities

3. Enhanced B2B Operations

  • BusinessPayBill endpoint for paying bills from business account
  • BusinessBuyGoods endpoint for paying to till numbers
  • Proper command ID validation
  • Enhanced error handling

4. Improved B2C Operations

  • Dedicated endpoints for different payment types:
    • SalaryPayment - Employee salary disbursements
    • BusinessPayment - Standard business to customer payments
    • PromotionPayment - Promotional payments with congratulatory messages

5. Enhanced C2B API (v2)

  • Updated to use official v2 endpoints
  • Proper simulation for both buy goods and pay bill
  • Enhanced validation with correct command IDs
  • Improved callback handling

6. Advanced Transaction Operations

  • Query transactions by receipt number
  • Query by originator conversation ID
  • Enhanced status checking with proper parameters
  • Improved reversal functionality

API Endpoints

Payment Methods

# Phone Payment
POST /api/mpesa/payments/phone

# Pochi Payment
POST /api/mpesa/payments/pochi

# Till Payment
POST /api/mpesa/payments/till

# Paybill Payment
POST /api/mpesa/payments/paybill

# Customer Buy Goods Online
POST /api/mpesa/payments/buy-goods-online

# Customer Pay Bill Online
POST /api/mpesa/payments/pay-bill-online

STK Push

# Initiate STK Push
POST /api/mpesa/stkpush/initiate

# Query STK Push Status
GET /api/mpesa/stkpush/query/:checkoutRequestID

B2B Operations

# Generic B2B Transfer
POST /api/mpesa/b2b/transfer

# Business Pay Bill
POST /api/mpesa/b2b/business-pay-bill

# Business Buy Goods
POST /api/mpesa/b2b/business-buy-goods

B2Pochi Operations (NEW)

# B2Pochi Payment
POST /api/mpesa/b2pochi/payment

B2C Operations

# Generic B2C Payment
POST /api/mpesa/b2c/payment

# Salary Payment
POST /api/mpesa/b2c/salary

# Business Payment
POST /api/mpesa/b2c/business

# Promotion Payment
POST /api/mpesa/b2c/promotion

C2B Operations

# Register C2B URLs
POST /api/mpesa/c2b/register

# Simulate C2B Payment
POST /api/mpesa/c2b/simulate

# Customer Buy Goods Simulation
POST /api/mpesa/c2b/buy-goods

# Customer Pay Bill Simulation
POST /api/mpesa/c2b/pay-bill

Transaction Operations

# Check Transaction Status
POST /api/mpesa/transactions/status

# Check Account Balance
POST /api/mpesa/transactions/balance

# Reverse Transaction
POST /api/mpesa/transactions/reversal

# Query by Receipt
POST /api/mpesa/transactions/query-by-receipt

# Query by Originator ID
POST /api/mpesa/transactions/query-by-originator-id

Certificate Setup

Certificate File Location

Place your M-Pesa certificate file in the cert folder:

  • cert/ProductionCertificate.cer - For production environment
  • cert/SandboxCertificate.cer - For sandbox environment (optional)

Password Encryption

The service now automatically encrypts initiator passwords using the certificate. You can also manually encrypt passwords:

const EncryptionUtils = require('./utils/encryptionUtils');

// Encrypt password for current environment
const encryptedPassword = EncryptionUtils.encryptPassword('your_password');

// Encrypt password for specific environment
const encryptedPassword = EncryptionUtils.encryptPasswordForEnvironment('your_password', 'production');

// Validate certificate
const certValidation = EncryptionUtils.validateCertificate();
console.log(certValidation);

Configuration Updates

Environment Variables

Update your .env file with the new variables:

# Existing variables remain the same
MPESA_CONSUMER_KEY=your_consumer_key_here
MPESA_CONSUMER_SECRET=your_consumer_secret_here
MPESA_PASSKEY=your_passkey_here
MPESA_SHORTCODE=174379
MPESA_HEAD_OFFICE=174379
MPESA_INITIATOR_NAME=testapi
MPESA_INITIATOR_PASSWORD=your_initiator_password_here
MPESA_SECURITY_CREDENTIAL=your_encrypted_security_credential_here
MPESA_CALLBACK_URL=https://your-domain.com/api/mpesa/callback
MPESA_TIMEOUT_URL=https://your-domain.com/api/mpesa/timeout
MPESA_RESULT_URL=https://your-domain.com/api/mpesa/result
MPESA_QUEUE_TIMEOUT_URL=https://your-domain.com/api/mpesa/queue-timeout
MPESA_ENVIRONMENT=sandbox
PORT=3000
API_KEY=your_api_key_here

Security Credential

You need to encrypt your initiator password using the certificate before adding it to the .env file:

  1. Use the encryption utility:
const EncryptionUtils = require('./utils/encryptionUtils');
const encrypted = EncryptionUtils.encryptPassword('your_initiator_password');
console.log(encrypted);
  1. Add the encrypted value to your .env file:
MPESA_SECURITY_CREDENTIAL=your_encrypted_password_here

Usage Examples

B2Pochi Payment

curl -X POST http://localhost:3000/api/mpesa/b2pochi/payment \
  -H "Content-Type: application/json" \
  -H "x-api-key: your_api_key" \
  -d '{
    "amount": 100,
    "partyB": "254700000000",
    "remarks": "Pochi payment",
    "occasion": "Business payment"
  }'

Business Buy Goods Payment

curl -X POST http://localhost:3000/api/mpesa/b2b/business-buy-goods \
  -H "Content-Type: application/json" \
  -H "x-api-key: your_api_key" \
  -d '{
    "amount": 500,
    "partyA": "174379",
    "partyB": "174380",
    "accountReference": "Goods Purchase",
    "remarks": "Business payment to till",
    "requester": "254700000000"
  }'

Business Pay Bill Payment

curl -X POST http://localhost:3000/api/mpesa/b2b/business-pay-bill \
  -H "Content-Type: application/json" \
  -H "x-api-key: your_api_key" \
  -d '{
    "amount": 1000,
    "partyA": "174379",
    "partyB": "174381",
    "accountReference": "ACC123456",
    "remarks": "Bill payment",
    "requester": "254700000000"
  }'

Salary Payment (B2C)

curl -X POST http://localhost:3000/api/mpesa/b2c/salary \
  -H "Content-Type: application/json" \
  -H "x-api-key: your_api_key" \
  -d '{
    "amount": 50000,
    "partyB": "254700000000",
    "remarks": "January Salary",
    "occasion": "Monthly Salary"
  }'

Customer Buy Goods Simulation (C2B)

curl -X POST http://localhost:3000/api/mpesa/c2b/buy-goods \
  -H "Content-Type: application/json" \
  -H "x-api-key: your_api_key" \
  -d '{
    "shortCode": "174379",
    "amount": 100,
    "msisdn": "254700000000"
  }'

Transaction Query by Receipt

curl -X POST http://localhost:3000/api/mpesa/transactions/query-by-receipt \
  -H "Content-Type: application/json" \
  -H "x-api-key: your_api_key" \
  -d '{
    "transactionID": "LHG31AA5TX",
    "remarks": "Query transaction"
  }'

Security Enhancements

Certificate-Based Encryption

  • Automatic password encryption using M-Pesa certificates
  • Certificate validation before encryption
  • Support for multiple certificates (sandbox/production)

Enhanced Validation

  • Phone number format validation (254XXXXXXXXX)
  • Command ID validation for all operations
  • Amount validation (positive numbers)
  • Required field checking

Improved Error Handling

  • Specific error codes from official M-Pesa documentation
  • Descriptive error messages
  • Proper logging of all operations

Callback Handling

All callbacks now handle the official M-Pesa response formats:

  • STK Push callbacks with proper result parsing
  • C2B v2 validation and confirmation callbacks
  • B2C, B2B, and B2Pochi result callbacks
  • Transaction status and reversal callbacks

Testing

The service includes comprehensive testing capabilities:

  • All endpoints properly validated
  • Error handling for all scenarios
  • Certificate validation utilities
  • Phone number formatting utilities

Production Deployment

Checklist

  1. ✅ Obtain production certificate from M-Pesa
  2. ✅ Encrypt initiator password using certificate
  3. ✅ Configure production environment variables
  4. ✅ Set up production callback URLs (HTTPS required)
  5. ✅ Configure proper firewall and security
  6. ✅ Set up monitoring and logging
  7. ✅ Test all endpoints in production environment

Security Recommendations

  • Use HTTPS for all production endpoints
  • Implement additional API key management
  • Set up proper rate limiting per user
  • Monitor logs for suspicious activities
  • Regular security audits
  • Implement database for transaction persistence

Support and Documentation

All implementation is based on official M-Pesa documentation:

  • C2B API v2 documentation
  • B2C API v3 documentation
  • B2B API documentation
  • B2Pochi API documentation
  • Transaction Status API documentation

For issues and questions, please refer to the official M-Pesa API documentation at https://developer.safaricom.co.ke