1. Go to this page and download the library: Download ongudidan/mpesa-sdk library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
ongudidan / mpesa-sdk example snippets
$mpesa = new \Mpesa\Mpesa();
$data = [
'Initiator' => 'API user created on Safaricom Business dashboard',
'initiatorPassword' => 'Password of the API user',
'CommandID' => 'BusinessPayment', // or SalaryPayment, PromotionPayment
'Amount' => '100', // Amount to send
'PartyA' => '600XXX', // Your shortcode
'PartyB' => '2547XXXXXXXX', // Customer phone number
'Remarks' => 'Salary payment',
'QueueTimeOutURL' => 'https://yourdomain.com/timeout',
'ResultURL' => 'https://yourdomain.com/result',
'Occasion' => 'JunePayroll',
'environment' => 'sandbox or live',
'consumer_key' => 'your_consumer_key',
'consumer_secret' => 'your_consumer_secret',
];
$response = $mpesa->b2c($data);
$mpesa = new \Mpesa\Mpesa();
$data = [
'IdentifierType' => '4', // 1: Shortcode, 2: Till, 4: Org
'PartyA' => '600XXX', // Your shortcode or organization ID
'Initiator' => 'API user created on dashboard',
'initiatorPassword' => 'Password of the API user',
'QueueTimeOutURL' => 'https://yourdomain.com/timeout',
'ResultURL' => 'https://yourdomain.com/result',
'environment' => 'sandbox or live',
'consumer_key' => 'your_consumer_key',
'consumer_secret' => 'your_consumer_secret',
];
$response = $mpesa->accountBalance($data);
$mpesa = new \Mpesa\Mpesa();
$data = [
'TransactionID' => 'OEI2AK4Q16', // M-Pesa transaction ID
'PartyA' => '600XXX', // Your shortcode
'IdentifierType' => '4', // 1: MSISDN (Phone number), 2: Till 4: Paybill, etc.
'Initiator' => 'API user',
'initiatorPassword' => 'Password of the API user',
'ResultURL' => 'https://yourdomain.com/result',
'QueueTimeOutURL' => 'https://yourdomain.com/timeout',
'environment' => 'sandbox or live',
'consumer_key' => 'your_consumer_key',
'consumer_secret' => 'your_consumer_secret',
];
$response = $mpesa->transactionStatus($data);
$mpesa = new \Mpesa\Mpesa();
$data = $mpesa->getDataFromCallback();
$mpesa = new \Mpesa\Mpesa();
$mpesa->finishTransaction(); // success
$mpesa->finishTransaction(false); // failure
// callback.php
// Capture raw POST data from Daraja
$callbackData = file_get_contents('php://input');
// Optional: Decode JSON for easier inspection
// $decoded = json_decode($callbackData, true);
// Define log file location (you can customize path)
$logFile = __DIR__ . '/M_PESAConfirmationResponse.json';
// Append the raw callback data with a newline for separation
file_put_contents($logFile, $callbackData . PHP_EOL, FILE_APPEND);
// You can add any additional logic to handle the data here
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.