
How to Integrate M-Pesa into a Python Application
M-Pesa is the leading mobile money solution in Kenya, Tanzania, Ghana, South Africa, and other African countries. If you're developing an application that requires mobile money payments, you need to integrate M-Pesa into your system.
This guide explains how to integrate M-Pesa Daraja API with Python in simple, easy-to-understand steps.
What You Will Learn in This Guide
By the end of this guide, you will be able to:
✅ Generate an M-Pesa API Access Token for authentication
✅ Implement STK Push (Lipa na M-Pesa Online Payment)
✅ Handle C2B (Customer to Business Payments)
✅ Process B2C (Business to Customer Payments)
✅ Check Transaction Status
✅ Retrieve Account Balance
Let’s Get Started! 🚀
1. Understanding M-Pesa Daraja API
The M-Pesa Daraja API is a set of RESTful APIs provided by Safaricom that allow developers to integrate M-Pesa transactions into their applications.
Key M-Pesa API Features
Feature | Purpose |
---|---|
STK Push (Lipa na M-Pesa Online Payment) | Allows customers to pay via M-Pesa by receiving a prompt on their phone. |
C2B (Customer to Business Payments) | Enables customers to send money to a business Paybill or Till number. |
B2C (Business to Customer Payments) | Allows a business to send money to a customer’s M-Pesa account. |
Transaction Status Query | Checks if a transaction was successful or failed. |
Account Balance Inquiry | Retrieves the balance of a Paybill or Till number. |
2. Prerequisites: What You Need
Before integrating M-Pesa API into Python, ensure you have the following:
Required Accounts and Tools
✅ M-Pesa Developer Account → Register here
✅ Business Shortcode (Paybill or Till Number) → Provided by Safaricom
✅ M-Pesa API Credentials (Consumer Key & Secret) → Generated from the M-Pesa Developer Portal
✅ Python Installed (Python 3.x recommended)
✅ Flask (or Django) to handle API responses
Install Required Python Libraries
Before proceeding, install the necessary libraries by running:
pip install requests flask python-dotenv
3. Getting Your M-Pesa API Credentials
To access the M-Pesa API, you need:
✅ Consumer Key
✅ Consumer Secret
These can be obtained from the Safaricom Developer Portal.
How to Get API Credentials
- Go to Safaricom Developer Portal
- Log in or create an account
- Create a new App → Select M-Pesa API
- Copy your Consumer Key and Secret
4. Generating M-Pesa API Access Token
Before making any API calls, you must first authenticate using an Access Token.
Step 1: Generate Access Token
import requests
from requests.auth import HTTPBasicAuth
# API Credentials
consumer_key = "YOUR_CONSUMER_KEY"
consumer_secret = "YOUR_CONSUMER_SECRET"
# Access Token URL
auth_url = "https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials"
# Request Access Token
response = requests.get(auth_url, auth=HTTPBasicAuth(consumer_key, consumer_secret))
access_token = response.json().get("access_token")
print("Access Token:", access_token)
✅ The access token expires in 60 minutes
✅ Use this token in the Authorization Header for all API calls
5. Implementing STK Push (Lipa na M-Pesa Online Payment)
What is STK Push?
STK Push allows customers to pay businesses using M-Pesa without manually entering details. The customer receives a payment request on their phone and enters their M-Pesa PIN to complete the transaction.
Step 1: Sending STK Push Request
import requests
import datetime
import base64
# Your Credentials
business_shortcode = "174379" # Test Paybill Number
passkey = "YOUR_MPESA_PASSKEY"
phone_number = "2547XXXXXXXX"
amount = 100
callback_url = "https://yourdomain.com/callback"
# Generate Timestamp
timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
# Encode Password
password = base64.b64encode((business_shortcode + passkey + timestamp).encode()).decode()
# STK Push URL
stk_push_url = "https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest"
headers = {
"Authorization": f"Bearer {access_token}",
"Content-Type": "application/json"
}
payload = {
"BusinessShortCode": business_shortcode,
"Password": password,
"Timestamp": timestamp,
"TransactionType": "CustomerPayBillOnline",
"Amount": amount,
"PartyA": phone_number,
"PartyB": business_shortcode,
"PhoneNumber": phone_number,
"CallBackURL": callback_url,
"AccountReference": "TestPayment",
"TransactionDesc": "Payment for goods"
}
response = requests.post(stk_push_url, json=payload, headers=headers)
print(response.json())
✅ ResponseCode "0" means request sent successfully.
✅ The customer receives an M-Pesa prompt to enter their PIN.
6. Handling STK Push Callback Responses
After the payment, M-Pesa sends a callback response to the CallBackURL
.
Setting Up a Flask Server to Handle Callback Responses
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route("/callback", methods=["POST"])
def mpesa_callback():
data = request.get_json()
print("Callback Response:", data)
return jsonify({"message": "Callback received"}), 200
if __name__ == "__main__":
app.run(port=5000, debug=True)
✅ M-Pesa sends a JSON response with payment status.
✅ Store successful transactions in your database.
7. Implementing C2B (Customer to Business Payments)
C2B allows customers to send money to your Paybill or Till Number.
Register C2B URLs
c2b_register_url = "https://sandbox.safaricom.co.ke/mpesa/c2b/v1/registerurl"
payload = {
"ShortCode": business_shortcode,
"ResponseType": "Completed",
"ConfirmationURL": "https://yourdomain.com/confirmation",
"ValidationURL": "https://yourdomain.com/validation"
}
response = requests.post(c2b_register_url, json=payload, headers=headers)
print(response.json())
✅ Customers can now send money to your Paybill/Till Number.
✅ You’ll receive real-time notifications.
8. Implementing B2C (Business to Customer Payments)
B2C is used to send money to customers (e.g., withdrawals, refunds).
b2c_url = "https://sandbox.safaricom.co.ke/mpesa/b2c/v1/paymentrequest"
payload = {
"InitiatorName": "YOUR_INITIATOR",
"SecurityCredential": "ENCRYPTED_PASSWORD",
"CommandID": "BusinessPayment",
"Amount": 500,
"PartyA": business_shortcode,
"PartyB": phone_number,
"Remarks": "Payment",
"QueueTimeOutURL": "https://yourdomain.com/timeout",
"ResultURL": "https://yourdomain.com/result",
"Occasion": "Test"
}
response = requests.post(b2c_url, json=payload, headers=headers)
print(response.json())
✅ Used for payouts (withdrawals, refunds, salaries).
🎉 Congratulations! You’ve successfully integrated M-Pesa API into Python.
💬 Questions? Comment Below! 🚀
Josphat Okutu
Leave a comment
Your email address will not be published. Required fields are marked *