PHPackages                             amos-o-7/laravel-mpesa - 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. amos-o-7/laravel-mpesa

ActiveLibrary[API Development](/categories/api)

amos-o-7/laravel-mpesa
======================

A Laravel package for M-Pesa C2B (Customer to Business) integration

2113PHP

Since Apr 14Pushed 1y ago2 watchersCompare

[ Source](https://github.com/amos-O-7/laravel-mpesa)[ Packagist](https://packagist.org/packages/amos-o-7/laravel-mpesa)[ RSS](/packages/amos-o-7-laravel-mpesa/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

Laravel M-Pesa Integration
==========================

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

A Laravel package for M-Pesa integration supporting both C2B (Customer to Business) and STK Push operations.

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

[](#installation)

You can install the package via composer:

```
composer require amos-o-7/laravel-mpesa
```

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

[](#configuration)

1. Publish the configuration file:

```
php artisan vendor:publish --provider="Mpesa\Providers\MpesaServiceProvider" --tag="config"
```

2. Add these variables to your `.env` file:

```
MPESA_BASE_URL=https://sandbox.safaricom.co.ke
MPESA_CONSUMER_KEY=your_consumer_key
MPESA_CONSUMER_SECRET=your_consumer_secret
MPESA_SHORTCODE=your_shortcode
MPESA_PASSKEY=your_passkey
MPESA_CALLBACK_URL=https://your-domain.com/api/mpesa/callback
MPESA_VALIDATION_URL=https://your-domain.com/api/mpesa/validate
MPESA_CONFIRMATION_URL=https://your-domain.com/api/mpesa/confirm
```

Usage
-----

[](#usage)

### Basic Usage

[](#basic-usage)

```
use Mpesa\Services\C2BService;

class PaymentController extends Controller
{
    protected $mpesa;

    public function __construct(C2BService $mpesa)
    {
        $this->mpesa = $mpesa;
    }

    // Register URLs (only needs to be done once)
    public function registerUrls()
    {
        try {
            $response = $this->mpesa->registerUrls();
            return response()->json($response);
        } catch (MpesaException $e) {
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }

    // Simulate a C2B payment (sandbox only)
    public function simulatePayment()
    {
        try {
            $response = $this->mpesa->simulateTransaction([
                'Amount' => 100,
                'BillRefNumber' => 'INV001',
                'PhoneNumber' => '254727343690'
            ]);
            return response()->json($response);
        } catch (MpesaException $e) {
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }
}
```

### Handling Callbacks

[](#handling-callbacks)

```
// Validation callback
public function validation(Request $request)
{
    Log::info('M-Pesa Validation', $request->all());
    return response()->json([
        'ResultCode' => 0,
        'ResultDesc' => 'Accepted'
    ]);
}

// Confirmation callback
public function confirmation(Request $request)
{
    Log::info('M-Pesa Confirmation', $request->all());
    return response()->json([
        'ResultCode' => 0,
        'ResultDesc' => 'Success'
    ]);
}
```

### STK Push (M-Pesa Express)

[](#stk-push-m-pesa-express)

The STK Push feature allows you to initiate M-Pesa payments by sending a payment prompt to the customer's phone.

#### 1. Basic Usage

[](#1-basic-usage)

```
use Mpesa\Services\STKPushService;

class PaymentController extends Controller
{
    protected $stkPush;

    public function __construct(STKPushService $stkPush)
    {
        $this->stkPush = $stkPush;
    }

    public function initiatePayment()
    {
        try {
            $response = $this->stkPush->initiateSTKPush(
                amount: 100, // Amount in KES
                phoneNumber: '254712345678',
                accountReference: 'INV001',
                transactionDesc: 'Payment for Invoice 001'
            );

            return response()->json($response);
        } catch (\Exception $e) {
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }
}
```

#### 2. Using the Built-in Controller

[](#2-using-the-built-in-controller)

The package comes with a pre-built controller. Just make a POST request to `/api/mpesa/stk/push` with the following parameters:

```
{
    "amount": 100,
    "phone": "254712345678",
    "account_reference": "INV001",
    "transaction_desc": "Payment for Invoice 001",
    "callback_url": "https://your-domain.com/custom-callback" // Optional
}
```

#### 3. Handling Callbacks

[](#3-handling-callbacks)

Create a callback handler to process M-Pesa payment notifications:

```
use Illuminate\Support\Facades\Log;

public function handleCallback(Request $request)
{
    $callbackData = $request->input('Body.stkCallback');

    if ($callbackData['ResultCode'] == 0) {
        // Payment successful
        $amount = $callbackData['CallbackMetadata']['Item'][0]['Value'];
        $mpesaReceiptNumber = $callbackData['CallbackMetadata']['Item'][1]['Value'];
        $transactionDate = $callbackData['CallbackMetadata']['Item'][2]['Value'];
        $phoneNumber = $callbackData['CallbackMetadata']['Item'][3]['Value'];

        // Process the payment...
    } else {
        // Payment failed
        $resultDesc = $callbackData['ResultDesc'];
        // Handle the failure...
    }
}
```

### Response Format

[](#response-format)

#### Successful Initiation

[](#successful-initiation)

```
{
    "MerchantRequestID": "29115-34620561-1",
    "CheckoutRequestID": "ws_CO_191220191020363925",
    "ResponseCode": "0",
    "ResponseDescription": "Success. Request accepted for processing",
    "CustomerMessage": "Success. Request accepted for processing"
}
```

#### Successful Payment Callback

[](#successful-payment-callback)

```
{
    "Body": {
        "stkCallback": {
            "MerchantRequestID": "29115-34620561-1",
            "CheckoutRequestID": "ws_CO_191220191020363925",
            "ResultCode": 0,
            "ResultDesc": "The service request is processed successfully.",
            "CallbackMetadata": {
                "Item": [
                    {
                        "Name": "Amount",
                        "Value": 100.00
                    },
                    {
                        "Name": "MpesaReceiptNumber",
                        "Value": "NLJ7RT61SV"
                    },
                    {
                        "Name": "TransactionDate",
                        "Value": 20191219102115
                    },
                    {
                        "Name": "PhoneNumber",
                        "Value": 254712345678
                    }
                ]
            }
        }
    }
}
```

### Error Handling

[](#error-handling)

The package throws `MpesaException` for M-Pesa API-related errors. Common error scenarios:

1. Invalid phone number format
2. Insufficient balance
3. Invalid credentials
4. Network errors

Always wrap your API calls in try-catch blocks to handle these errors gracefully.

### Testing

[](#testing)

```
composer test
```

Security
--------

[](#security)

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

Features
--------

[](#features)

- Token Generation
- URL Registration
- C2B Payment Simulation (Sandbox)
- STK Push (M-Pesa Express)
- Validation &amp; Confirmation Handling
- Error Handling
- Automatic Token Management

Credits
-------

[](#credits)

- [Amos O](https://github.com/amos-o-7)

License
-------

[](#license)

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

###  Health Score

18

—

LowBetter than 8% of packages

Maintenance35

Infrequent updates — may be unmaintained

Popularity13

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity15

Early-stage or recently created project

 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.

### Community

Maintainers

![](https://www.gravatar.com/avatar/1c42a56eaeaabded206a1445b8c49e1de9e2450e013f1ec34557d52309991370?d=identicon)[amos0-7](/maintainers/amos0-7)

---

Top Contributors

[![amos-O-7](https://avatars.githubusercontent.com/u/77561842?v=4)](https://github.com/amos-O-7 "amos-O-7 (7 commits)")

### Embed Badge

![Health badge](/badges/amos-o-7-laravel-mpesa/health.svg)

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

###  Alternatives

[stripe/stripe-php

Stripe PHP Library

4.0k143.3M480](/packages/stripe-stripe-php)[twilio/sdk

A PHP wrapper for Twilio's API

1.6k92.9M272](/packages/twilio-sdk)[knplabs/github-api

GitHub API v3 client

2.2k15.8M187](/packages/knplabs-github-api)[facebook/php-business-sdk

PHP SDK for Facebook Business

90121.9M34](/packages/facebook-php-business-sdk)[meilisearch/meilisearch-php

PHP wrapper for the Meilisearch API

73813.7M114](/packages/meilisearch-meilisearch-php)[google/gax

Google API Core for PHP

263103.1M454](/packages/google-gax)

PHPackages © 2026

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