How to Prevent Duplicate and Fake M-Pesa Payments in Your Finance App
Heading: Why finance apps get "tricked"
If your system handles loans, savings, B2B or B2C transfers through M-Pesa, money moves automatically. Anything that moves money automatically will eventually be tested by people looking for a gap.
In my experience, most so-called "hacks" on payment systems are not clever attacks on M-Pesa itself. They are weaknesses in how the developer's own code reacts to payment messages. The usual problems are:
- The same confirmation being processed twice, so one payment is credited two times
- A system that trusts any request sent to its callback URL, even if it did not come from Safaricom
- A payout that can be triggered twice by a double click, a retry or a slow network
- No record of who approved what, so nobody can trace a mistake afterwards
In this article I will explain how I approach each of these as a developer. The goal is to protect your business and your customers, so everything here is defensive.
Heading: The golden rule: never trust, always verify
Your callback URL is a public web address. Anyone can send data to it. So the first rule is that a message arriving at your server is only a claim, not proof. Your system should only credit money when it can match the message to a payment it expects, and ideally confirm it with Safaricom.
Heading: Step 1: Design your payments table to block duplicates
Protection starts in the database, not in PHP. Create a table like this:
CREATE TABLE payments (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
user_id INT UNSIGNED NOT NULL,
checkout_request_id VARCHAR(100) NOT NULL UNIQUE,
mpesa_receipt VARCHAR(30) NULL UNIQUE,
expected_amount DECIMAL(12,2) NOT NULL,
paid_amount DECIMAL(12,2) NULL,
status ENUM('pending','completed','failed') NOT NULL DEFAULT 'pending',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
completed_at TIMESTAMP NULL
);Two columns do the heavy lifting here:
- checkout_request_id is UNIQUE, so one payment request can only exist once.
- mpesa_receipt is UNIQUE, so the same M-Pesa receipt number can never be recorded twice, even if Safaricom sends the callback twice or someone replays it.
A UNIQUE rule in the database cannot be bypassed by a bug in your PHP code. That makes it your strongest safety net.
Heading: Step 2: Create the payment record before you ask for money
When a customer starts a payment, save a pending record first, with the amount you expect. Only then send the STK Push request. When the response comes back, store its CheckoutRequestID against that record.
This means every legitimate callback has a matching pending row waiting for it. A callback with no matching row is simply ignored and logged.
Heading: Step 3: Process the callback safely
Here is a simplified callback handler. It uses a database transaction and a row lock so that two identical callbacks arriving at the same moment cannot both succeed:
<?php
require 'db.php';
$raw = file_get_contents('php://input');
$data = json_decode($raw, true);
// Log everything for your audit trail
file_put_contents('callback_log.txt', date('c') . ' ' . $raw . PHP_EOL, FILE_APPEND);
$cb = $data['Body']['stkCallback'] ?? null;
if (!$cb) { http_response_code(400); exit; }
$checkoutId = $cb['CheckoutRequestID'] ?? '';
$resultCode = $cb['ResultCode'] ?? -1;
try {
$pdo->beginTransaction();
$stmt = $pdo->prepare('SELECT * FROM payments WHERE checkout_request_id = ? FOR UPDATE');
$stmt->execute([$checkoutId]);
$payment = $stmt->fetch(PDO::FETCH_ASSOC);
// Unknown request, or already processed: do nothing
if (!$payment || $payment['status'] !== 'pending') {
$pdo->rollBack();
echo json_encode(['ResultCode' => 0, 'ResultDesc' => 'Accepted']);
exit;
}
if ($resultCode != 0) {
$pdo->prepare("UPDATE payments SET status = 'failed' WHERE id = ?")->execute([$payment['id']]);
$pdo->commit();
echo json_encode(['ResultCode' => 0, 'ResultDesc' => 'Accepted']);
exit;
}
// Read the metadata items
$amount = null; $receipt = null;
foreach ($cb['CallbackMetadata']['Item'] as $item) {
if ($item['Name'] === 'Amount') $amount = $item['Value'];
if ($item['Name'] === 'MpesaReceiptNumber') $receipt = $item['Value'];
}
// Amount must match what we expected
if ($receipt === null || (float)$amount !== (float)$payment['expected_amount']) {
$pdo->rollBack();
// flag for manual review instead of crediting
exit;
}
$pdo->prepare("UPDATE payments SET status='completed', paid_amount=?, mpesa_receipt=?, completed_at=NOW() WHERE id=?")
->execute([$amount, $receipt, $payment['id']]);
// Credit the customer's account or loan balance here, inside the same transaction
$pdo->commit();
} catch (PDOException $e) {
$pdo->rollBack();
error_log($e->getMessage());
}
echo json_encode(['ResultCode' => 0, 'ResultDesc' => 'Accepted']);Look at what this code does:
- SELECT ... FOR UPDATE locks the row, so a second identical callback has to wait, and then finds the status is no longer pending.
- The status check makes the handler idempotent. Processing the same message ten times has the same result as processing it once.
- The amount is compared with what the system expected, not trusted blindly.
- Crediting the account happens inside the same transaction as marking the payment complete, so you can never have one without the other.
Heading: Step 4: Do not trust the callback URL alone
Because the callback address is public, add extra layers:
- Use HTTPS only. Install a valid SSL certificate on the callback domain.
- Use a hard-to-guess callback path, for example one that includes a long random secret token, and keep it out of public code repositories.
- Restrict access where you can. Safaricom publishes the source IP addresses it uses, so check the current list on the Daraja portal and allow only those at your firewall or in your code.
- For important payments, confirm with Safaricom directly. Before crediting a large amount, call the STK Push Query or Transaction Status API from your server and compare the result with the callback. A forged message cannot fake a response that you fetched yourself.
Heading: Step 5: Protect payouts (B2C and B2B) from double sending
Money going out needs even more care than money coming in. These are the rules I follow:
- One loan, one disbursement. Add a UNIQUE column such as loan_id in your disbursements table, so the database refuses a second payout for the same loan.
- Mark as "processing" before calling the API. Set the status first, then send the request. If the user double clicks or the page refreshes, the second attempt sees the status and stops.
- Disable the button after the first click and handle the request on the server, not only in JavaScript.
- Set limits. Define a maximum amount per transaction, per day and per user, and require extra approval above those limits.
- Use two-person approval. For finance systems, one staff member initiates and another approves. No single account should be able to send large sums alone.
- Keep your API credentials safe. Store Daraja keys outside the public web folder, never in front-end code, and rotate them if you suspect a leak.
- Check your balance and rate limit. Verify the float balance before sending and limit how fast payouts can be triggered.
Heading: Step 6: Keep an audit trail
If something goes wrong, you need to answer the question "what happened?" within minutes. Log every callback received, every payout request, who approved it and the result. Never delete these logs, and never let normal users edit them.
Also run daily reconciliation. Compare the transactions in your database with the M-Pesa statement from your portal. Any mismatch should be flagged for a person to review.
Heading: Common mistakes to avoid
- Crediting a customer straight from the callback without matching a pending payment
- Not using UNIQUE constraints on receipt numbers and request IDs
- Trusting the amount sent in the message without comparing it to the expected amount
- Sending payouts without a status check or a lock
- Letting one admin account approve and send money alone
- Keeping API keys inside public files or front-end JavaScript
- Having no logs, so problems cannot be traced
Heading: Bonus points before you go
- Bonus 1: Ask your developer this question: "What happens if the same M-Pesa callback arrives twice?" If they cannot answer clearly, your system may be crediting twice.
- Bonus 2: Check your database for duplicate receipt numbers. Even one duplicate is a sign your system has a gap.
- Bonus 3: A finance app is only as strong as its weakest approval step. If one person can send money without a second check, that is your biggest risk.
- Bonus 4: Fixing these problems after you lose money costs far more than building them correctly from day one.
Heading: Final thoughts
No system is ever 100 percent unbreakable, but a well-built finance app makes tricking it extremely difficult and makes every attempt visible. Unique database rules, locked transactions, amount checks, server-side verification, approval workflows and good logs together close the gaps that people usually try to use.
If you are planning a loan, savings or payment system, or you want your current one reviewed for these weaknesses, I would be glad to help. Reach me on WhatsApp at 0739334082 or email consult@johnsimiyuweb.site.
Next, read: How to Secure M-Pesa B2C and B2B Payouts in a Loan or Finance System
Heading: About the author
John Simiyu is an experienced full-time full-stack software developer with proven, robust skills in web development using PHP, Bootstrap, JavaScript, HTML, MySQL and CSS, Python for automation, and Kotlin and Java for native Android development. He has over 5 years of experience building websites, business systems and mobile apps for clients.


