PHPackages                             apxcde/laravel-mpesa-b2c - 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. [Payment Processing](/categories/payments)
4. /
5. apxcde/laravel-mpesa-b2c

ActiveLibrary[Payment Processing](/categories/payments)

apxcde/laravel-mpesa-b2c
========================

Laravel Package For Mpesa B2C

v0.2.0(8mo ago)3461[2 PRs](https://github.com/apxcde/laravel-mpesa-b2c/pulls)MITPHPPHP ^8.1CI passing

Since Oct 10Pushed 5mo ago1 watchersCompare

[ Source](https://github.com/apxcde/laravel-mpesa-b2c)[ Packagist](https://packagist.org/packages/apxcde/laravel-mpesa-b2c)[ Docs](https://github.com/apxcde/laravel-mpesa-b2c)[ GitHub Sponsors](https://github.com/apxcde)[ RSS](/packages/apxcde-laravel-mpesa-b2c/feed)WikiDiscussions main Synced yesterday

READMEChangelog (4)Dependencies (12)Versions (7)Used By (0)

Laravel Package For Mpesa B2C
=============================

[](#laravel-package-for-mpesa-b2c)

[![Latest Version on Packagist](https://camo.githubusercontent.com/29d7443a5d6c4b40761861155c702fc9ba53f00a29750635847d2e6a05da5cf5/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6170786364652f6c61726176656c2d6d706573612d6232632e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/apxcde/laravel-mpesa-b2c)[![Total Downloads](https://camo.githubusercontent.com/5ecf599f2a62e757e0a65f520565cb10912204925a7d39704f1876a453dcc576/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6170786364652f6c61726176656c2d6d706573612d6232632e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/apxcde/laravel-mpesa-b2c)

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

[](#installation)

You can install the package via composer:

```
composer require apxcde/laravel-mpesa-b2c
```

You can publish and run the migrations with:

```
php artisan vendor:publish --tag="laravel-mpesa-b2c-migrations"
php artisan migrate
```

You can publish the config file with:

```
php artisan vendor:publish --tag="laravel-mpesa-b2c-config"
```

This is the contents of the published config file:

```
return [
    'env' => env('MPESA_ENV', 'sandbox'),

    'shortcode' => env('MPESA_SHORTCODE', '600980'),

    'key' => env('MPESA_KEY', 'IWBJnpHUSMqGLVU21qhxFOdfTOzGjH5a'),

    'secret' => env('MPESA_SECRET', 'uqUYObhDprZoWFnG'),

    'username' => env('MPESA_USERNAME', 'testapi'),

    'password' => env('MPESA_PASSWORD', 'Safaricom980!'),

    'results_url' => env('MPESA_RESULTS_URL', ''),

    'timeout_url' => env('MPESA_TIMEOUT_URL', ''),

    'generated_password' => env('MPESA_GENERATED_PASSWORD', 'UNPMpfrhSfSeqN566HAlAQYaIQMeLvpEPZ5SiUR5pJn4faGYBnye251wCLGR56B3uOtT39UmoSeHtFhIa3torjhkXsfESm5NvKhIIOnHKa5Ry3rzeVxL+ruZE2st80HCLsbsJUQmvJ8vbE+h+NamH4DJi7JFHrHAPJ06BPjZuQEYbd/Lei1q4sdmQg6c38ZAnPIrvvWWidqxWc+uspbjqC+Dcyy6o9uwkfCCYGkvLtA8n2FM8MZazh/wgVjBOSV/RMmnt/cZjqoAiUVTkW6FMac77w1ejhweN4khV9mhmZvjmfaFmYi54nXbLSOC8FvkyiJf8uecNSAyWb5G/IhpaQ=='),

    'party_public_name' => env('MPESA_PARTY_PUBLIC_NAME', '4'),
];
```

Add Environment Variables
-------------------------

[](#add-environment-variables)

Set the variables below in your .env file.

```
MPESA_ENV=live
MPESA_SHORTCODE=
MPESA_KEY=
MPESA_SECRET=
MPESA_USERNAME=""
MPESA_PASSWORD=""
MPESA_RESULTS_URL="https://app-name.com/api/result-url"
MPESA_TIMEOUT_URL="https://app-name.com/api/timeout-url"
MPESA_PARTY_PUBLIC_NAME=2
MPESA_COMPLETED_DATE=3
MPESA_UTILITY_AVAILABLE=4
MPESA_WORKING_AVAILABLE=5
MPESA_REGISTERED=6
MPESA_CHARGES_PAID_ACCOUNT=7
```

The Values below would probably remain the same on your environment file. These are used to determine the returning values from the MPESA API.

```
MPESA_PARTY_PUBLIC_NAME=2
MPESA_COMPLETED_DATE=3
MPESA_UTILITY_AVAILABLE=4
MPESA_WORKING_AVAILABLE=5
MPESA_REGISTERED=6
MPESA_CHARGES_PAID_ACCOUNT=7
```

Usage
-----

[](#usage)

```
use Apxcde\LaravelMpesaB2c\MpesaB2C;
use Apxcde\LaravelMpesaB2c\Models\MpesaB2CTransaction;

MpesaB2C::init([]); // Initialize the Mpesa B2C API

MpesaB2C::send($phone_number, $amount, 'BusinessPayment', $remarks, null, function($response) use ($amount, $phone_number) {
    if (array_key_exists('errorCode', $response)) {
        return [
            'state' => 'Failed',
            'error_code' => $response['errorCode'],
            'error_message' => $response['errorMessage']
        ];
    }

    if($response["ResponseCode"] != 0) {
        return [ 'state' => 'Failed' ];
    }

    // You can save the transaction to your database here
    // You can modify the table by publishing the migration file and adding values like phone_number, account_number, etc
    // Saving the transaction to the database is important because MPESA responds to the results url (value in the .env file).
    MpesaB2CTransaction::create([
        'originator_conversation_id' => $response["OriginatorConversationID"],
        'conversation_id' => $response["ConversationID"],
        'description' => $response["ResponseDescription"],
        'transaction_amount' => $amount,
        'transaction_id' => $transaction->id,
    ]);

    return [
        'state' => 'Pending',
        'mpesa_transaction' => $mpesa_transaction,
        'description' => "Request to send ".money($amount)." to ". $phone_number . " received successfully \n"
    ];
});
```

In the controller of your results url, you can get the transaction by originator\_conversation\_id. Controller should look like this:

```
use Apxcde\LaravelMpesaB2c\Models\MpesaB2CTransaction;
use Apxcde\LaravelMpesaB2c\MpesaB2C;

class MpesaController extends Controller
{
    public function resultsUrl(Request $request)
    {
        MpesaB2C::reconcile(function($request) {
            $Result = $request["Result"];
            $ResultCode = $Result["ResultCode"];
            $ResultDesc = $Result["ResultDesc"];
            $TransactionID = $Result["TransactionID"];
            $OriginatorConversationID = $Result["OriginatorConversationID"];

            $transaction = MpesaB2CTransaction::find($OriginatorConversationID);

            // Check if the transaction failed
            if($ResultCode != 0) {
                // Update the saved transaction
                $transaction->update([
                    'state' => 'Failed',
                    'description' => $ResultDesc,
                    'mpesa_transaction_id' => $TransactionID,
                ]);
                // Do something else here: Send an email, SMS, etc
                // Return so the function doesn't continue
                return null;
            }

            $ResultParameter = $Result["ResultParameters"]["ResultParameter"];
            $ReceiverPartyPublicName = $ResultParameter[config('mpesa-b2c.party_public_name')]["Value"];

            // Update the saved transaction because the B2C transaction was successful
            $transaction->update([
                'state' => 'Accepted',
                'description' => $ResultDesc,
                'mpesa_transaction_id' => $TransactionID,
                'receiver_public_data' => $ReceiverPartyPublicName,
            ]);

            // You can do other things here: Send an email, SMS to the customer, etc
            // Also maybe update the customer's account in your database
        });
    }
}
```

```
## Testing

```bash
composer test
```

Changelog
---------

[](#changelog)

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

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

[](#contributing)

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

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

Please review [our security policy](../../security/policy) on how to report security vulnerabilities.

Credits
-------

[](#credits)

- [ApexCode](https://github.com/apxcde)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

37

—

LowBetter than 81% of packages

Maintenance65

Regular maintenance activity

Popularity12

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity50

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 53.5% 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 ~367 days

Total

4

Last Release

261d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/110383893?v=4)[ApexCode](/maintainers/apxcde)[@apxcde](https://github.com/apxcde)

---

Top Contributors

[![mwamodo](https://avatars.githubusercontent.com/u/52991058?v=4)](https://github.com/mwamodo "mwamodo (23 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (11 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (9 commits)")

---

Tags

laravellaravel-packagempesa-apimpesa-b2claravelapxcdelaravel-mpesa-b2c

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/apxcde-laravel-mpesa-b2c/health.svg)

```
[![Health](https://phpackages.com/badges/apxcde-laravel-mpesa-b2c/health.svg)](https://phpackages.com/packages/apxcde-laravel-mpesa-b2c)
```

###  Alternatives

[spatie/laravel-pdf

Create PDFs in Laravel apps

1.0k4.8M47](/packages/spatie-laravel-pdf)[dedoc/scramble

Automatic generation of API documentation for Laravel applications.

2.1k11.2M102](/packages/dedoc-scramble)[spatie/laravel-passkeys

Use passkeys in your Laravel app

471890.7k39](/packages/spatie-laravel-passkeys)[rawilk/profile-filament-plugin

Profile &amp; MFA starter kit for filament.

3914.6k](/packages/rawilk-profile-filament-plugin)[harris21/laravel-fuse

Circuit breaker for Laravel queue jobs. Protect your workers from cascading failures.

44855.7k](/packages/harris21-laravel-fuse)[vormkracht10/laravel-mails

Laravel Mails can collect everything you might want to track about the mails that has been sent by your Laravel app.

24857.5k](/packages/vormkracht10-laravel-mails)

PHPackages © 2026

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