Introduction
A modern, developer-friendly M-Pesa SDK that makes mobile payments integration effortless.
Singularity Payments
Singularity Payments is a modern TypeScript Software Development Kit built on top of Safaricom's Daraja API that simplifies M-Pesa integration for developers. Whether you're building an e-commerce platform, a SaaS application, or any service that requires mobile payments, this SDK provides everything you need.
Features?
While the Daraja API is powerful, integrating it directly comes with several challenges that we aim to solve.
Type Safety First
Built with TypeScript, you will get full IntelliSense support and catch errors before they reach production. No more guessing API parameters or dealing with cryptic runtime errors.
const { data, error } = await mpesaClient.stkPush({
amount: 1,
phoneNumber: phone,
accountReference: "Singularity",
transactionDesc: "Sponsorship",
});
const { data, error } = await mpesaClient.stkPush({
amount: "1",
phone: "254712345678",
});Simplified Authentication
No need to manually handle OAuth tokens, token refresh, or authentication flows. The SDK manages all of this automatically.
const mpesaClient = new MpesaClient({
consumerKey: process.env.MPESA_KEY,
consumerSecret: process.env.MPESA_SECRET,
});
await mpesaClient.stkPush({});Built-in Rate Limiting for Distributed Systems
Protect your M-Pesa integration from API rate limits with built-in rate limiting that works seamlessly across multiple servers and serverless functions using Redis. Perfect for production applications running on platforms like Vercel, AWS Lambda, or Kubernetes clusters.
import { createClient } from "redis";
import { createMpesa } from "@singularity-payments/nextjs";
const redisClient = createClient({
url: process.env.REDIS_URL,
});
await redisClient.connect();
export const mpesa = createMpesa(
{
consumerKey: process.env.MPESA_CONSUMER_KEY,
consumerSecret: process.env.MPESA_CONSUMER_SECRET,
passkey: process.env.MPESA_PASSKEY,
shortcode: process.env.MPESA_SHORTCODE,
environment: "sandbox",
},
{
rateLimitOptions: {
enabled: true,
maxRequests: 100,
windowMs: 60000,
redis: redisClient,
},
},
);Why Redis Rate Limiting Matters
Without Redis (In-Memory Only)
- Rate limits reset when your server restarts
- Each server instance has separate limits
- Serverless functions can't share rate limit state
- Risk of exceeding M-Pesa API limits in distributed deployments
With Redis Rate Limiting
- Shared rate limit state across all servers
- Survives server restarts and redeployments
- Works perfectly with serverless architectures
- Automatic synchronization across multiple regions
- Prevents API limit violations in high-traffic scenarios
Distributed System Support
Whether you're running a single server or a globally distributed application, Redis-based rate limiting ensures consistent API usage tracking:
- Serverless Functions: Share rate limits across Lambda, Vercel Edge, or Cloudflare Workers
- Kubernetes Clusters: Coordinate limits across multiple pods and nodes
- Multi-Region Deployments: Synchronize limits globally with Redis replication
- Auto-Scaling: New instances immediately respect existing rate limits
Flexible Configuration
rateLimitOptions: {
enabled: true,
maxRequests: 100,
windowMs: 60000,
redis: redisClient,
}Configure rate limits based on your M-Pesa plan and traffic patterns. The SDK automatically tracks requests per endpoint and enforces limits before making API calls, preventing costly rate limit errors.
Intuitive API Design
Clean, modern API that follows JavaScript/TypeScript conventions. No need to study complex Daraja documentation for hours.
STK Push
Trigger payment prompts on customer phones
STK Query Status
Check transaction status in real-time
Business to Customer(B2C)
Initiate payments to customers
Business to Business(B2B)
Initiate payments between businesses
Account Balance
Check your account balance
Transaction Query Status
Check transaction status in real-time
Reversal
Reverse a transaction
Register Customer to Business URLs
Register callback URLs
Generate Dynamic QR Code
Generate a dynamic QR code for payments
Built-in Error Handling
Comprehensive error handling with descriptive messages. Know exactly what went wrong and how to fix it.
Framework Agnostic
Works seamlessly with any JavaScript framework or library:
- Next.js
- React
- Sveltekit
- Vue.js
- Svelte
- Nuxt.js
- Elysia
- Fastify
- Express.js
- Hono
Industry Standard: Built following best practices from the Daraja API documentation with additional safeguards and optimizations.
Comparison
| Feature | Singularity Payments | Raw Daraja API |
|---|---|---|
| TypeScript Support | ✅ Full type safety | ❌ Manual typing |
| Auto Authentication | ✅ Handled automatically | ❌ Manual token management |
| Distributed Rate Limiting | ✅ Redis-based | ❌ Manual implementation |
| Error Handling | ✅ Descriptive errors | ❌ Raw API errors |
| Documentation | ✅ Comprehensive | ⚠️ Basic |
| Framework Support | ✅ All frameworks | ✅ All frameworks |
| Serverless Compatible | ✅ Full support | ⚠️ Requires custom setup |
What You Can Build
With Singularity Payments, you can implement:
- E-commerce Checkouts - Accept payments for online stores
- SaaS Subscriptions - Process recurring subscription payments
- Ticket Sales - Sell event tickets and generate payment confirmations
- Point of Sale - Build POS systems for retail
- Peer-to-Peer Transfers - Enable money transfers between users
- In-App Purchases - Monetize mobile applications
- Bill Payments - Process utility and service bill payments
- Payroll Systems - Automate salary disbursements
Getting Started
Ready to integrate M-Pesa payments? Get started in just 5 minutes:
Prerequisites
Before you begin, you'll need: - A Safaricom Daraja account - Your Consumer Key and Consumer Secret - A registered M-Pesa shortcode (or use sandbox for testing)
Community & Support
Ready to start? Head over to the Installation Guide to set up Singularity Payments in your project.