PHP code example of apelimpesa / mpesa-php

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

    

apelimpesa / mpesa-php example snippets




$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();

use ApeliMpesa\Mpesa\Mpesa;

$mpesa = new Mpesa([
    'consumer_key' => getenv('MPESA_CONSUMER_KEY'),
    'consumer_secret' => getenv('MPESA_CONSUMER_SECRET'),
    'shortcode' => getenv('MPESA_SHORTCODE'),
    'passkey' => getenv('MPESA_PASSKEY'),
    'environment' => getenv('APP_ENV'), // 'development' or 'production'
]);

$response = $mpesa->stkPush([
    'amount' => 100,
    'phone' => '+254712345678',
    'reference' => 'Order123',
    'description' => 'Payment for Order123',
    'callback_url' => 'https://yourdomain.com/api/stk/callback',
]);

if ($response->isSuccessful()) {
    echo "STK Push initiated successfully. CheckoutRequestID: " . $response->getCheckoutRequestID();
} else {
    echo "Error: " . $response->getErrorMessage();
}

$response = $mpesa->queryTransactionStatus('CheckoutRequestID123');

if ($response->isSuccessful()) {
    echo "Transaction completed successfully.";
} else {
    echo "Error: " . $response->getErrorMessage();
}

$response = $mpesa->reverseTransaction([
    'transaction_id' => 'TransactionID123',
    'amount' => 100,
    'receiver' => '600000',
    'receiver_type' => 'Paybill',
    'callback_url' => 'https://yourdomain.com/api/reversal/callback',
]);

if ($response->isSuccessful()) {
    echo "Transaction reversed successfully.";
} else {
    echo "Error: " . $response->getErrorMessage();
}
ini
APP_ENV=production