PHP code example of tumainimosha / laravel-mpesa-push

1. Go to this page and download the library: Download tumainimosha/laravel-mpesa-push 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/ */

    

tumainimosha / laravel-mpesa-push example snippets



use Tumainimosha\MpesaPush\MpesaPush;

...

public function testPush() {

    // Resolve service object
    $push = MpesaPush::instance();
    
    $customerMsisdn = '<substitute valid mpesa-tz number>';
    $amount = 250;
    $txnId = str_random('20');
    
    $responseCode = $push->postRequest($customerMsisdn, $amount, $txnId);
    
    // Check for response code
    // Valid response codes
    //  '0' - Success (note: response code is string '0' not numeric 0)
    //  'Duplicate' - Duplicate transaction ID
    //   Others - fail
    
}
    

// EventServiceProvider.php

protected $listen = [
    ...
    \Tumainimosha\MpesaPush\Events\MpesaCallbackReceived::class => [
        \App\Listeners\MpesaCallbackReceivedHandler::class,
    ],
];

// MpesaCallbackReceivedHandler.php

public function handle(MpesaCallbackReceived $event)
{
    $transaction = $event->transaction;
    
    // do your custom logic here
}


// $account here could be a Model fetched from db with account attributes
$pushService = MpesaPush::instance();

$pushService->setUsername($account->username)
    ->setPassword($account->password)
    ->setBusinessName($account->business_name)
    ->setBusinessNumber($account->business_number)
    ->setCommand($account->command);
    
$pushService->postRequest($customerMsisdn, $amount, $txnId);
bash
php artisan vendor:publish --provider="Tumainimosha\MpesaPush\MpesaPushServiceProvider" --tag="config"
bash
php artisan vendor:publish --provider="Tumainimosha\MpesaPush\MpesaPushServiceProvider" --tag="migrations"
php artisan migrate