PHPackages                             maina-david/multi-shortcode-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. [Utility &amp; Helpers](/categories/utility)
4. /
5. maina-david/multi-shortcode-mpesa

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

maina-david/multi-shortcode-mpesa
=================================

Multiple shortcode mpesa integration

111PHP

Since Sep 13Pushed 1y ago1 watchersCompare

[ Source](https://github.com/maina-david/multi-shortcode-mpesa)[ Packagist](https://packagist.org/packages/maina-david/multi-shortcode-mpesa)[ RSS](/packages/maina-david-multi-shortcode-mpesa/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

Multi-Shortcode-Mpesa-PHP
=========================

[](#multi-shortcode-mpesa-php)

This package seeks to help php developers implement the various Mpesa APIs without much hustle. It is based on the REST API whose documentation is available on .

It supports multiple shortcodes on both sandbox and production environments.

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

[](#installation)

You can install the PHP SDK via composer or by downloading the source

#### Via Composer

[](#via-composer)

The recommended way to install the SDK is with [Composer](http://getcomposer.org/).

```
composer require maina-david/multi-shortcode-mpesa
```

Optional: The service provider will automatically get registered. Or you may manually add the service provider in your config/app.php file:

```
'providers' => [
    // ...
    MainaDavid\MultiShortcodeMpesa\MpesaServiceProvider::class,
];

```

You should publish the shortcode migration and the config/multi-shortcode-mpesa.php config file with:

```
php artisan vendor:publish --provider="MainaDavid\MultiShortcodeMpesa\MpesaServiceProvider"
```

You can overwrite the default urls in config/multi-shortcode-mpesa.php file.

Clear your config cache. This package requires access to the multi-shortcode-mpesa config. Generally it's bad practice to do config-caching in a development environment. If you've been caching configurations locally, clear your config cache with either of these commands:

```
 php artisan optimize:clear
 # or
 php artisan config:clear
```

Run the migrations: After the config and migration have been published and configured, you can create the tables for this package by running:

```
 php artisan migrate
```

Usage
-----

[](#usage)

The SDK needs to be instantiated using one of your shortcode saved in the short\_codes table and expects following values to be encrypted when storing them in the database for security reasons. It will decrypt the values, if unable it will throw an error.

- consumer\_key.
- consumer\_secret.
- pass\_key.
- initiator\_name.
- initiator\_password.

### Example saving a shortcode to the database

[](#example-saving-a-shortcode-to-the-database)

```
use MainaDavid\MultiShortcodeMpesa\Models\ShortCode;

    /**
     * It validates the request, creates a new shortcode object, encrypts the sensitive data and saves it
     * to the database
     *
     * @param Request request The request object.
     *
     * @return A JSON response with a success message.
     */
    public function storeShortCode(Request $request)
    {
        /* Validating the request. */
        $request->validate([
            'environment' => 'required|in:sandbox,production',
            'direction' => 'required|in:c2b,b2c',
            'shortcode' => 'required|integer',
            'consumer_key' => 'required',
            'consumer_secret' => 'required',
            'pass_key' => 'required_if:direction,c2b',
            'initiator_name' => 'required_if:direction,b2c',
            'initiator_password' => 'required_if:direction,b2c',
        ]);

        $shortcode = new ShortCode();
        $shortcode->environment = $request->environment; //sandbox or production
        $shortcode->direction = $request->direction; // c2b or b2c
        $shortcode->shortcode = $request->shortcode; // mpesa shortcode
        $shortcode->consumer_key = encrypt($request->consumer_key); // shortcode consumer key
        $shortcode->consumer_secret = encrypt($request->consumer_secret); // shortcode consumer secret
        /* Checking if the request has a pass_key and if it does, it encrypts it and saves it to the database. */
        if ($request->has('pass_key')) {
            $shortcode->pass_key = encrypt($request->pass_key); // not required for b2c
        }
        /* Checking if the request has an initiator name and if it does, it encrypts it and saves it to the
        database. */
        if ($request->has('initiator_name')) {
            $shortcode->initiator_name = encrypt($request->initiator_name);  // shortcode api initiator
        }
        /* Checking if the request has an initiator password and if it does, it encrypts it and saves it to the
        database. */
        if ($request->has('initiator_password')) {
            $shortcode->initiator_password = encrypt($request->initiator_password); // shortcode initiator password
        }
        $shortcode->save();

        return response()->json([
            'success' => true,
            'message' => 'Shortcode saved successfully!'
        ], 200);
    }
```

> You can use this SDK for either production or sandbox apps. For sandbox, the shortcode environment is **ALWAYS** `sandbox`

> Authorization is done by the SDK for both sandbox and production environments. You can use multiple shortcodes with different environments seamlessly.

### Content

[](#content)

- `stkPush($phonenumber, $amount, $reference = '', $description = '')`: Initiates an STK push transaction

    - `phonenumber`: The phone number sending money. `REQUIRED`
    - `amount`: This is the Amount to be transacted. Only whole numbers are supported. `REQUIRED`
    - `reference`: This is an Identifier of the transaction for CustomerPayBillOnline transaction type. `OPTIONAL`
    - `description`: This is any additional comment that can be sent along with the request. `OPTIONAL`
- `stkPushQuery($CheckoutRequestID)`: Returns the status of the transaction

    - `CheckoutRequestID`: The unique identifier of the processed checkout transaction request. `REQUIRED`
- `b2c($commandID, $amount, $phonenumber, $remarks)`: Sends money from your business to a customer

    - `commandID`: Unique command that specifies B2C transaction type \[SalaryPayment,BusinessPayment,PromotionPayment\]. `REQUIRED`
    - `phonenumber`: Customer mobile number to receive the amount. `REQUIRED`
    - `amount`: The amount of money being sent to the customer. Only whole numbers are supported. `REQUIRED`
    - `remarks`: Any additional information to be associated with the transaction. `REQUIRED`
- `transactionStatus($TransactionID)`: It returns the status of a transaction

    - `TransactionID`: Unique identifier to identify a transaction on Mpesa. `REQUIRED`
- `reverseTransaction($TransactionID, $amount)`: It reverses a transaction

    - `TransactionID`: Unique identifier to identify a transaction on Mpesa. `REQUIRED`

### Lipa na Mpesa Online

[](#lipa-na-mpesa-online)

```
use MainaDavid\MultiShortcodeMpesa\Mpesa;

// Mpesa shortcode
$shortcode = '12345';

// Phone numbers are transformed to the required format by the sdk so no worries about the formatting
$phonenumber = '0722123456';

// Instantiate the class
$mpesa  = new Mpesa($shortcode);

// Use stkpush service
$result = $mpesa->stkPush($phonenumber, $amount);

print_r($result);
```

### Check the status of a Lipa Na M-Pesa Online Payment

[](#check-the-status-of-a-lipa-na-m-pesa-online-payment)

```
use MainaDavid\MultiShortcodeMpesa\Mpesa;

// Mpesa shortcode
$shortcode = '12345';

$CheckoutRequestID = 'ws_CO_260520211133524545';

// Instantiate the class
$mpesa  = new Mpesa($shortcode);

$result = $mpesa->stkPushQuery($CheckoutRequestID);

print_r($result);
```

### Business to Customers (Pay Outs)

[](#business-to-customers-pay-outs)

```
use MainaDavid\MultiShortcodeMpesa\Mpesa;

// Mpesa shortcode
$shortcode = '12345';

$phonenumber = '0722123456';

// Instantiate the class
$mpesa  = new Mpesa($shortcode);

$result = $mpesa->b2c($commandID, $amount, $phonenumber, $remarks);

print_r($result);
```

### Check the status of a transaction

[](#check-the-status-of-a-transaction)

```
use MainaDavid\MultiShortcodeMpesa\Mpesa;

// Mpesa shortcode
$shortcode = '12345';

$TransactionID = 'QWERTY123456789';

// Instantiate the class
$mpesa  = new Mpesa($shortcode);

$result = $mpesa->transactionStatus($TransactionID);

print_r($result);
```

### Reverse a transaction

[](#reverse-a-transaction)

```
use MainaDavid\MultiShortcodeMpesa\Mpesa;

// Mpesa shortcode
$shortcode = '12345';

$TransactionID = 'QWERTY123456789';

// Instantiate the class
$mpesa  = new Mpesa($shortcode);

$result = $mpesa->reverseTransaction($TransactionID);

print_r($result);
```

### Example SDK responses

[](#example-sdk-responses)

The SDK will return a response with either success or error in the below format.

#### Success response

[](#success-response)

```
{
  "status": "success",
  "data": {
    "ConversationID": "AG_20230108_2010364679d05de418cd",
    "OriginatorConversationID": "12425-164354829-1",
    "ResponseCode": "0",
    "ResponseDescription": "Accept the service request successfully."
  }
}
```

#### Error response

[](#error-response)

```
{
  "status": "error",
  "data": "Shortcode does not support Business to Customer!"
}
```

###  Health Score

16

—

LowBetter than 5% of packages

Maintenance29

Infrequent updates — may be unmaintained

Popularity7

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity17

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/19209ddb9c7632e99060f83df45438c545e53e00771d8f8ab9e55cba15046c5b?d=identicon)[MainaDavid](/maintainers/MainaDavid)

---

Top Contributors

[![maina-david](https://avatars.githubusercontent.com/u/32592596?v=4)](https://github.com/maina-david "maina-david (52 commits)")

### Embed Badge

![Health badge](/badges/maina-david-multi-shortcode-mpesa/health.svg)

```
[![Health](https://phpackages.com/badges/maina-david-multi-shortcode-mpesa/health.svg)](https://phpackages.com/packages/maina-david-multi-shortcode-mpesa)
```

PHPackages © 2026

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