<![CDATA[Borore DevTech Blog]]><![CDATA[I share what I have learnt and what am currently learning.]]>https://bororedevtech.hashnode.devRSS for NodeWed, 25 Nov 2026 04:39:38 GMT<![CDATA[en]]>60<![CDATA[How to Secure Your M-Pesa Daraja STK Push Callback Webhook]]><![CDATA[Learn how to secure M-Pesa Daraja STK Push callbacks using idempotency, validation, and best practices to prevent fraud and fake requests.]]>https://bororedevtech.hashnode.dev/how-to-secure-stk-push-callbackhttps://bororedevtech.hashnode.dev/how-to-secure-stk-push-callback<![CDATA[MPesa]]><![CDATA[Mpesa integration Nodejs]]><![CDATA[daraja-api]]><![CDATA[Django M-Pesa Integration]]><![CDATA[M-Pesa Callback security]]><![CDATA[Safaricom Daraja Best practices]]><![CDATA[STK Push callback validation]]><![CDATA[Borore]]>Sun, 22 Feb 2026 18:16:27 GMT<![CDATA[

Introduction

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.


The Security Problem

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.


Threat Model

Common risks include:

  1. Fake success callbacks

  2. Replay attacks (duplicate submissions)

  3. Brute-force endpoint discovery

  4. Parameter tampering

  5. Race conditions (double processing)

  6. Denial of service

A secure solution must mitigate all of these.


Defense-in-Depth Strategy

A robust production approach combines multiple layers:

  1. Non-predictable callback URL (obfuscation)

  2. Correlation token (idempotent key)

  3. Database verification

  4. MerchantRequestID + CheckoutRequestID validation

  5. IP whitelisting (optional but useful)

  6. Idempotent processing logic

  7. Transaction locking

  8. Optional server-side confirmation (STK Query API)

  9. Rate limiting

  10. Audit logging

No single layer is sufficient — security comes from combining them.


Let's delve deep into these measures:

Callback URL Obfuscation

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.


IP Whitelisting

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.


Server-Side Confirmation (Optional but stronger)

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.


Using an Idempotent Correlation Key (Core Protection)

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:

  1. Correlates the callback with a transaction you created

  2. Prevents unauthorized requests from being accepted

Architecture Diagram Flow

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.


Initializing STK Push (Django Example)

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:

Callback Schema Validation (Django Ninja)

# 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

Secure Callback Processing

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.


Rate Limiting Protection

Protect against brute force attacks on callback URLs.

Options:

  • Nginx limit_req

  • API gateway throttling

  • Django middleware rate limiting


Audit Logging

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:

Best Practices Checklist

  • [ ] 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

Common Mistakes to Avoid

  • Trusting callback without DB correlation

  • Activating services before validation

  • Ignoring duplicate callbacks

  • Using predictable callback URLs

  • Not handling concurrency

  • Skipping error logging


Conclusion

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"

]]><![CDATA[Database JOINS in PostgreSQL]]><![CDATA[Learn what are database joins, types and how to use them in PostgreSQL.]]>https://bororedevtech.hashnode.dev/database-joins-in-postgresqlhttps://bororedevtech.hashnode.dev/database-joins-in-postgresql<![CDATA[Borore]]>Sat, 17 Jan 2026 13:08:45 GMT<![CDATA[

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;

Types of JOIN

The following are the most commonly used JOINS:

  1. INNER JOIN

  • get all the records from left and right tables that match with the joining condition
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.

  1. LEFT OUTER JOIN

  • each rows in the left table is outputted at lease once, whereas the right will only have rows that match some of the rows in the left table. When outputting left-table rows which there is no right-table match, empty (null) values are substituted for the right-table columns.
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.

  1. RIGHT OUTER JOIN

  • each rows in the right table is outputted at lease once, whereas the left will only have rows that match some of the rows in the right table. When outputting right-table rows which there is no left-table match, empty (null) values are substituted for the left-table columns. This is the vice versa of 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)
*/
  1. FULL OUTER JOIN

  • Get all records from the T1 (users) table and the right T2 (cities) that do not match the ON clause condition (joining condition) and those that do. For each row in the T1 that don't satisfy the join condition with any row in T2, a joined row is added with null values in the columns of T2. Also, for each row in the T2 that don't satisfy the join condition with any row in T1, a joined row is added with null values in the columns of T1.
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)
*/

SELF JOIN

  • joining a table against itself.
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)
*/
]]>