PHP code example of brotechsploit / daraja

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

    

brotechsploit / daraja example snippets

 , match with the  config as sampled below in mpesa stk file 
$config = [
    'consumerkey'    => $_ENV['MPESA_CONSUMER_KEY'],
    'consumersecret' => $_ENV['MPESA_CONSUMER_SECRET'],
    'shortcode'      => $_ENV['MPESA_SHORTCODE'],
    'passkey'        => $_ENV['MPESA_PASSKEY'],
    'callbackurl'    => $_ENV['MPESA_CALLBACK_URL'],
    'sandbox'        => true,
    'apiusername'    => $_ENV['MPESA_INITIATOR_USERNAME'],
    'apipassword'    => $_ENV['MPESA_SECURITY_CREDENTIALS'],
    'timeouturl'     => $_ENV['QueueTimeOutURL'],
    'resulturl'      => $_ENV['ResultURL']
];


otenv\Dotenv;
use Brotechsploit\Daraja\Daraja;
$phonenumber = "254742513563";
$amount = (float)1;
$reference = 'VINCENT';
$dotenv = Dotenv::createImmutable(__DIR__);// change to fit .env directory
$dotenv->load();

$config = [
    'consumerkey'    => $_ENV['MPESA_CONSUMER_KEY'],
    'consumersecret' => $_ENV['MPESA_CONSUMER_SECRET'],
    'shortcode'      => $_ENV['MPESA_SHORTCODE'],
    'passkey'        => $_ENV['MPESA_PASSKEY'],
    'callbackurl'    => $_ENV['MPESA_CALLBACK_URL'],
    'sandbox'        => true,
    'apiusername'    => $_ENV['MPESA_INITIATOR_USERNAME'],
    'apipassword'    => $_ENV['MPESA_SECURITY_CREDENTIALS'],
    'timeouturl'     => $_ENV['QueueTimeOutURL'],
    'resulturl'      => $_ENV['ResultURL']
];

$daraja = new Daraja($config);
$response = $daraja->stkPush($phonenumber,$amount,$reference);

if(isset($response['ResponseCode']) && $response['ResponseCode'] === "0"){
    $CheckoutRequestID = $response['CheckoutRequestID'];
    $MerchantRequestID = $response['MerchantRequestID'];
    echo "payment request successfull . an stk push has been send to your phonenumber";

    //// here you can run you other code i.e inserting  in the database
}

print_r($response);

daraja/
│
│
│
├── callback/
│   └── (Callback responses)
│
├── .env
│
├── example/
│
│── composer.json
│── composer.lock
│── src/
│   └── Daraja.php
│── vendor/
│   ├── autoload.php
│   ├── composer/
│   │   ├── autoload_psr4.php
│   │   ├── autoload_real.php
│   │   └── ...
│   └── vlucas/

/example/mpesastkpush.php