PHPackages                             breviam/mpesa-sdk - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. breviam/mpesa-sdk

ActiveLibrary[API Development](/categories/api)

breviam/mpesa-sdk
=================

Laravel SDK for M-Pesa Daraja API

v1.1.0(12mo ago)044GPL-3.0-or-laterPHPPHP ^8.1CI passing

Since Jul 8Pushed 12mo agoCompare

[ Source](https://github.com/Breviam-LLP/MpesaSDK)[ Packagist](https://packagist.org/packages/breviam/mpesa-sdk)[ RSS](/packages/breviam-mpesa-sdk/feed)WikiDiscussions main Synced today

READMEChangelog (3)Dependencies (6)Versions (6)Used By (0)

STILL UNDER DEVELOPMENT
=======================

[](#still-under-development)

M-Pesa Laravel SDK
==================

[](#m-pesa-laravel-sdk)

[![Latest Version on Packagist](https://camo.githubusercontent.com/68a3b866713be529ccb2fbbd79e7685e293bf453150594bd588907b13e768a04/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6272657669616d2f6d706573612d73646b2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/breviam/mpesa-sdk)[![Total Downloads](https://camo.githubusercontent.com/15db6948a317d3f660064e61272acd5f529406dc94f9581b8fa9aa11b2bafd9e/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6272657669616d2f6d706573612d73646b2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/breviam/mpesa-sdk)[![Tests](https://camo.githubusercontent.com/7701a6c52c81f7e9c83ce0b448979cff466c70514149d2d1086ed8a6c0295913/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f4272657669616d2d4c4c502f4d7065736153444b2f63692e796d6c3f6c6162656c3d7465737473)](https://github.com/Breviam-LLP/MpesaSDK/actions/workflows/ci.yml)

A comprehensive Laravel SDK for integrating with Safaricom's M-Pesa Daraja API. This package provides a clean, well-documented interface for all major M-Pesa services including STK Push, C2B, B2C, Transaction Status, and Account Balance.

Features
--------

[](#features)

- ✅ **STK Push** (Lipa na M-Pesa Online)
- ✅ **C2B** (Customer to Business) payments
- ✅ **B2C** (Business to Customer) payments
- ✅ **Transaction Status** queries
- ✅ **Account Balance** inquiries
- ✅ **Webhook handling** with automatic route registration
- ✅ **Token management** with automatic caching
- ✅ **Laravel Facade** support
- ✅ **Artisan commands** for testing and debugging
- ✅ **Comprehensive logging**
- ✅ **Event-driven architecture**
- ✅ **Full test coverage**

Requirements
------------

[](#requirements)

- PHP 8.1+
- Laravel 11.x (recommended)
- Laravel 10.x (experimental support)

> **Note**: For detailed Laravel version compatibility information, see [LARAVEL\_COMPATIBILITY.md](LARAVEL_COMPATIBILITY.md)

Installation
------------

[](#installation)

Install the package via Composer:

```
composer require breviam/mpesa-sdk
```

Publish the configuration file:

```
php artisan vendor:publish --tag=mpesa-config
```

Configuration
-------------

[](#configuration)

Add your M-Pesa credentials to your `.env` file:

```
MPESA_ENV=sandbox
MPESA_CONSUMER_KEY=your_consumer_key
MPESA_CONSUMER_SECRET=your_consumer_secret
MPESA_SHORTCODE=your_shortcode
MPESA_PASSKEY=your_passkey
MPESA_INITIATOR_NAME=your_initiator_name
MPESA_SECURITY_CREDENTIAL=your_security_credential
MPESA_CALLBACK_URL=https://yourdomain.com/mpesa/webhooks

# Optional: Withdrawal-specific credentials (if different)
MPESA_W_CONSUMER_KEY=your_withdrawal_consumer_key
MPESA_W_CONSUMER_SECRET=your_withdrawal_consumer_secret
MPESA_W_SHORTCODE=your_withdrawal_shortcode
MPESA_INITIATOR_W_NAME=your_withdrawal_initiator
MPESA_INITIATOR_W_PASS=your_withdrawal_security_credential

# Optional: Service-specific callback URLs
MPESA_STK_CALLBACK_URL=https://yourdomain.com/mpesa/stk
MPESA_C2B_CALLBACK_URL=https://yourdomain.com/mpesa/c2b
MPESA_B2C_CALLBACK_URL=https://yourdomain.com/mpesa/b2c
```

Basic Usage
-----------

[](#basic-usage)

### STK Push (Lipa na M-Pesa Online)

[](#stk-push-lipa-na-m-pesa-online)

```
use Breviam\MpesaSdk\Facades\Mpesa;

// Initiate STK Push
$response = Mpesa::stkPush(
    phone: '254712345678',
    amount: 100,
    reference: 'ORDER123',
    description: 'Payment for order #123'
);

// Query STK Push status
$status = Mpesa::stkQuery($response['CheckoutRequestID']);
```

### C2B (Customer to Business)

[](#c2b-customer-to-business)

```
// Register C2B URLs (usually done once)
$response = Mpesa::c2b()->registerUrls(
    confirmationUrl: 'https://yourdomain.com/mpesa/webhooks/c2b/confirmation',
    validationUrl: 'https://yourdomain.com/mpesa/webhooks/c2b/validation'
);

// Simulate C2B payment (sandbox only)
$response = Mpesa::c2b()->simulate(
    phone: '254712345678',
    amount: 100,
    reference: 'BILL123'
);
```

### B2C (Business to Customer)

[](#b2c-business-to-customer)

```
$response = Mpesa::sendMoney(
    phone: '254712345678',
    amount: 1000,
    commandId: 'BusinessPayment',
    remarks: 'Salary payment'
);
```

### Account Balance

[](#account-balance)

```
$response = Mpesa::checkBalance('Balance inquiry');
```

### Transaction Status

[](#transaction-status)

```
$response = Mpesa::checkTransactionStatus(
    transactionId: 'ABC123XYZ',
    partyA: '254712345678',
    remarks: 'Transaction status check'
);
```

Advanced Usage
--------------

[](#advanced-usage)

### Using Individual Services

[](#using-individual-services)

```
use Breviam\MpesaSdk\Contracts\StkInterface;
use Breviam\MpesaSdk\Contracts\AuthInterface;

class PaymentController extends Controller
{
    public function __construct(
        private StkInterface $stkService,
        private AuthInterface $authService
    ) {}

    public function initiatePayment()
    {
        $response = $this->stkService->push(
            '254712345678',
            100,
            'ORDER123',
            'Payment description'
        );

        return response()->json($response);
    }
}
```

### Handling Webhooks

[](#handling-webhooks)

The package automatically registers webhook routes. You can listen to events:

```
use Illuminate\Support\Facades\Event;

// In your EventServiceProvider
Event::listen('mpesa.stk.callback', function ($data) {
    // Handle STK Push callback
    Log::info('STK Push callback received', $data);
});

Event::listen('mpesa.c2b.confirmation', function ($data) {
    // Handle C2B confirmation
    $payment = Payment::where('reference', $data['BillRefNumber'])->first();
    $payment->update(['status' => 'confirmed']);
});
```

### Artisan Commands

[](#artisan-commands)

Check token status:

```
php artisan mpesa:token
```

Clear token cache:

```
php artisan mpesa:token --clear
```

Simulate payment (sandbox only):

```
php artisan mpesa:simulate-payment 254712345678 100 --reference=TEST123
```

Testing
-------

[](#testing)

Run the tests:

```
composer test
```

Run tests with coverage:

```
composer test:coverage
```

Events
------

[](#events)

The package fires the following events:

EventDescription`mpesa.stk.callback`STK Push callback received`mpesa.c2b.validation`C2B validation request`mpesa.c2b.confirmation`C2B confirmation received`mpesa.b2c.result`B2C transaction result`mpesa.b2c.timeout`B2C transaction timeout`mpesa.balance.result`Balance inquiry result`mpesa.balance.timeout`Balance inquiry timeout`mpesa.transaction.result`Transaction status result`mpesa.transaction.timeout`Transaction status timeoutConfiguration Options
---------------------

[](#configuration-options)

The package supports extensive configuration through the `config/mpesa.php` file:

```
return [
    'env' => 'sandbox', // or 'production'
    'consumer_key' => env('MPESA_CONSUMER_KEY'),
    'consumer_secret' => env('MPESA_CONSUMER_SECRET'),
    'shortcode' => env('MPESA_SHORTCODE'),
    'passkey' => env('MPESA_PASSKEY'),
    'initiator' => env('MPESA_INITIATOR'),
    'security_credential' => env('MPESA_SECURITY_CREDENTIAL'),
    'callback_url' => env('MPESA_CALLBACK_URL'),

    'cache' => [
        'prefix' => 'mpesa_',
        'ttl' => 3300, // 55 minutes
    ],

    'timeout' => 30,

    'logging' => [
        'enabled' => true,
        'channel' => 'daily',
    ],
];
```

Security
--------

[](#security)

- All sensitive data is masked in logs
- OAuth tokens are securely cached
- HTTPS is enforced for all API calls
- Webhook requests are logged with IP and user agent

Error Handling
--------------

[](#error-handling)

The package throws specific exceptions:

```
use Breviam\MpesaSdk\Exceptions\MpesaException;
use Breviam\MpesaSdk\Exceptions\AuthenticationException;

try {
    $response = Mpesa::stkPush('254712345678', 100, 'REF123', 'Description');
} catch (AuthenticationException $e) {
    // Handle authentication errors
    Log::error('M-Pesa authentication failed: ' . $e->getMessage());
} catch (MpesaException $e) {
    // Handle general M-Pesa API errors
    Log::error('M-Pesa API error: ' . $e->getMessage());
    $context = $e->getContext(); // Get additional context
}
```

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

Security
--------

[](#security-1)

If you discover any security-related issues, please email  instead of using the issue tracker.

Credits
-------

[](#credits)

- [Victor Kariuki](https://github.com/breviam)
- [All Contributors](../../contributors)

License
-------

[](#license)

The GNU General Public License v3.0. Please see [License File](LICENSE.md) for more information.

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

###  Health Score

31

—

LowBetter than 66% of packages

Maintenance50

Moderate activity, may be stable

Popularity8

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity49

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

3

Last Release

360d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/76d2be09f76277d33702df566b417f1b69e99cb0810279f42a6199221df3d365?d=identicon)[Breviam](/maintainers/Breviam)

---

Top Contributors

[![victorKariuki](https://avatars.githubusercontent.com/u/82287651?v=4)](https://github.com/victorKariuki "victorKariuki (35 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/breviam-mpesa-sdk/health.svg)

```
[![Health](https://phpackages.com/badges/breviam-mpesa-sdk/health.svg)](https://phpackages.com/packages/breviam-mpesa-sdk)
```

###  Alternatives

[psalm/plugin-laravel

Psalm plugin for Laravel

3355.3M346](/packages/psalm-plugin-laravel)[laravel/pulse

Laravel Pulse is a real-time application performance monitoring tool and dashboard for your Laravel application.

1.7k15.1M132](/packages/laravel-pulse)[roots/acorn

Framework for Roots WordPress projects built with Laravel components.

9762.4M131](/packages/roots-acorn)[laravel/mcp

Rapidly build MCP servers for your Laravel applications.

77022.3M151](/packages/laravel-mcp)[mike-bronner/laravel-model-caching

Automatic caching for Eloquent models.

2.4k91.0k1](/packages/mike-bronner-laravel-model-caching)[api-platform/laravel

API Platform support for Laravel

58171.5k14](/packages/api-platform-laravel)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
