PHP code example of wasksofts-technology / omnipay-mpesa

1. Go to this page and download the library: Download wasksofts-technology/omnipay-mpesa 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/ */

    

wasksofts-technology / omnipay-mpesa example snippets


use Omnipay\Omnipay;

$gateway = Omnipay::create('Mpesa');
$gateway->setStoreNumber('174379');
$gateway->setPTNumber('174379'); //paybill number or TILL number
$gateway->setConsumerKey('');
$gateway->setConsumerSecret('');
$gateway->setPassKey('');
$gateway->setTestMode(false); 

$response = $gateway->payment([
  'amount' => '100',
  'phone_number' => '254708374149',
  'account' => 'apitest',
  'description' => 'This is a purchase',
  'callbackUrl' => 'https://example.com/callback_url.php',
])->send();
           
           
if ($response->isSuccessful()) {
    echo "Check phone and Input your pin to purchase!";
}else{
   // Payment failed
    echo $response->getMessage();
} 

$data = $response->getData();
echo '<pre>';print_r($data);echo '</pre>';

$callbackJSONData=file_get_contents('php://input');
$callbackData=json_decode($callbackJSONData);

$result=[
"resultDesc"=>$callbackData->Body->stkCallback->ResultDesc,
"resultCode"=>$callbackData->Body->stkCallback->ResultCode,
"merchantRequestID"=>$callbackData->Body->stkCallback->MerchantRequestID,
"checkoutRequestID"=>$callbackData->Body->stkCallback->CheckoutRequestID,
"amount"=>$callbackData->Body->stkCallback->CallbackMetadata->Item[0]->Value,
"mpesaReceiptNumber"=>$callbackData->Body->stkCallback->CallbackMetadata->Item[1]->Value,
"transactionDate"=>$callbackData->Body->stkCallback->CallbackMetadata->Item[3]->Value,
"phoneNumber"=>$callbackData->Body->stkCallback->CallbackMetadata->Item[4]->Value
];

return json_encode($result);
//you can save json_data on database

 $response = $gateway->confirmPayment([
 'checkout_request_id' => 'ws_CO_12072024131357408712244372'
 ])->send();
 

 $response = $gateway->registerUrl()->send();
 

 $callbackJSONData=file_get_contents('php://input');
 $callbackData=json_decode($callbackJSONData);

 $amount = $callbackData->TransAmount;
 $trx_id = $callbackData->TransID;
 $phone_number = $callbackData->MSISDN;
 $BillRefNumber = $callbackData->BillRefNumber;
 
 //you can save json_data on database