Last Updated on June 26, 2025 by Burst Digital

In Part 1 of our series, we covered the essential steps of setting up your business on the M-Pesa G2 Portal, acquiring your API credentials, and understanding how mobile payments via Paybill or BuyGoods accounts work. In this follow-up, we’ll walk you through how to integrate M-Pesa into your PHP-powered website or app using the Safaricom Daraja API.

This article is tailored for developers and business owners who want a reliable and secure way to accept payments online in Kenya via M-Pesa.

Prerequisites

Before proceeding with this PHP integration, ensure you:

  • Have a Paybill or BuyGoods number
  • Have obtained M-Pesa API credentials from Safaricom (Consumer Key, Secret, Shortcode, and Passkey)
  • Have a server running PHP 7.0+ (most shared hosting is fine)
  • Optionally, have SSL enabled (for live environments)

If you’re not at this stage yet, we recommend starting with Part 1 of this series.

Step 1: Download Our PHP M-Pesa Integration Kit

To simplify the process, we’ve built a lightweight PHP library that helps you get started quickly with the Daraja API.

Download it here on GitHub

This zip includes:

  • config.php (where you enter your credentials)
  • daraja.php (the reusable library)
  • index.php (a sample form + payment trigger)
  • mpesa_callback.php (handles the callback from Safaricom)

Step 2: Configure Your API Credentials

Edit config.php and replace the placeholders with your actual values. Here’s a safe structure:

<?php
// M-Pesa API credentials
define('CONSUMER_KEY', 'your-consumer-key');
define('CONSUMER_SECRET', 'your-consumer-secret');
define('BUSINESS_SHORT_CODE', 'your-paybill-or-buygoods');
define('PASSKEY', 'your-daraja-passkey');
define('CALLBACK_URL', 'https://yourdomain.com/mpesa/mpesa_callback.php');
define('ACCOUNT_REFERENCE', 'YourBusinessName');
define('TRANSACTION_DESC', 'Payment for Order');
define('TRANSACTION_TYPE', 'CustomerPayBillOnline');

Step 3: Initiate Payment (STK Push)

In index.php, we capture user input and send it to Safaricom’s STK Push API:

require_once('config.php');
require_once('daraja.php');

$daraja = new Daraja();

$phone = $_POST['phone'];
$amount = $_POST['amount'];

$paymentRequest = $daraja->lipaNaMpesaOnline([
  'Amount' => $amount,
  'PhoneNumber' => $phone,
  'PartyA' => $phone,
  'CallBackURL' => CALLBACK_URL,
  'AccountReference' => ACCOUNT_REFERENCE,
  'TransactionDesc' => TRANSACTION_DESC,
  'TransactionType' => TRANSACTION_TYPE
]);

$response = $daraja->execute($paymentRequest);

If the STK Push succeeds, your customer will get a prompt on their phone to enter their M-Pesa PIN.

Step 4: Handle Callback from Safaricom

When a transaction is completed, Safaricom sends a POST request to your mpesa_callback.php. Here’s a simplified version:

$data = file_get_contents('php://input');
file_put_contents('logs.txt', $data, FILE_APPEND); // optional log

// You can decode and save to DB
$response = json_decode($data);
$amount = $response->Body->stkCallback->CallbackMetadata->Item[0]->Value;
$phone  = $response->Body->stkCallback->CallbackMetadata->Item[4]->Value;

// Update order status, mark as paid etc.

tep 5: Test Using Safaricom Sandbox

Before going live:

  • Replace the live URL https://api.safaricom.co.ke/ with https://sandbox.safaricom.co.ke/
  • Use sandbox credentials from Safaricom developer portal
  • Simulate transactions from the Daraja test page

Step 6: Go Live

When ready:

  • Update your config.php with live credentials
  • Ensure you’re using HTTPS and valid domain callback URL
  • Monitor your transactions and implement error handling logs

Common Errors and Troubleshooting

ErrorCauseFix
Invalid CredentialsWrong key/secret or shortcodeDouble-check credentials
500 ErrorCode failure or missing fileCheck error_log file
Callback Not FiringInvalid or unreachable URLTest with curl or Postman

Example Use Cases

  • Collect payments on a WordPress site
  • Accept donations via mobile
  • Add “Pay with M-Pesa” button on checkout pages
  • Automate invoice payments in PHP apps

Final Thoughts

You’ve just seen how simple it can be to integrate M-Pesa into your PHP application with the Daraja API and our lightweight library. Whether you’re running an e-commerce site or a custom-built app, this guide gives you everything you need to get started.

At Burst Digital, we help businesses of all sizes accept M-Pesa payments. If you need help setting up or customizing your solution, contact us at hello@burstdigital.co.ke or call 0768871177.

💡 Need help? We offer one-time integration from Kshs 5,000 or complete e-commerce setup packages.


Download the Code

Grab the full source code on our GitHub: 👉 https://github.com/Burst-Digital-Kenya/mpesa-integration-php

Next Up: M-Pesa integration using Python and Node.js — stay tuned!

Using WordPress? Why Use Our M-Pesa Payment Plugin Instead of Free Ones?

The free M-Pesa Payment plugin on WP Repo doesn’t process callbacks. Ours:

  • Handles callbacks: update order status automatically
  • Real-time customer feedback
  • Works with Till/Paybill
  • Allows payment to Till/Paybill directly
  • Set default order status after successful payment
  • One domain license

Pricing: Ksh 8,000 one-time (including plugin $25 + setup). Get it here > https://burstdigital.co.ke/product/woocommerce-m-pesa-payment-plugin-pro-with-stk-push/

Test it here> https://burstdigital.co.ke/mpesa/?amount=10.00&product=M-Pesa+Integration+Test&time=2025-06-22T15%3A56%3A23.209Z

FAQs

What if I have a Till number only?

You need to write a letter to Safaricom requesting to change your settlement method from phone to bank. Attach:

  • The letter (on business letterhead)
  • KYC documents
  • Cancelled cheque / bank letter
  • Business Administrator Form

Once approved, they’ll give you a Store Number and portal login.

What if I have a Paybill?

You already have a store number, so just email Safaricom with your KYC documents and Business Admin Form to get portal logins.

How do I do live tests?

Use your live credentials on Daraja with sandbox/test URLs. The money is refunded to your M-Pesa line.

What if I don’t have a Till or Paybill?

Refer to our guide here: How to Get a Till or Paybill

What if I find the whole process hard?

Let us help! Burst Digital can:

  • Help you apply
  • Do the integration end-to-end

Charges:

  • WordPress: KES 5,000
  • PHP/Laravel: KES 15,000
  • React/Node/Odoo/POS/Apps: KES 30,000

What if I want other M-Pesa APIs like C2B or B2C?

We also offer:

  • C2B integration (customer pays, you receive)
  • B2C (send to customer)
  • B2B (send to other businesses)
  • Reversal APIs
  • Transaction status, balance checks

Each additional API: KES 10,000 (Excludes Safaricom’s own API usage fees)

Tags :
M-Pesa integration,Mobile payment solutions,PHP payment integration,Safaricom Daraja API
Share This :

What Our Clients Say...

5.0
Based on 35 Reviews
google
Software Xperts
5.0
May 20, 2023

Together, we unleashed the power of technology and delivered exceptional outcomes for our clients. Thanks Burst Digital!

google
Faith Naim
5.0
February 15, 2022

Effective SEO solutions and targeted online advertising. Good job!

google
kay meds
5.0
February 15, 2022

Their digital work is World Class! I would highly recommend them.

google
Kelvin Babu
5.0
February 2, 2022

They are the best. An incredibly efficient and professional team with deep understanding of business needs & digital media. Highly recommended especially for complex digital media needs.

Request Callback

Interested in digital marketing? Request a call.

Questions?

We’re available on phone and email to answer your questions.

Recommended Posts