1. Go to this page and download the library: Download kemboielvis/mpesa-sdk-php 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/ */
kemboielvis / mpesa-sdk-php example snippets
Kemboielvis\MpesaSdkPhp\Mpesa;
// Option A: via constructor
$mpesa = new Mpesa('YOUR_CONSUMER_KEY', 'YOUR_CONSUMER_SECRET', 'sandbox'); // or 'live'
// Option B: via setCredentials (also allows specifying a custom token store file)
$mpesa = (new Mpesa())
->setCredentials('YOUR_CONSUMER_KEY', 'YOUR_CONSUMER_SECRET', 'sandbox', /* optional */ 'mpesa_api_cache.json');
// Optional: choose where to store the token cache file
// If only a filename is provided, it's stored under the system temp directory.
$mpesa->setStoreFile('mpesa_api_cache.json');
// Optional: enable debug logging (prints to PHP error_log)
$mpesa->setDebug(true);
// Example: STK Push
$response = $mpesa->setBusinessCode('YOUR_TILL_OR_SHORTCODE')
->setPassKey('YOUR_LNM_PASSKEY')
->stk()
->setTransactionType('CustomerPayBillOnline') // or 'CustomerBuyGoodsOnline'
->setAmount(100)
->setPhoneNumber('254712345678')
->setCallbackUrl('https://yourdomain.com/callback')
->setAccountReference('INV-12345')
->setTransactionDesc('Payment for invoice INV-12345')
->push()
->getResponse();
print_r($response);
$mpesa->setStoreFile('/var/run/mpesa/token.json');
$path = $mpesa->getResolvedStoreFilePath(); // inspect where it ends up
$mpesa->setDebug(true); // lock events, cache hits/misses, and token response metadata go to error_log
// $config is internal; shown for completeness in test setups only
// $config->setBaseUrl('http://127.0.0.1:8091');
bash
composer
bash
php src/Tests/token_cache_smoke.php
bash
# Start fake token server in a background shell
php -S 127.0.0.1:8091 src/Tests/fake_mpesa_server.php
# In another shell
php src/Tests/concurrency_test.php
bash
# Start fake token server on a different port
php -S 127.0.0.1:8092 src/Tests/fake_mpesa_server.php
# In another shell
php src/Tests/tamper_concurrency_test.php
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.