PHP code example of kemboielvis / mpesa-sdk-php

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);

$resp = $mpesa->stk()
    ->setTransactionType('CustomerPayBillOnline')
    ->setAmount(100)
    ->setPhoneNumber('254712345678')
    ->setCallbackUrl('https://yourdomain.com/callback')
    ->setAccountReference('INV-12345')
    ->setTransactionDesc('Payment for invoice')
    ->push()
    ->getResponse();

$status = $mpesa->stk()
    ->query('CHECKOUT_REQUEST_ID')
    ->getResponse();

$resp = $mpesa->customerToBusiness()
    ->setResponseType('Completed')
    ->setConfirmationUrl('https://yourdomain.com/confirmation')
    ->setValidationUrl('https://yourdomain.com/validation')
    ->registerUrl()
    ->getResponse();

$resp = $mpesa->customerToBusiness()
    ->setCommandId('CustomerPayBillOnline')
    ->setAmount(100)
    ->setPhoneNumber('254712345678')
    ->setBillRefNumber('INV-123') // for PayBill only
    ->simulate()
    ->getResponse();

$resp = $mpesa->businessToCustomer()
    ->setInitiatorName('YOUR_INITIATOR_NAME')
    ->setCommandId('SalaryPayment') // or BusinessPayment, PromotionPayment
    ->setAmount(1000)
    ->setPhoneNumber('254712345678')
    ->setRemarks('Salary payment')
    ->setOccasion('May 2023 salary')
    ->paymentRequest(
        'YOUR_INITIATOR_NAME',
        'YOUR_INITIATOR_PASSWORD',
        'SalaryPayment',
        1000,
        'YOUR_SHORTCODE',
        '254712345678',
        'Salary payment',
        'https://yourdomain.com/timeout',
        'https://yourdomain.com/result',
        'May 2023 salary'
    );

$resp = $mpesa->reversal()
    ->setInitiator('YOUR_INITIATOR_NAME')
    ->setTransactionId('YOUR_TRANSACTION_ID')
    ->setReceiverIdentifierType('11') // 1=MSISDN, 2=Till, 4=Shortcode
    ->setRemarks('Refund')
    ->setOccasion('Customer refund')
    ->reverse(
        'YOUR_INITIATOR_NAME',
        'YOUR_INITIATOR_PASSWORD',
        'Refund',
        'YOUR_SHORTCODE',
        'YOUR_TRANSACTION_ID',
        '11',
        'https://yourdomain.com/timeout',
        'https://yourdomain.com/result',
        'Customer refund'
    );

try {
    $resp = $mpesa->stk()->push()->getResponse();
} catch (\Throwable $e) {
    error_log('M-Pesa error: ' . $e->getMessage());
}

$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