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


    //USING ARROW FUNCTION
    
       $credentials = new Mpesa();
    // replace consumerkey with consumer key from daraja portal
    // Replace consumer secret with consumer secret from daraja portal
    // in the env it either "live" or "develoment
    $mpesa = $credentials->consumerKey("CONSUMER_KEY")->consumerSecret("CONSUMER_SECRET")->env("live")->setCredentials();
 

    // PASSING KEY AS PARAMETERS IN SET CREDENTIALS
    $credentials = new Mpesa();
    $mpesa = $credentials->setCredentials("CONSUMER_KEY", "CONSUMER_SECRET", "live");
 

     $stk = $mpesa->stk()
     ->businessCode("BUSINESS_CODE")
     ->amount(AMOUNT)
     ->phoneNumber("PHONE_NUMBER")
     ->callBackUrl("CALL_BACK_URL")
     ->transactionType("CustomerPayBillOnline")
     ->accountReference("ACCOUNT-REFERENCE")
     ->transactionDesc("TRANSACTION_DESC")
     ->passKey("PASS_KEY");
    // Get response in and store it after sending a push
    $response = $stk->push()->response();
    // Query STK Push and check its status
    $transactionQuery = $push->query();
 

    $registerUrl = $mpesa->customerToBusiness()
      ->responseType("Completed")
      ->validationUrl("https://mydomain.com/confirmation")
      ->confirmationUrl("https://mydomain.com/confirmation")
      ->businessCode("600984")->registerUrl();
    // Get the response
    $response = $registerUrl->response();
  

    $c2b = $mpesa->customerToBusiness();
    $simulate = $c2b->businessCode("600988")->commandId("CustomerBuyGoodsOnline")->amount("10")->phoneNumber("PHONE_NUMBER")->simulate();
    // You can add 
    ->billRefNumber("BILL REF_NUMBER") //  For pay bills only
    
   
    // Get the response
    $response = $simulate->response();   
   
  

  
      $b2c = $mpesa->businessToCustomer();
      $paymentRequest = $b2c
      ->initiatorName("INITIATOR_NAME")
      ->securityCredential("INTIATOR_PASSWORD")
      ->commandId("SalaryPayment")
      ->amount(AMOUNT) //int
      ->businessCode("600584")
      ->phoneNumber("PHONE_NUMBER")->remarks("Test")
      ->queueTimeoutUrl("https://mydomain.com/b2c/queue")
      ->resultUrl("https://mydomain.com/b2c/queue")
      ->occasion("Test")->paymentRequest();
    $response = $paymentRequest->response();
    print_r($response->response());
  
  

composer