This guide will help you get started with the Adams MPesa SDK in just a few minutes.
- Node.js 16 or higher
- NPM or Yarn
- Safaricom Developer Account (Sign up here)
- Go to Safaricom Developer Portal
- Create a new app or use an existing one
- Note down your:
- Consumer Key
- Consumer Secret
- Shortcode (Business Number)
- Passkey (for STK Push)
npm install adams-mpesa-sdkCreate a .env file in your project root:
MPESA_CONSUMER_KEY=your_consumer_key_here
MPESA_CONSUMER_SECRET=your_consumer_secret_here
MPESA_SHORTCODE=174379
MPESA_PASSKEY=your_passkey_here
MPESA_ENVIRONMENT=sandboxCreate a file mpesa-test.js:
const { Mpesa } = require('adams-mpesa-sdk');
require('dotenv').config();
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.MPESA_ENVIRONMENT,
});
async function testPayment() {
try {
const response = await mpesa.stkPush({
amount: 1,
phone: '254712345678', // Replace with your phone number
accountReference: 'Test Payment',
transactionDesc: 'Testing MPesa SDK',
callbackUrl: 'https://yourdomain.com/callback', // Optional
});
console.log('Success! Check your phone for the payment prompt.');
console.log('Response:', response);
} catch (error) {
console.error('Error:', error.message);
}
}
testPayment();Run it:
node mpesa-test.jsIf you're building a web application, create an endpoint to receive payment confirmations:
const express = require('express');
const app = express();
app.use(express.json());
app.post('/api/mpesa/callback', (req, res) => {
const { Body } = req.body;
if (Body.stkCallback) {
const { ResultCode, CheckoutRequestID, ResultDesc } = Body.stkCallback;
if (ResultCode === 0) {
console.log('✅ Payment successful!', CheckoutRequestID);
// Update your database, send confirmation email, etc.
} else {
console.log('❌ Payment failed:', ResultDesc);
}
}
res.status(200).json({ ResultCode: 0, ResultDesc: 'Accepted' });
});
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});For TypeScript projects:
import { Mpesa, StkPushRequest, StkPushResponse } from 'adams-mpesa-sdk';
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: 'sandbox',
});
async function initiatePayment(): Promise<StkPushResponse> {
const request: StkPushRequest = {
amount: 100,
phone: '254712345678',
accountReference: 'Invoice #123',
};
return await mpesa.stkPush(request);
}For sandbox testing:
- Use the Safaricom sandbox credentials
- Use the test phone numbers provided by Safaricom
- Test paybill:
174379 - You can simulate payments without real money
Solution: Check your consumer key and secret are correct.
Solution: Ensure your shortcode is registered for STK Push on the developer portal.
Solution: Use format 254712345678 (254 + 9 digits without leading zero).
Solution: For local development, use ngrok or similar to expose your localhost:
npx ngrok http 3000
# Use the HTTPS URL as your callback URL- Read the full README.md for all features
- Check out examples.ts for more use cases
- Learn about error handling
- Explore B2C payments
- Set up C2B
Happy coding! 🚀