mpesa-app
v1.0.1
Published
Robost M-Pesa API SDK with retries, callbacks and Typescript support
Maintainers
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 5000Update 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
