PHP code example of leefipay / mpesa

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

    

leefipay / mpesa example snippets


use LeefiPay\Mpesa\Facades\LeefiPay;

$response = LeefiPay::stkPush([
    'phone' => '254700000000',
    'amount' => 100,
    'payment_channel_id' => 1,
    'reference' => 'ORDER-1001', // sent as account_reference
    'notes' => 'Payment for Order 1001',
    'idempotency_key' => 'order-1001',
]);

if ($response->success()) {
    $response->reference();
    $response->waitingUrl();
    $response->checkoutRequestId();
}

use LeefiPay\Mpesa\Contracts\LeefiPayClientInterface;

public function __construct(private LeefiPayClientInterface $leefiPay) {}

$status = LeefiPay::paymentStatus('PAY-12');

$verified = LeefiPay::verifyTransaction([
    'reference' => 'PAY-12',
    // or 'uuid' / 'checkout_request_id'
]);

$channels = LeefiPay::paymentChannels();

LeefiPay::testConnection();
LeefiPay::me();
LeefiPay::health(); // unauthenticated

use LeefiPay\Mpesa\Events\PaymentSuccessful;

Event::listen(PaymentSuccessful::class, function ($event) {
    $event->webhookEvent->paymentReference();
});

use LeefiPay\Mpesa\Exceptions\ApiException;
use LeefiPay\Mpesa\Exceptions\AuthenticationException;
use LeefiPay\Mpesa\Exceptions\ValidationException;
use LeefiPay\Mpesa\Exceptions\RateLimitException;

try {
    LeefiPay::stkPush([...]);
} catch (ValidationException $e) {
    $e->errors();
} catch (AuthenticationException $e) {
    // Invalid / missing Bearer token
} catch (RateLimitException $e) {
    // HTTP 429
} catch (ApiException $e) {
    $e->statusCode();
    $e->errorCode(); // e.g. subscription_expired
    $e->response();
}
bash
php artisan vendor:publish --tag=leefipay-config