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

ActiveLibrary[Payment Processing](/categories/payments)

akika/laravel-mpesa
===================

A single-tenant Laravel package for integrating Mpesa Daraja API. The package supports Laravel version 5 and above.

v1.16(9mo ago)3566↓50%3[2 issues](https://github.com/akikadigital/laravel-mpesa/issues)MITPHPPHP ^8.0

Since Apr 7Pushed 6mo ago1 watchersCompare

[ Source](https://github.com/akikadigital/laravel-mpesa)[ Packagist](https://packagist.org/packages/akika/laravel-mpesa)[ Docs](https://github.com/Akika-Digital/laravel-mpesa)[ RSS](/packages/akika-laravel-mpesa/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (3)Versions (15)Used By (0)

Laravel Mpesa Package by [Akika Digital](https://akika.digital)
---------------------------------------------------------------

[](#laravel-mpesa-package-by-akika-digital)

This Laravel package provides convenient methods for integrating [Mpesa Daraja API's](https://developer.safaricom.co.ke/APIs) functionalities into your Laravel application.

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

[](#installation)

You can install the package via composer:

```
composer require akika/laravel-mpesa
```

After installing the package, publish the configuration file using the following command:

```
php artisan mpesa:install
```

This will generate a mpesa.php file in your config directory where you can set your Mpesa credentials and other configuration options.

.env file Setup
---------------

[](#env-file-setup)

Add the following configurations into the .env file

```
MPESA_ENV=
MPESA_APP_DEBUG=
MPESA_SHORTCODE=
MPESA_CONSUMER_KEY=
MPESA_CONSUMER_SECRET=
MPESA_PASSKEY=
MPESA_INITIATOR_NAME=
MPESA_INITIATOR_PASSWORD=
MPESA_STK_VALIDATION_URL=
MPESA_STK_CONFIRMATION_URL=
MPESA_STK_CALLBACK_URL=
MPESA_BALANCE_RESULT_URL=
MPESA_BALANCE_TIMEOUT_URL=
MPESA_TRANSACTION_STATUS_RESULT_URL=
MPESA_TRANSACTION_STATUS_TIMEOUT_URL=
MPESA_B2C_TIMEOUT_URL=
MPESA_B2C_RESULT_URL=
MPESA_B2C_TOPUP_TIMEOUT_URL=
MPESA_B2C_TOPUP_RESULT_URL=
MPESA_B2B_TIMEOUT_URL=
MPESA_B2B_RESULT_URL=
MPESA_B2B_EXPRESS_CHECKOUT_URL=
MPESA_REVERSAL_TIMEOUT_URL=
MPESA_REVERSAL_RESULT_URL=
MPESA_BILL_MANAGER_LOGO_URL=
MPESA_BILL_MANAGER_OPTIN_CALLBACK_URL=
MPESA_TAX_REMITTANCE_TIMEOUT_URL=
MPESA_TAX_REMITTANCE_RESULT_URL=
MPESA_RATIBA_CALLBACK_URL=

```

NOTE: The mpesa.php config file sets the default `MPESA_ENV` value to `sandbox`. This will always load sandbox urls.

Function Responses
------------------

[](#function-responses)

All responses, except the token generation response, conform to the responses documented on the daraja portal.

Usage
-----

[](#usage)

### Initializing Mpesa

[](#initializing-mpesa)

```
use Akika\LaravelMpesa\Mpesa;

$mpesa = new Mpesa();
```

### Fetching Token

[](#fetching-token)

You can fetch the token required for Mpesa API calls as follows:

```
$token = $mpesa->getToken();
```

### Getting Account Balance

[](#getting-account-balance)

You can fetch mpesa account balance as follows:

```
$balance = $mpesa->getBalance();
```

### C2B Transactions

[](#c2b-transactions)

#### Registering URLs for C2B Transactions

[](#registering-urls-for-c2b-transactions)

You can register validation and confirmation URLs for C2B transactions:

```
$response = $mpesa->c2bRegisterUrl();
```

You can register the C2B URLs using the provided command below:

```
php artisan mpesa:register-c2b-urls
```

The above command requires you to have set the below variables in your env or in the config file:

```
MPESA_SHORTCODE=
MPESA_STK_VALIDATION_URL=
MPESA_STK_CONFIRMATION_URL=

```

#### Simulating C2B Transactions

[](#simulating-c2b-transactions)

You can simulate payment requests from clients:

```
$response = $mpesa->c2bSimulate($amount, $phoneNumber, $billRefNumber, $commandID);
```

#### Initiating STK Push

[](#initiating-stk-push)

You can initiate online payment on behalf of a customer:

```
$response = $mpesa->stkPush($accountNumber, $phoneNumber, $amount, $transactionDesc);
```

- `$transactionDesc` can be null

#### Querying STK Push Status

[](#querying-stk-push-status)

You can query the result of a STK Push transaction:

```
$response = $mpesa->stkPushStatus($checkoutRequestID);
```

#### Reversing Transactions

[](#reversing-transactions)

You can reverse a C2B M-Pesa transaction:

```
$response = $mpesa->reverse($transactionId, $amount, $receiverShortCode, $remarks);
```

- `$ocassion` is an optional field.

### Business to Customer (B2C) Transactions

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

You can perform Business to Customer transactions:

```
$response = $mpesa->b2cTransaction($oversationId, $commandID, $msisdn, $amount, $remarks, $ocassion);
```

- `$ocassion` is an optional field.

### B2C Topup

[](#b2c-topup)

This API enables you to load funds to a B2C shortcode directly for disbursement. The transaction moves money from your MMF/Working account to the recipient’s utility account.

```
$response = $mpesa->b2cTopup($accountReference, $receiverShortCode, $amount, $remarks);
```

- `$accountReference`: A unique (system generated) identifier for the transaction.
- `$receiverShortCode`: The shortcode to which money will be moved
- `$amount`: The transaction amount.
- `$remarks`: Any additional information to be associated with the transaction.

### Business to Business (B2B) Transactions

[](#business-to-business-b2b-transactions)

#### B2B Paybill

[](#b2b-paybill)

You can perform Business to Business transactions:

```
$response = $mpesa->b2bPaybill($destShortcode, $amount, $remarks, $accountNumber, $resultUrl, $timeoutUrl, $requester = null);
```

- `$destShortcode`: This is the party receiving the money.
- `$accountNumber`: The account number to be associated with the payment. Up to 13 characters.
- `$requester` is an optional field.

#### B2B Buy Goods

[](#b2b-buy-goods)

This api accepts variables as provided in section [B2B Paybill](b2b-paybill) above.

```
$response = $mpesa->b2bBuyGoods($destShortcode, $amount, $remarks, $accountNumber, $resultUrl, $timeoutUrl, $requester = null);
```

#### B2B Express Checkout

[](#b2b-express-checkout)

```
$response = $mpesa->b2bExpressCheckout($destShortcode, $partnerName, $amount, $paymentReference, $requestRefID);
```

- `$destShortcode`: This is the party receiving the money.
- `$partnerName`: This is the organization Friendly name used by the vendor as known by the Merchant.
- `$paymentReference`: This is a reference to the payment being made. This will appear in the text for easy reference by the merchant. e.g. Order ID
- `$requestRefID`: This is an auto-genarated reference ID generated by your system.

### QR Code Generation

[](#qr-code-generation)

You can generate QR codes for making payments:

```
$response = $mpesa->dynamicQR($merchantName, $refNo, $trxCode, $cpi, $size, $amount = null);
```

- `$amount` is an optional field

### Bill Manager

[](#bill-manager)

You can optin to the bill manager service and send invoices:

```
$response = $mpesa->billManagerOptin($email, $phoneNumber, $sendReminders);

$response = $mpesa->sendInvoice($reference, $billedTo, $phoneNumber, $billingPeriod, $invoiceName, $dueDate, $amount, $items);
```

- `$sendReminders` is a boolean field. Allows true or false (1 or 0)

### Tax Remittance

[](#tax-remittance)

You can remit tax to the government:

```
$response = $mpesa->taxRemittance($amount, $receiverShortCode, $accountReference, $remarks);
```

### Mpesa Ratiba

[](#mpesa-ratiba)

The Standing Order APIs enable teams to integrate with the standing order solution by initiating a request to create a standing order on the customer profile.

```
$response = $mpesa->ratiba($name, $startDate, $endDate, $transactionType, $type, $amount, $msisdn,$accountReference, $transactionDesc, $frequency)
```

- `$name`: Name of standing order that must be unique for each customer.
- `$startDate`: The date you wish for the standing order to start executing
- `$endDate`: The date you wish for the standing order to stop executing
- `$transactionType`: This is the transaction type that is used to identify the transaction when sending the request to M-PESA. Either till or paybill
- `$type`: This is the transaction type that is used to identify the transaction when sending the request to M-PESA.
- `$amount`: This is the money that the customer pays to the Shortcode.
- `$phoneNumber`: The phone number sending money. The parameter expected is a Valid Safaricom Mobile Number that is M-PESA registered in the format 2547XXXXXXXX
- `$accountReference`: This is a unique identifier for the transaction and is generated by the system. It has a maximum limit of 13 characters.
- `$transactionDesc`: This is any additional information/comment that can be sent along with the request from your system. Maximum of 13 Characters
- `$frequency`: The frequency of the standing order (one-off, daily, weekly, monthly, bi-monthly, quarterly, half-year, annually)

### Mpesa Transaction History

[](#mpesa-transaction-history)

The following API takes in the start and and end dates and returns the transactions between that period.

```
$response = $mpesa->mpesaTransactionsHistory($startDate, $endDate, $offset = 0);
```

#### Successful Response

[](#successful-response)

```
{
    "ResponseRefID": "8bab-42cc-bb85-5056a6c01e6915928124",
    "ResponseCode": "1000",
    "ResponseMessage": "Success",
    "Response": [
        [
            {
                "transactionId": "XXXXXXXXX",
                "trxDate": "2025-01-24T10:56:11+03:00",
                "msisdn": 2547XXXXXXXX,
                "sender": "MPESA",
                "transactiontype": "c2b-buy-goods-debit",
                "billreference": "",
                "amount": "2697.0",
                "organizationname": "VENDOR"
            }
        ]
    ]
}
```

API Response Body
-----------------

[](#api-response-body)

$response has the following as a json object

```
{
    "OriginatorConversationID": "5118-111210482-1",
    "ConversationID": "AG_20230420_2010759fd5662ef6d054",
    "ResponseCode": "0",
    "ResponseDescription": "Accept the service request successfully."
}
```

Succssful result body
---------------------

[](#succssful-result-body)

A successful result body has the following structure

```
{
 "Result":
 {
   "ResultType": "0",
   "ResultCode":"0",
   "ResultDesc": "The service request is processed successfully",
   "OriginatorConversationID":"626f6ddf-ab37-4650-b882-b1de92ec9aa4",
   "ConversationID":"12345677dfdf89099B3",
   "TransactionID":"QKA81LK5CY",
   "ResultParameters":
     {
       "ResultParameter":
          [{
           "Key":"DebitAccountBalance",
           "Value":"{Amount={CurrencyCode=KES, MinimumAmount=618683, BasicAmount=6186.83}}"
          },
          {
          "Key":"Amount",
           "Value":"190.00"
          },
           {
          "Key":"DebitPartyAffectedAccountBalance",
           "Value":"Working Account|KES|346568.83|6186.83|340382.00|0.00"
          },
           {
          "Key":"TransCompletedTime",
           "Value":"20221110110717"
          },
           {
          "Key":"DebitPartyCharges",
           "Value":""
          },
           {
          "Key":"ReceiverPartyPublicName",
           "Value":000000– Biller Companty
          },
          {
          "Key":"Currency",
           "Value":"KES"
          },
          {
           "Key":"InitiatorAccountCurrentBalance",
           "Value":"{Amount={CurrencyCode=KES, MinimumAmount=618683, BasicAmount=6186.83}}"
          }]
       },
     "ReferenceData":
       {
        "ReferenceItem":[
           {"Key":"BillReferenceNumber", "Value":"19008"},
           {"Key":"QueueTimeoutURL", "Value":"https://mydomain.com/b2b/businessbuygoods/queue/"}
         ]
      }
 }
}
```

Unsuccessful reusult body
-------------------------

[](#unsuccessful-reusult-body)

An unsuccessful result body has the following structure

```
{
 "Result":
 {
   "ResultType":0,
   "ResultCode":2001,
   "ResultDesc":"The initiator information is invalid.",
   "OriginatorConversationID":"12337-23509183-5",
   "ConversationID":"AG_20200120_0000657265d5fa9ae5c0",
   "TransactionID":"OAK0000000",
   "ResultParameters":{
     "ResultParameter":{
        "Key":"BillReferenceNumber",
        "Value":12323333
      }
   },
   "ReferenceData":{
     "ReferenceItem":[
      {
        "Key":"BillReferenceNumber",
        "Value":12323333
      },
      {
        "Key":"QueueTimeoutURL",
        "Value":"https://internalapi.safaricom.co.ke/mpesa/abresults/v1/submit"
      }
      {
        "Key":"Occassion"
      }
     ]
    }
 }
}
```

License
-------

[](#license)

The Laravel Mpesa package is open-sourced software licensed under the MIT license. See the LICENSE file for details.

###  Health Score

36

—

LowBetter than 82% of packages

Maintenance50

Moderate activity, may be stable

Popularity21

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity53

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 ~40 days

Recently: every ~48 days

Total

13

Last Release

279d ago

Major Versions

v0.0.8 → v1.0.92025-01-24

PHP version history (2 changes)v1.0.1PHP ^8.0|^8.1|^8.2

v1.1.5PHP ^8.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/3b9d9e3a6ef73a3692c261d49a7a70d0362c5e83fa9a4e8765eb9309173b59b3?d=identicon)[akika.digital](/maintainers/akika.digital)

---

Top Contributors

[![fenicfelix](https://avatars.githubusercontent.com/u/7171039?v=4)](https://github.com/fenicfelix "fenicfelix (81 commits)")

---

Tags

akikaakikadigitaldaraja-mpesadaraja-mpesa-laravellaravelmpesampesa-apimpesa-laravelpayment-gatewaypaymentslaravelpaymentmpesaAkikadigitaldaraja

### Embed Badge

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

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

###  Alternatives

[sebdesign/laravel-viva-payments

A Laravel package for integrating the Viva Payments gateway

4845.9k](/packages/sebdesign-laravel-viva-payments)[iankumu/mpesa

A package that helps integrate the Mpesa APIs to your Laravel Project

5014.7k](/packages/iankumu-mpesa)[itsmurumba/laravel-mpesa

Laravel Package for Mpesa Daraja API

191.6k](/packages/itsmurumba-laravel-mpesa)[henryejemuta/laravel-monnify

A laravel package to seamlessly integrate monnify api within your laravel application

132.1k](/packages/henryejemuta-laravel-monnify)

PHPackages © 2026

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