PHP code example of levizwannah / mpesa-sdk-php

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

    

levizwannah / mpesa-sdk-php example snippets




use LeviZwannah\MpesaSdk\Mpesa;

$config = [
  "key" => "consumer-key", // consumer key
  "secret" => "consumer-secret", // consumer secret
  "code" => "12345", // business short code
  
  "till" => "67891", // optional till number
  "passkey" => "xxxx", // optional passkey
  "initiator" => "levizwannah", // optional initiator name
  "credential" => "levi-cred++=="  // optional security credential
]

$mpesa = Mpesa::new()->configure($config);

 

use LeviZwannah\MpesaSdk\Mpesa;

$mpesa = Mpesa::new();

$mpesa->key("consumer-key")
      ->secret("consumer-secret")
      ->code(12345)
      ->till(67891) // optional
      ->passkey('stk-passkey') // optional
      ->initiator("levizwannah") // optional
      ->credential("levi-cred++=="); // optional

//...other code
use LeviZwannah\MpesaSdk\Helpers\Constant;

$mpesa->configure([
    'env' => Constant::SANDBOX, 
    // or
    'env' => Constant::LIVE, // default value
]);

// or
$mpesa->env(Constant::SANDBOX);
$mpesa->env(Constant::LIVE); // default value

//... request made

if($client->accepted()) {
    // ... mpesa accepted the request for processing
    // This means the ResponseCode == 0
    $response = $client->response();
}
else {
    // The response code is not == 0 or there is an error.
    $error = $client->error(); // get an error object
    echo "error: $error->code, $error->message";
}

// you can always get the latest response using
$response = $client->response(); // returns an object

$conversationId = $response->ConversationID;
$responseCode = $response->ResponseCode;
// ...




use LeviZwannah\MpesaSdk\Mpesa;

$isFromMpesa = Mpesa::verifyOrigin();
$result = Mpesa::data();

//...

//..setup...

$stk = $mpesa->stk();

// for till numbers
// ensure that the till number is set during setup
// or set it up using $stk->till(123455)

$stk->phone('0724786543')
    ->amount(1)
    ->buygoods() // for till numbers
    ->paybill() // for paybill numbers
    ->callback('https://my-domain.com/path/to/callback')
    ->description('optional description') // optional
    ->push();

// check if the request was accepted by mpesa.
if(!$stk->accepted()) {
    $error = $stk->error();
    echo "error: $error->code, $error->message";
    // exit...
}

// accepted for processing
$response = $stk->response(); // returns an object

$merchantRequestId = $response->MerchantRequestID;
$checkoutRequestId = $response->checkoutRequestID;

//...

//...setup...

$query = $mpesa->stk()->query();

$query->checkoutId('checkout-request-id')
      ->paybill() // for paybill number
      ->buygoods() // for till numbers
      ->make();

// check if it's not accepted
if(!$query->accepted()){
  $error = $query->error();
  echo "$error->code $error->message";
  // exit;
}

$response = $query->response();
$resultCode = $response->ResultCode;
$merchantId = $response->MerchantRequestID;
// ...

// ...setup...
// c2b url registration
$urls = $mpesa->urls();

$urls->confirmation('https://my.url/path/to/confirmation')
     ->validation('https://my.url/path/to/validation') // optional
     ->register();

if(!$urls->accepted()) {
  $error = $urls->error();
  echo "Error: $error->code - $error->message";
  // exit;
}




use LeviZwannah\MpesaSdk\Mpesa;

# confirmation.url

// your code ...
Mpesa::confirm(); // echos the formatted response
// your code...
// send SMS ... etc

#================#

# validation.url

// your code ...
if(!true) {
    Mpesa::deny();
}
else {
    Mpesa::confirm();
}

// your code ...


// ...setup...

$reversal = $mpesa->reversal();

$reversal->timeoutUrl('https://my.url/path/to/reversal/timeout')
        ->resultUrl('https://my.url/path/to/reversal/result')
        ->transId('1X1Y1ZNME') // transaction ID to reverse
        ->amount(100) // amount paid
        ->remarks('optional remarks') // optional
        ->occasion('optional occasion') // optional
        ->make();

if(!$reversal->accepted()) {
  $error = $reversal->error();
  echo "$error->code - $error->message";
  // exit;
}

// reversal initiated
$response = $reversal->response();
$originatorId = $response->OriginatorConversationID;
$conversationId = $response->ConversationID;
//...


// Transaction query
$query = $mpesa->query();

$query->transId('1X1Y1ZNME')
      ->resultUrl('https://my.url/path/to/timeout')
      ->timeoutUrl('https://my.url/path/to/result')
      ->remarks('optional remarks') // optional
      ->occasion('optional occasion') // optional
      ->make();

if(!$query->accepted()) {
  $error = $query->error();
  echo "$error->code - $error->message";
  // exit;
}

$response = $query->response();
$originatorId = $response->OriginatorConversationID;
$conversationId = $response->ConversationID;
//...

//...setup...

$balance = $mpesa->balance();

$balance->timeoutUrl('https://my.url/path/to/timeout')
        ->resultUrl('https://my.url/path/to/result')
        ->remarks('optional remarks') // optional
        ->check();

if(!$balance->accepted()){
  $error = $balance->error();
  echo "$error->code $error->message";
  // exit;
}

$response = $balance->response();
$originatorId = $response->OriginatorConversationID;
$conversationId = $response->ConversationID;
//...


// ...setup...
$b2b = $mpesa->b2b();
$b2b->amount(100)
    ->receiver('123456') // business you are paying to
    ->resultUrl('https://my.url/path/to/result')
    ->timeoutUrl('https://my.url/path/to/timeout');

# if receiver is a paybill number
$b2b->paybill()
    ->account('account-number'); 

# if receiver is a till number
$b2b->buygoods();

# optional
$b2b->remarks('optional remarks')
    ->occasion('optional occasion')
    ->requester('0712345678'); // the customer on
                               // whose behalf the money is
                               // being paid.

# make payment
$b2b->pay();

if(!$b2b->accepted()) {
  $error = $b2b->error();
  echo "$error->code $error->message";
  // exit;
}

$response = $b2b->response();
$originatorId = $response->OriginatorConversationID;
$conversationId = $response->ConversationID;
//...

//... save to db, etc

$b2c = $mpesa->b2c();

$b2c->amount(100)
    ->phone('0712345678')
    ->resultUrl('https://my.url/path/to/result')
    ->timeoutUrl('https://my.url/path/to/timeout');

# set payment purpose
$b2c->salary() // for salary payment
    ->promotion() // for promotion payment
    ->payment(); // for business payment

# optional
$b2c->remarks('optional-remarks')
    ->occasion('optional-occasion');

# pay
$b2c->pay();

if(!$b2c->accepted()) {
  $error = $b2c->error();
  echo "$error->code $error->message";
  // exit;
}

$response = $b2c->response();
$originatorId = $response->OriginatorConversationID;
$conversationId = $response->ConversationID;
//...

//... save to db, etc


// ...setup...

$remit = $mpesa->remitTax();

$remit->amount(1000)
      ->resultUrl('https://my.url/path/to/result')
      ->timeoutUrl('https://my.url/path/to/timeout')
      ->remarks('optional-remarks') // optional
      ->pay();

if(!$remit->accepted()) {
  $error = $remit->error();
  echo "$error->code $error->message";
  // exit;
}

$response = $remit->response();
$originatorId = $response->OriginatorConversationID;
$conversationId = $response->ConversationID;
//...

//... save to db, etc


//...setup...
$qr = $mpesa->qr();

$qr->size(300) // QR Code size (300x300)
   ->merchantName('Business Name')
   ->reference('account-number') // transaction reference
   ->amount(100);

# the receiver of the payment
# can be Till Number, Agent number, phone number
# paybill number, or business number
# Correspond to CPI in the Daraja doc
$qr->receiver('123457');

# sets the receiver type
# corresponds to TrxCode in the Daraja Doc
$qr->buygoods(); // receiver is a till number
$qr->paybill(); // receiver is a paybill number
$qr->sendMoney(); // receiver is a phone number
$qr->withdraw(); // receiver is an agent number
$qr->sendToBusiness(); // receiver is a business number

# generate code
$qr->generate();

if(!$qr->accepted()) {
  $error = $qr->error();
  echo "$error->code $error->message";
  // exit;
}

$response = $qr->response();
$qrCode = $response->QRCode;
$requestId = $response->RequestID;
//...

// ...setup...
$btb = $mpesa->btb();
$btb->amount(100)
    ->receiver('123456') // short code of the receiver 
    ->resultUrl('https://my.url/path/to/result')
    ->timeoutUrl('https://my.url/path/to/timeout');

# if in the same organization use
$btb->amount(100)
    ->toSelf() // accepts an optional short code param for sub-organizations
    ->resultUrl('https://my.url/path/to/result')
    ->timeoutUrl('https://my.url/path/to/timeout');

# optional
$btb->remarks('optional remarks') // optional
    ->requester('0712345678'); // optional - the customer on
                               // whose behalf the transfer is
                               // being made.

# make the transfer
$btb->transfer();

if(!$btb->accepted()) {
  $error = $btb->error();
  echo "$error->code $error->message";
  // exit;
}

$response = $btb->response();
$originatorId = $response->OriginatorConversationID;
$conversationId = $response->ConversationID;
//...

//... save to db, etc

// ...setup...
$subscription = $mpesa->subscription(); // same as $mpesa->ratiba();

$subscription->amount(100)
    ->plan("Gold Plan") // Standing order Name (same as $sub->name('Gold Plan'))
    ->phone('0740958756')
    ->startDate(10, 10, 2024) // month, day, year
    ->endDate(10, 11, 2024) // month, day, year
    ->frequency(Constant::FREQ_DAILY)
    ->callback('https://my.url/path/to/result');

# if your code is paybill number
$subscription->paybill() // if paybill number
    ->account('account-number'); 

# if using a till till number
$subscription->buygoods()
    ->till(1234567); // if till number

# optional
$subscription->description('optional description');

# create subscription
$subscription->create();

if(!$subscription->accepted()) {
  $error = $subscription->error();
  echo "$error->code $error->message";
  // exit;
}

$response = $subscription->response();
$refId = $response->responseRefID;
//...

//... save to db, etc
composer