M-Pesa STK push in Python (Flask and Django)
JMSURF PAY guide · updated 23 November 2026
This guide shows M-Pesa STK push from Python with the requests library, plus webhook receivers for Flask and Django. Your code sends one HTTPS request; the customer gets the M-Pesa PIN prompt; the money goes straight to your till, paybill or bank; and JMSURF PAY posts the result to your webhook. There is no Daraja token handling, no passkey and no callback URL registration in your code.
Set up
- 1Account and test key. Create a free account at app.jmsurfpay.co.ke, confirm your email and copy the test secret key.
- 2Payment channel. Add the till, paybill or bank account you are paid into under Payment channels and copy its code.
- 3Webhook. Add your HTTPS webhook address under Developers, Webhooks and copy the secret.
Send the prompt and read the status
Python with requests
# pip install requests
import os
import requests
API = "https://jmsurfpay.co.ke/api"
SECRET_KEY = os.environ["JMSURFPAY_SECRET_KEY"] # sk_test_... or sk_...
CHANNEL = os.environ["JMSURFPAY_CHANNEL_CODE"] # tnnt_...
def send_prompt(order_id: str, phone: str, amount: int) -> str:
r = requests.post(
f"{API}/payments/stkpush",
headers={"X-API-Key": SECRET_KEY, "Idempotency-Key": f"order-{order_id}"},
json={
"tenantCode": CHANNEL,
"phoneNumber": phone, # 07..., 2547... or +2547...
"amount": int(amount), # whole shillings, 1 to 250,000
"accountReference": f"ORD{order_id}",
"transactionDesc": f"Order {order_id}",
},
timeout=30,
)
data = r.json()
if r.status_code >= 400:
raise RuntimeError(f"{data.get('error')}: {data.get('message')}")
return data["checkoutRequestId"]
def payment_status(checkout_request_id: str) -> dict:
r = requests.get(f"{API}/payments/status/{checkout_request_id}",
headers={"X-API-Key": SECRET_KEY}, timeout=15)
return r.json() # status: pending | completed | failed | cancelledrequests also builds HTTP Basic for you: requests.post(url, auth=(PUBLIC_KEY, SECRET_KEY), json=payload) is the same as sending X-API-Key.
Response (200)
{
"checkoutRequestId": "ws_CO_...",
"merchantRequestId": "...",
"responseCode": "0",
"responseDescription": "Success. Request accepted for processing",
"customerMessage": "Success. Request accepted for processing",
"transactionId": 42,
"livemode": true
}Webhook receiver in Flask
Flask
# Flask webhook receiver. pip install flask
import hashlib, hmac, os
from flask import Flask, request, abort
app = Flask(__name__)
WEBHOOK_SECRET = os.environ["JMSURFPAY_WEBHOOK_SECRET"].encode()
@app.post("/webhooks/jmsurfpay")
def jmsurfpay_webhook():
raw = request.get_data() # exact bytes, before parsing
expected = "sha256=" + hmac.new(WEBHOOK_SECRET, raw, hashlib.sha256).hexdigest()
if not hmac.compare_digest(expected, request.headers.get("X-Webhook-Signature", "")):
abort(401)
event = request.get_json()
if already_processed(event["id"]): # retries keep the same id
return "", 200
if event["event"] == "payment.completed" and event["livemode"]:
p = event["data"]
mark_paid(p["accountReference"], p["mpesaReceiptNumber"], p["amount"])
remember(event["id"])
return "", 200Webhook receiver in Django
Django
# Django view (add the URL in urls.py). The view must skip CSRF: JMSURF PAY calls it.
import hashlib, hmac, json
from django.conf import settings
from django.http import HttpResponse, HttpResponseForbidden
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
@csrf_exempt
@require_POST
def jmsurfpay_webhook(request):
expected = "sha256=" + hmac.new(settings.JMSURFPAY_WEBHOOK_SECRET.encode(),
request.body, hashlib.sha256).hexdigest()
if not hmac.compare_digest(expected, request.headers.get("X-Webhook-Signature", "")):
return HttpResponseForbidden()
event = json.loads(request.body)
if event["event"] == "payment.completed" and event["livemode"]:
Order.objects.filter(checkout_request_id=event["data"]["checkoutRequestId"]) \
.update(paid=True, receipt=event["data"]["mpesaReceiptNumber"])
return HttpResponse(status=200)- Sign and compare the raw body (
request.get_data()in Flask,request.bodyin Django), never a re-encoded dict. - Answer 2xx within 8 seconds; failed deliveries are retried up to 4 more times over about 2.5 hours.
livemodeisfalsefor test-key payments. Keep the check so a test can never mark a real order paid.
Testing without real money
With the test key, amount 2 fails with a wrong PIN (2001), 3 is cancelled (1032), 4 gets no response (1037), and any other amount is paid with a receipt that starts with TEST. Webhooks fire exactly as in live mode, so you can test your whole flow end to end. Details: test mode.
Errors
| HTTP | error | What to do |
|---|---|---|
| 400 | VALIDATION_ERROR | A field is missing or wrong. phoneNumber, amount, accountReference and transactionDesc are required; the amount is a whole number from 1 to 250,000. |
| 400 | CHANNEL_REQUIRED | You have more than one payment channel. Send tenantCode so the money goes to the right one. |
| 401 | Unauthorized | The secret key is missing or wrong. |
| 402 | PLAN_EXPIRED / FREE_LIMIT_REACHED | The plan has ended or the Free plan's monthly limit is used. The answer carries a renewUrl. |
| 403 | KYC_REQUIRED | A live key was used before the business is verified. Use a test key until then. |
| 429 | PROMPT_LIMIT / PROMPT_PAUSED | Too many prompts to the same number (3 in 2 minutes), or recent prompts to it did not reach the phone. Wait retryAfterSeconds or use another number. |
| 502 | MPESA_ERROR | M-Pesa returned an error. Read the message field. |
Building a platform that serves many businesses? Read M-Pesa API for SaaS platforms.
Start on the Free plan: 1 payment channel, up to KES 50,000 a month, test keys included. Questions? WhatsApp +254 712 504 593.