I have worked with Daraja API in several projects as a means of integrating M-PESA as payment provider in those projects. When I first started, I struggled to find clear guidance on how to secure the callback route. This topic is rarely covered in most integration tutorials.
Callback webhook URL is the URL that you provide as one of the attributes in the data sent during STK Push prompt request. Safaricom is going to send payment confirmations to your system via that URL.
One of the biggest unanswered questions developers face is:
How do you trust and secure the callback request sent to your server?
Unlike providers such as Stripe or PayPal, Daraja callbacks do not include cryptographic signatures that allow you to verify authenticity. This means developers must implement their own defensive controls to prevent fraud, replay attacks, and fake payment confirmations.
This guide explains a production-grade approach to securing your STK Push callback endpoint using multiple defensive layers.
When you initiate an STK Push, Safaricom sends a POST request to your callback URL with the transaction result.
Example flow:
User → Your App → Daraja API → User Phone
↓ Callback to Your Server
The issue:
Anyone who discovers your callback URL could send a fake request.
Without validation, your system may activate services without payment.
Duplicate callbacks can cause double processing.
Therefore, you must treat callbacks as untrusted input.
Common risks include:
Fake success callbacks
Replay attacks (duplicate submissions)
Brute-force endpoint discovery
Parameter tampering
Race conditions (double processing)
Denial of service
A secure solution must mitigate all of these.
A robust production approach combines multiple layers:
Non-predictable callback URL (obfuscation)
Correlation token (idempotent key)
Database verification
MerchantRequestID + CheckoutRequestID validation
IP whitelisting (optional but useful)
Idempotent processing logic
Transaction locking
Optional server-side confirmation (STK Query API)
Rate limiting
Audit logging
No single layer is sufficient — security comes from combining them.
Let's delve deep into these measures:
This involves deliberately making the callback URL take a weird and confusing format or adding random strings to it, to make it hard to guess or reduce automated discovery.
Example: https://yourdomain.com/payments/m/c/back/p/ or https://yourdomain.com/payments/mpesa/callback/x7f9a2k/
However, obfuscation is not real security — only a friction layer.
Attackers can still discover endpoints through:
Traffic analysis
Logs exposure
Enumeration tools
Use obfuscation only as a minor improvement, never as your primary defense.
You may restrict requests to known Safaricom IP ranges.
Important considerations:
IP ranges may change
If behind a proxy (Nginx, Cloudflare), extract real IP correctly
Never trust X-Forwarded-For unless controlled by your infrastructure
This method requires you frequently ensure that the list is up-to-date with Safaricom IP addresses. Otherwise, you might inadvertently block valid requests. IP filtering should never replace application-level validation.
For high-value payments, you can call the STK Query API after receiving the callback to confirm status directly from Safaricom.
This provides an additional trust layer.
Idempotency prevents duplicate processing of requests and correlation token verifies the authenticity. Idempotency is commonly used in payment systems to avoid unintentionally charging the user multiple times. This is achieved by generating and attaching a unique idempotent key to each transaction.
This token/key servers two purposes:
Correlates the callback with a transaction you created
Prevents unauthorized requests from being accepted
STEP 1: Create Transaction
Your Server
↓ generate idempotent_key
↓ Database ← transaction(PENDING)
STEP 2: Send STK Push
Your Server → Daraja API
CallBackURL = https://yourdomain.com/callback/{idempotent_key}
STEP 3: Receive Callback
Daraja → Your Server
↓ extract key
↓ Database lookup → VALID? → Process ↓ (key doesn't exist) Discard request.
from uuid import uuid4
def initialize_stk_push_prompt(request):
idempotent_key = uuid4().hex
transaction = Transaction.objects.create(
idempotent_key=idempotent_key,
status="PENDING",
amount=amount,
phone_number=phone_number,
)
callback_url = f"https://yourdomain.com/api/mpesa/callback/{idempotent_key}/"
stk_data = {
"BusinessShortCode": shortcode,
"Password": password,
"Timestamp": timestamp,
"TransactionType": "CustomerPayBillOnline",
"Amount": amount,
"PartyA": phone_number,
"PartyB": shortcode,
"PhoneNumber": phone_number,
"CallBackURL": callback_url,
"AccountReference": account_reference,
"TransactionDesc": transaction_desc,
}
# send request to Daraja here
return {"message": "STK Push initialized"}
These are snippets of the callback view using Django Ninja API:
# schemas.py
from typing import Optional, Union
from ninja import Schema
# Schemas for validation
class CallbackItem(Schema):
Name: str
Value: Union[str, int, None] = None
class CallbackMetadataSchema(Schema):
Item: list[CallbackItem]
class StkCallback(Schema):
MerchantRequestID: str
CheckoutRequestID: str
ResultCode: int
ResultDesc: str
CallbackMetadata: Optional[CallbackMetadataSchema] = None
class Body(Schema):
stkCallback: StkCallback
class MpesaCallbackSchema(Schema):
Body: Body
Key protections included:
Database locking
Status verification
Correlation key validation
ID verification
Idempotency
Atomic transaction
# api.py
from django.db import transaction as db_transaction
from django.http import HttpRequest
from ninja import NinjaAPI
from .schemas import MpesaCallbackSchema
from .models import StkTransaction
api = NinjaAPI()
@api.post("/mpesa/callback/{idempotent_key}/")
def mpesa_callback(request: HttpRequest, idempotent_key: str, data: MpesaCallbackSchema):
stk = data.Body.stkCallback
try:
with db_transaction.atomic():
txn = (
StkTransaction.objects
.select_for_update()
.get(
idempotent_key=idempotent_key,
status="PENDING",
merchant_request_id=stk.MerchantRequestID,
checkout_request_id=stk.CheckoutRequestID,
)
)
if stk.ResultCode == 0 and stk.CallbackMetadata:
txn.status = "SUCCESS"
txn.save()
# TODO: activate service / grant access
else:
txn.status = "FAILED"
txn.save()
except StkTransaction.DoesNotExist:
# Invalid or already processed
pass
return {"ResultCode": 0, "ResultDesc": "Accepted"}
Important: Verify Transaction Identifiers Always validate: - MerchantRequestID - CheckoutRequestID
These values are returned during STK initialization and must match the callback. Without this step, attackers could fabricate success responses.
Protect against brute force attacks on callback URLs.
Options:
Nginx limit_req
API gateway throttling
Django middleware rate limiting
Store:
Raw payload
Timestamp
Source IP
Headers
SHA256 hash of body
This helps with:
Fraud investigation
Dispute resolution
Compliance
Example
import hashlib
raw_body = request.body
payload_hash = hashlib.sha256(raw_body).hexdigest()
Below is the checklist that I follow:
[ ] Use unique callback URLs per transaction
[ ] Store transactions before initiating STK
[ ] Validate MerchantRequestID and CheckoutRequestID
[ ] Use database locking (select_for_update)
[ ] Enforce idempotent processing
[ ] Return success response quickly (avoid retries)
[ ] Log everything
[ ] Apply rate limiting
[ ] Consider STK Query confirmation for critical payments
Trusting callback without DB correlation
Activating services before validation
Ignoring duplicate callbacks
Using predictable callback URLs
Not handling concurrency
Skipping error logging
Because Daraja callbacks lack cryptographic verification, securing them requires thoughtful architecture rather than a single trick.
The safest approach combines:
Correlation tokens
Database validation
Idempotent logic
Optional network filtering
When implemented correctly, your payment system becomes resilient against fraud and replay attacks.
If you are building production fintech systems, always design with this mindset that prevents most payment vulnerabilities:
]]>"Any external request can be forged"
JOINS are queries that access multiple tables (or multiple instances of the same table) at one time by combining rows from one table with the rows from a second table with an expression specifying which rows are to be paired (PostgreSQL documentation).
For a better understanding of this concept. Let's have some context by having some tables.
--- create tables
CREATE TABLE users (
id serial PRIMARY KEY,
name varchar(64),
city varchar(20)
);
CREATE TABLE accounts (
id serial PRIMARY KEY,
name varchar(80),
balance int DEFAULT 0,
userId int REFERENCES users(id)
);
CREATE TABLE cities ( name varchar(80), location point );
--- insert data
INSERT INTO users (name, city) VALUES ('ricky'), ('morty'), ('patrick'), ('spongebob');
SELECT * FROM users;
INSERT INTO accounts (name, balance, userId) VALUES ('Bank', 10, 1),('Cash', 100, 1);
INSERT INTO accounts (name, balance, userId) VALUES ('Loop', 30, 2),('Cash', 50, 2);
INSERT INTO accounts (name, balance, userId) VALUES ('MPESA', 45, 4),('Cash', 100, 4);
SELECT * FROM accounts;
INSERT INTO cities VALUES ('San Francisco', '(-194.0, 53.0)') ,('Nairobi', '(0.0, 53.0)'), ('Nakuru', '(0.0, 43.0)');
SELECT * FROM cities;
The following are the most commonly used JOINS:
SELECT * FROM users JOIN accounts ON users.id=accounts.userId;
/* output
id | name | id | name | balance | userid
----+-----------+----+-------+---------+--------
1 | ricky | 1 | Bank | 10 | 1
1 | ricky | 2 | Cash | 100 | 1
2 | morty | 3 | Loop | 30 | 2
2 | morty | 4 | Cash | 50 | 2
4 | spongebob | 5 | MPESA | 45 | 4
4 | spongebob | 6 | Cash | 100 | 4
*/
As you can see patrick is omitted because he doesn't have an account.
SELECT * FROM users LEFT OUTER JOIN accounts ON users.id=accounts.userId;
/*
id | name | id | name | balance | userid
----+-----------+----+-------+---------+--------
1 | ricky | 1 | Bank | 10 | 1
1 | ricky | 2 | Cash | 100 | 1
2 | morty | 3 | Loop | 30 | 2
2 | morty | 4 | Cash | 50 | 2
4 | spongebob | 5 | MPESA | 45 | 4
4 | spongebob | 6 | Cash | 100 | 4
3 | patrick | | | |
(7 rows)
*/
Since not matches were found for patrick on the accounts table, we see we have blanks on that row on accounts table columns.
LEFT OUTER JOIN.SELECT * FROM users RIGHT OUTER JOIN accounts ON users.id=accounts.userId;
/*
id | name | id | name | balance | userid
----+-----------+----+-------+---------+--------
1 | ricky | 1 | Bank | 10 | 1
1 | ricky | 2 | Cash | 100 | 1
2 | morty | 3 | Loop | 30 | 2
2 | morty | 4 | Cash | 50 | 2
4 | spongebob | 5 | MPESA | 45 | 4
4 | spongebob | 6 | Cash | 100 | 4
(6 rows)
*/
SELECT * FROM users FULL JOIN cities ON users.city = cities.name;
/*
id | name | city | name | location
----+-----------+------+---------------+-----------
| | | San Francisco | (-194,53)
| | | Nairobi | (0,53)
| | | Nakuru | (0,43)
4 | spongebob | | |
3 | patrick | | |
2 | morty | | |
1 | ricky | | |
(7 rows)
*/
-- Let's update some of the users to have city attribute
UPDATE users SET city='Nakuru' WHERE users.id=1; -- ricky
UPDATE users SET city='Nairobi' WHERE users.id=3; -- patrick
-- Now for a more demonstrative example of the FULL JOIN
SELECT * FROM users FULL JOIN cities ON users.city = cities.name;
/*
id | name | city | name | location
----+-----------+---------+---------------+-----------
| | | San Francisco | (-194,53)
3 | patrick | Nairobi | Nairobi | (0,53)
1 | ricky | Nakuru | Nakuru | (0,43)
4 | spongebob | | |
2 | morty | | |
(5 rows)
*/
CREATE TABLE weather (
city varchar(80),
temp_lo int, -- low temperature
temp_hi int, -- high temperature
prcp real, -- precipitation
date date
);
INSERT INTO weather VALUES
('San Francisco', 25, 30, 0.25, '2025-11-27'),
('Nakuru', 15, 23, 0.25, '2026-1-17'),
('Nairobi', 13, 25, 0.25, '2026-1-2');
/*
SELF JOIN we want to find all weather records that are in the temperature range of other records. So, we compare the temp_lo and temp_h1 columns of each weather row to the temp_lo and temp_hi columns of all the other weather rows.
*/
SELECT w1.city, w1.temp_lo AS low, w1.temp_hi AS high,
w2.city, w2.temp_lo AS low, w2.temp_hi AS high
FROM weather w1 JOIN weather w2
ON w1.temp_lo < w2.temp_lo AND w1.temp_hi > w2.temp_hi;
/*
city | low | high | city | low | high
---------+-----+------+--------+-----+------
Nairobi | 13 | 25 | Nakuru | 15 | 23
(1 row)
*/
]]>