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

@tashie/mpesa-sdk

v3.0.2

Published

Mpesa sdk based on daraja 3.0 for the nodejs lovers

Downloads

232

Readme

@tashie/mpesa-sdk

Safaricom MPesa

TypeScript SDK for Safaricom's MPesa Daraja API v3.0

npm version License: ISC


About This SDK

This is a community-maintained, open-source TypeScript SDK for Safaricom's MPesa Daraja API v3.0. It's production-ready, actively maintained, and provides a clean interface for integrating MPesa payments into your Node.js applications.

For official Safaricom documentation and API reference, visit the Safaricom Developer Portal.


About

This SDK provides a clean, type-safe interface to interact with Safaricom's MPesa Daraja API v3.0. It's designed for Node.js applications and supports all major MPesa operations including STK Push, B2C/B2B transfers, account balance queries, QR code generation, tax remittance, standing orders, and more.

✅ Daraja 3.0 Compatible - Built for and tested with the latest Daraja API v3.0.

Installation

npm install @tashie/mpesa-sdk

Quick Start

import { Mpesa, Environment } from "@tashie/mpesa-sdk";

// Initialize
const mpesa = new Mpesa({
  consumerKey: "your_consumer_key",
  consumerSecret: "your_consumer_secret",
  shortCode: "your_shortcode",
  passKey: "your_passkey",
  environment: Environment.SANDBOX,
});

// Authenticate
await mpesa.getAccessToken();

// Send payment request
const result = await mpesa.sendSTKPush({
  amount: 100,
  sender: "254712345678",
  reference: "ORDER-12345",
  callbackUrl: "https://your-domain.com/callback",
  description: "Payment for order #12345",
});

What You Can Do

1. Request Payments (STK Push)

Send payment requests to customers' phones. They receive an MPesa prompt to complete the payment.

const result = await mpesa.sendSTKPush({
  amount: 100,
  sender: "254712345678",
  reference: "ORDER-12345",
  callbackUrl: "https://your-domain.com/callback",
  description: "Payment for order #12345",
});

Response:

{
  "MerchantRequestID": "...",
  "CheckoutRequestID": "...",
  "ResponseCode": "0",
  "ResponseDescription": "Success. Request accepted for processing"
}

2. Send Money to Customers (B2C)

Transfer money from your business account to a customer's phone number.

const result = await mpesa.B2C({
  InitiatorName: "testapi",
  SecurityCredential: "your_encrypted_credential",
  CommandID: "SalaryPayment",
  Amount: "100",
  PartyA: "600782",
  PartyB: "254712345678",
  Remarks: "Salary payment",
  QueueTimeOutURL: "https://your-domain.com/b2c-timeout",
  ResultURL: "https://your-domain.com/b2c-result",
  Occassion: "January Salary",
});

3. Check Account Balance

Query your MPesa business account balance.

const result = await mpesa.getAccountBalance({
  PartyA: 600782,
  Remarks: "Balance check",
  Initiator: "testapi",
  SecurityCredential: "your_encrypted_credential",
  QueueTimeOutURL: "https://your-domain.com/balance-timeout",
  ResultURL: "https://your-domain.com/balance-result",
});

4. Generate QR Codes

Create dynamic QR codes that customers can scan to make payments.

const result = await mpesa.generateDynamicQRCode({
  MerchantName: "Your Business Name",
  RefNo: "ORDER-12345",
  Amount: 100,
  TrxCode: "PB",
  CPI: "your_shortcode",
  Size: "300",
});

// Returns base64 encoded QR code image
// Use result.QRCode to display the QR code

5. Check Transaction Status

Query the status of any transaction.

const result = await mpesa.getTransactionStatus({
  Initiator: "testapi",
  SecurityCredential: "your_encrypted_credential",
  TransactionID: "NEF61H8J60",
  OriginalConversationID: "7071-4170-a0e5-8345632bad442144258",
  PartyA: "600782",
  IdentifierType: "4",
  ResultURL: "https://your-domain.com/transaction-status/result",
  QueueTimeOutURL: "https://your-domain.com/transaction-status/timeout",
  Remarks: "OK",
  Occasion: "OK",
});

6. Reverse Transactions

Reverse a completed transaction.

const result = await mpesa.initiateReversal({
  Initiator: "testapi",
  SecurityCredential: "your_encrypted_credential",
  CommandID: "TransactionReversal",
  TransactionID: "PDU91HIVIT",
  Amount: "200",
  ReceiverParty: "603021",
  RecieverIdentifierType: "11",
  ResultURL: "https://your-domain.com/reversal/result",
  QueueTimeOutURL: "https://your-domain.com/reversal/queue",
  Remarks: "Payment reversal",
});

7. Register C2B URLs

Register URLs to receive customer-to-business payment notifications.

const result = await mpesa.registerUrls({
  ShortCode: "600782",
  ResponseType: "Completed",
  ConfirmationURL: "https://your-domain.com/c2b/confirmation",
  ValidationURL: "https://your-domain.com/c2b/validation",
});

8. Business to Business Payments (B2B)

Initiate payments from one business to another business account.

const result = await mpesa.initiateB2BPayment({
  Initiator: "testapi",
  SecurityCredential: "your_encrypted_credential",
  CommandID: "BusinessPayBill", // or "BusinessBuyGoods", "BusinessPayToPochi", "BusinessPayToBulk"
  SenderIdentifierType: "4",
  RecieverIdentifierType: "4",
  Amount: "100",
  PartyA: "600782",
  PartyB: "600000",
  AccountReference: "INV-12345",
  Requester: "254712345678",
  Remarks: "Payment for invoice",
  QueueTimeOutURL: "https://your-domain.com/b2b-timeout",
  ResultURL: "https://your-domain.com/b2b-result",
});

9. Remit Tax

Remit tax payments to KRA (Kenya Revenue Authority) or other tax authorities.

const result = await mpesa.remittTax({
  Initiator: "testapi",
  SecurityCredential: "your_encrypted_credential",
  CommandID: "PayTaxToKRA",
  SenderIdentifierType: "4",
  RecieverIdentifierType: "4",
  Amount: "100",
  PartyA: "600782",
  PartyB: "572572",
  AccountReference: "TAX-12345",
  Remarks: "Tax payment",
  QueueTimeOutURL: "https://your-domain.com/tax-timeout",
  ResultURL: "https://your-domain.com/tax-result",
});

10. Create Standing Orders

Create standing orders for automated recurring revenue collection. Note: This is a commercial API and requires communication with Safaricom to enable the M-Pesa Ratiba product.

const result = await mpesa.createStandingOrder({
  StandingOrderName: "Monthly Subscription",
  StartDate: "20240101",
  EndDate: "20241231",
  BusinessShortCode: "600782",
  TransactionType: "CustomerPayBillOnline",
  ReceiverPartyIdentifierType: "4",
  Amount: "100",
  PartyA: "254712345678",
  CallBackURL: "https://your-domain.com/standing-order/callback",
  AccountReference: "SUB-12345",
  TransactionDesc: "Monthly subscription payment",
  Frequency: "Monthly", // or "Weekly", "Daily", etc.
});

Configuration

const mpesa = new Mpesa({
  consumerKey: "your_consumer_key", // From Safaricom Developer Portal
  consumerSecret: "your_consumer_secret", // From Safaricom Developer Portal
  shortCode: "your_shortcode", // Your MPesa business shortcode
  passKey: "your_passkey", // From Safaricom Developer Portal
  environment: Environment.SANDBOX, // or Environment.PRODUCTION
});

Authentication

Before making any API calls, authenticate:

await mpesa.getAccessToken();

The token is cached internally. You only need to call this once, or refresh it if you get authentication errors.

Type Safety

All types are exported for use in your application:

import {
  Mpesa,
  Environment,
  ClientConfig,
  STKQuery,
  B2CTransactionConfig,
  B2BPaymentQuery,
  RemittTaxQuery,
  StandingOrderCreationQuery,
  // ... and more
} from "@tashie/mpesa-sdk";

Error Handling

try {
  const result = await mpesa.sendSTKPush({...});
  console.log("Success:", result);
} catch (error) {
  console.error("Error:", error.message);
  // Handle error appropriately
}

Important Notes

Phone Number Format

Always use international format without the leading +:

// ✅ Correct
sender: "254712345678";

// ❌ Wrong
sender: "+254712345678";
sender: "0712345678";

Callback URLs

  • Must be publicly accessible
  • Use HTTPS in production
  • Handle both success and failure cases
  • Implement idempotency to handle duplicate callbacks

Environment Variables

Never hardcode credentials:

const mpesa = new Mpesa({
  consumerKey: process.env.MPESA_CONSUMER_KEY!,
  consumerSecret: process.env.MPESA_CONSUMER_SECRET!,
  shortCode: process.env.MPESA_SHORTCODE!,
  passKey: process.env.MPESA_PASSKEY!,
  environment:
    process.env.NODE_ENV === "production"
      ? Environment.PRODUCTION
      : Environment.SANDBOX,
});

Requirements

Examples

See the examples directory for complete working examples.

Support & Resources

Community & Support

This SDK is maintained by the community and is not officially affiliated with Safaricom PLC. For official Safaricom support, please contact them through their Developer Portal.

If you encounter issues with this SDK, please open an issue on GitHub.

License

ISC


Built with ❤️ by sean for the Node.js community

Safaricom MPesa

MPesa and Safaricom are trademarks of Safaricom PLC