Getting Started with M-Pesa Daraja API: A Beginner’s Guide


Introduction: A Quick Story
Imagine you’re running a small neighborhood chama (savings group). Every week, members contribute money, but the process feels chaotic—people send money late, some forget to confirm, and the treasurer spends hours reconciling M-Pesa messages.
Now, picture a system where members simply enter the amount on your app, get an instant prompt on their phones to confirm payment, and you see the transaction reflected automatically on your dashboard. No more cross-checking SMS messages. That’s exactly what the M-Pesa Daraja API makes possible.
In this article, we’ll break down what Daraja is, why it matters, and how you can integrate it into your own projects—like I did with Tujenge, a chama management app.
What is the M-Pesa Daraja API?
Daraja is Safaricom’s official API platform that allows developers to integrate M-Pesa services directly into apps, websites, or backend systems.
With it, you can:
- Accept payments from customers seamlessly.
- Automate processes like contribution tracking.
- Get real-time notifications of every transaction.
Core Concepts
Before diving into code, here are some terms you’ll meet often:
- Consumer Key & Consumer → Credentials for authenticating your app.
- Shortcode → Your business number (Paybill or Till).
- Passkey → Special string used for Lipa na M-Pesa (STK Push).
- Callback URL → Your server endpoint where Safaricom sends the final transaction status.
Think of these as the "keys and addresses" that connect your app to M-Pesa.
Getting Started: The Prerequisites
1. Safaricom Developer Portal
Head over to the Safaricom Daraja portal.
- Create an account.
- Register a new app to get your Consumer Key and Consumer Secret.
2. Sandbox Environment
Safaricom provides a sandbox—a test environment with fake money. This lets you try things out safely before going live.
3. Tools You’ll Need
- Code editor (VS Code recommended)
- Backend server (Node.js, Python/Django, PHP—your choice)
- API testing tools like Postman or Insomnia
Key API Endpoints & Workflows
1. Authentication: Getting an Access Token
Every request to Daraja needs an access token. Here’s an example in Django:
import base64
import requests
from django.conf import settings
def get_access_token():
consumer_key = settings.MPESA_CONSUMER_KEY
consumer_secret = settings.MPESA_CONSUMER_SECRET
# Encode in Base64
data_to_encode = f"{consumer_key}:{consumer_secret}"
encoded = base64.b64encode(data_to_encode.encode('utf-8')).decode('utf-8')
headers = {
"Authorization": f"Basic {encoded}"
}
url = "https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials"
response = requests.get(url, headers=headers)
if response.status_code == 200:
access_token = response.json()['access_token']
return access_token
else:
raise Exception("Failed to fetch access token")
This token is valid for 1 hour and must be included in your API calls.
2. Lipa na M-Pesa Online (STK Push)
This is the most popular workflow—your app triggers a payment prompt on the customer’s phone.
import requests
import datetime
import base64
from django.conf import settings
def lipa_na_mpesa(phone_number, amount):
access_token = get_access_token()
shortcode = settings.MPESA_SHORTCODE
passkey = settings.MPESA_PASSKEY
timestamp = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
# Generate password
data_to_encode = shortcode + passkey + timestamp
password = base64.b64encode(data_to_encode.encode('utf-8')).decode('utf-8')
url = "https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest"
headers = { "Authorization": f"Bearer {access_token}" }
payload = {
"BusinessShortCode": shortcode,
"Password": password,
"Timestamp": timestamp,
"TransactionType": "CustomerPayBillOnline",
"Amount": amount,
"PartyA": phone_number, # Customer's number
"PartyB": shortcode,
"PhoneNumber": phone_number,
"CallBackURL": "https://yourdomain.com/api/mpesa/callback/",
"AccountReference": "Tujenge Contribution",
"TransactionDesc": "Weekly chama payment"
}
response = requests.post(url, json=payload, headers=headers)
return response.json()
When I tested this with Tujenge, members received the familiar “Enter your M-Pesa PIN” prompt on their phones, and once confirmed, Safaricom sent the status to my backend.
3. Handling Transaction Responses
- Immediate response: Daraja returns a JSON with basic info (like ResponseCode).
- Callback URL: This is where Safaricom sends the final result (success/failure). Your backend must be able to receive and save it.
Example of a callback response:
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
import json
@csrf_exempt
def mpesa_callback(request):
if request.method == "POST":
data = json.loads(request.body)
# Extract details
result_code = data["Body"]["stkCallback"]["ResultCode"]
result_desc = data["Body"]["stkCallback"]["ResultDesc"]
# Save to DB (example)
# Transaction.objects.create(...)
return JsonResponse({"ResultCode": 0, "ResultDesc": "Accepted"})
4. Other Useful APIs
- C2B Register URL → To handle payments via Paybill/Till directly.
- Transaction Status Query → Check a transaction’s state.
- Account Balance API → Retrieve your Paybill/Till balance.
Security and Best Practices
- Don’t hardcode credentials: Use environment variables (.env).
- Always use HTTPS: Your callback must have SSL in production.
- Log everything: Keep track of requests/responses for troubleshooting.
Conclusion
Summary
- Daraja lets you integrate M-Pesa payments directly into your apps.
- You’ll need to register on the developer portal, test in the sandbox, and understand workflows like STK Push.
- Secure your credentials, handle callbacks properly, and log your transactions.
Going Live
Once you’re confident with sandbox testing:
- Apply for production access on the portal.
- Update your credentials (production keys, shortcode, passkey).
- Switch your endpoints from sandbox.safaricom.co.ke to api.safaricom.co.ke.
And just like that, your chama members—or any customers—can pay you directly from their phones while your system records everything automatically.
Subscribe to my newsletter
Read articles from Michelle Wangari directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
