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-app

v1.0.1

Published

Robost M-Pesa API SDK with retries, callbacks and Typescript support

Readme

mpesa-app

A robust, developer-first M-Pesa SDK for Node.js with built-in retries, token automation, and clean callback handling.


🚀 Why mpesa-app?

M-Pesa integrations are usually painful:

  • Manual token handling
  • Messy callbacks
  • No retry logic
  • Poor developer experience

mpesa-app fixes that.

✔ Automatic access token management
✔ Built-in retry system (network-safe)
✔ Clean STK Push API
✔ Simple callback parser
✔ TypeScript-first


📦 Installation

npm install mpesa-app

⚡ Quick Start

import { Mpesa } from "mpesa-app";

const mpesa = new Mpesa({
  consumerKey: process.env.MPESA_KEY!,
  consumerSecret: process.env.MPESA_SECRET!,
  shortCode: "174379",
  passkey: process.env.MPESA_PASSKEY!,
  environment: "sandbox",
});

await mpesa.stkPush({
  phone: "2547XXXXXXXX",
  amount: 100,
  accountReference: "Test",
  transactionDesc: "Payment",
  callbackUrl: "https://yourdomain.com/callback",
});

💰 STK Push

Trigger a payment request to a user's phone.

await mpesa.stkPush({
  phone: "2547XXXXXXXX",
  amount: 100,
  accountReference: "Order123",
  transactionDesc: "Payment for order",
  callbackUrl: "https://yourdomain.com/callback",
});

📡 Handling Callbacks

M-Pesa responses are complex. This SDK simplifies them.

Example (Express)

import express from "express";
import { Mpesa } from "mpesa-app";

const app = express();
app.use(express.json());

const mpesa = new Mpesa({ ...config });

app.post("/callback", (req, res) => {
  try {
    const data = mpesa.parseCallback(req.body);

    console.log("M-Pesa Result:", data);

    if (data.resultCode === 0) {
      // Payment successful
    } else {
      // Payment failed
    }

    res.sendStatus(200);
  } catch (error) {
    console.error(error);
    res.sendStatus(400);
  }
});

🧪 Full Working Example (Express Server)

import express from "express";
import dotenv from "dotenv";
import { Mpesa } from "mpesa-app";

dotenv.config();

const app = express();
app.use(express.json());

const mpesa = new Mpesa({
  consumerKey: process.env.MPESA_KEY!,
  consumerSecret: process.env.MPESA_SECRET!,
  shortCode: process.env.MPESA_SHORTCODE!,
  passkey: process.env.MPESA_PASSKEY!,
  environment: "sandbox",
});

// STK Push endpoint
app.post("/pay", async (req, res) => {
  try {
    const { phone, amount } = req.body;

    const response = await mpesa.stkPush({
      phone,
      amount,
      accountReference: "DemoApp",
      transactionDesc: "Test Payment",
      callbackUrl: process.env.CALLBACK_URL!,
    });

    res.json({
      success: true,
      message: "STK Push sent",
      data: response,
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      error: error.message,
    });
  }
});

// Callback endpoint
app.post("/callback", (req, res) => {
  try {
    const data = mpesa.parseCallback(req.body);

    console.log("📩 Callback:", data);

    if (data.resultCode === 0) {
      console.log("✅ Payment successful");
      // Save to DB here
    } else {
      console.log("❌ Payment failed");
    }

    res.sendStatus(200);
  } catch (error) {
    res.sendStatus(400);
  }
});

app.listen(5000, () => {
  console.log("🚀 Server running on port 5000");
});

🌐 Testing Locally

Use ngrok to expose your callback URL:

npx ngrok http 5000

Update your callback URL:

https://your-ngrok-url.ngrok.io/callback

🔐 Configuration

type MpesaConfig = {
  consumerKey: string;
  consumerSecret: string;
  shortCode: string;
  passkey: string;
  environment?: "sandbox" | "production";
};

🔁 Built-in Retry System

All requests automatically retry on:

  • Network failures
  • Temporary API issues

No extra setup required.


🧠 How It Works

  • Handles OAuth token generation + caching
  • Automatically attaches Bearer tokens
  • Retries failed requests with backoff
  • Normalizes M-Pesa callback responses

🌍 Environments

environment: "sandbox"; // default
environment: "production";

⚠️ Important Notes

  • Always use HTTPS for callbacks
  • Callback endpoint must be publicly accessible
  • Test in sandbox before going live

🛠 Roadmap

  • [ ] B2C (Business to Customer)
  • [ ] C2B (Customer to Business)
  • [ ] Transaction status API
  • [ ] CLI tools (npx mpesa-app test)
  • [ ] Debug mode & logging
  • [ ] Webhook retry system
  • [ ] SaaS dashboard

💰 SaaS Vision (mpesa-app Platform)

This SDK is the foundation for a larger platform:

  • Hosted webhook handling
  • Transaction storage & analytics
  • Automatic retries & reconciliation
  • Developer dashboard
  • API key management

Goal: 👉 Become the Stripe for M-Pesa integrations


🤝 Contributing

Pull requests are welcome. For major changes, open an issue first.


📄 License

MIT


👤 Author

Built by Mbalanya