PHPackages                             apelimpesa/mpesa-php - 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. apelimpesa/mpesa-php

ActiveLibrary[API Development](/categories/api)

apelimpesa/mpesa-php
====================

A comprehensive PHP library for integrating with the M-Pesa API

v1.0.0(1y ago)223MITPHPPHP &gt;=7.4

Since May 5Pushed 1y ago1 watchersCompare

[ Source](https://github.com/ApeliDev/Mpesa-sdk)[ Packagist](https://packagist.org/packages/apelimpesa/mpesa-php)[ GitHub Sponsors](https://github.com/sponsors/ApeliDev)[ Patreon](https://www.patreon.com/ApeliDev)[ RSS](/packages/apelimpesa-mpesa-php/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (1)Dependencies (10)Versions (2)Used By (0)

M-Pesa PHP Library
==================

[](#m-pesa-php-library)

This library provides a simple and flexible way to integrate M-Pesa API services into your PHP application. It supports STK Push, C2B, B2C, transaction status queries, and reversals.

---

Features
--------

[](#features)

- **STK Push**: Initiate Lipa Na M-Pesa Online payments.
- **C2B**: Handle customer-to-business transactions.
- **B2C**: Process business-to-customer payments.
- **Transaction Status**: Query the status of transactions.
- **Reversal**: Reverse transactions.

---

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

[](#installation)

Install the library via Composer:

```
composer require apelimpesa/mpesa
```

---

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

[](#configuration)

### Step 1: Copy the Example Environment File

[](#step-1-copy-the-example-environment-file)

The library includes an `.env.example` file with all required configuration variables. Copy this file to your project root as `.env`:

```
cp vendor/apelimpesa/mpesa/.env.example .env
```

### Step 2: Configure Your Environment Variables

[](#step-2-configure-your-environment-variables)

Edit the `.env` file with your M-Pesa API credentials and settings:

```
# ==============================================
# M-PESA API CONFIGURATION
# ==============================================

# Application Environment (development/production)
APP_ENV=development

# M-Pesa API Credentials
MPESA_CONSUMER_KEY=your_consumer_key
MPESA_CONSUMER_SECRET=your_consumer_secret
MPESA_SHORTCODE=your_shortcode
MPESA_PASSKEY=your_passkey

# Security Credentials
MPESA_INITIATOR_NAME=your_initiator_name
MPESA_INITIATOR_PASSWORD=your_initiator_password
MPESA_CERTIFICATE_PATH=path/to/your/cert.pem

# ==============================================
# CALLBACK URLS
# ==============================================

# C2B URLs
MPESA_C2B_VALIDATION_URL=https://yourdomain.com/api/c2b/validate
MPESA_C2B_CONFIRMATION_URL=https://yourdomain.com/api/c2b/confirm

# B2C URLs
MPESA_B2C_RESULT_URL=https://yourdomain.com/api/b2c/result
MPESA_B2C_TIMEOUT_URL=https://yourdomain.com/api/b2c/timeout

# Transaction Status URLs
MPESA_TRANSACTION_STATUS_RESULT_URL=https://yourdomain.com/api/status/result
MPESA_TRANSACTION_STATUS_TIMEOUT_URL=https://yourdomain.com/api/status/timeout

# Reversal URLs
MPESA_REVERSAL_RESULT_URL=https://yourdomain.com/api/reversal/result
MPESA_REVERSAL_TIMEOUT_URL=https://yourdomain.com/api/reversal/timeout
```

### Step 3: Required Variables

[](#step-3-required-variables)

VariableDescriptionRequired For`APP_ENV`Application environment (`development`/`production`)All operations`MPESA_CONSUMER_KEY`Your M-Pesa API consumer keyAll operations`MPESA_CONSUMER_SECRET`Your M-Pesa API consumer secretAll operations`MPESA_SHORTCODE`Your business shortcodeAll operations`MPESA_PASSKEY`Your Lipa Na M-Pesa Online passkeySTK Push`MPESA_INITIATOR_NAME`B2C/B2B transaction initiator nameB2C/B2B`MPESA_INITIATOR_PASSWORD`Encrypted initiator passwordB2C/B2B`MPESA_CERTIFICATE_PATH`Path to your M-Pesa certificate (if required)Optional for security---

Usage
-----

[](#usage)

### Step 1: Load Environment Variables

[](#step-1-load-environment-variables)

Ensure your application loads the `.env` file. For non-Laravel projects, use `vlucas/phpdotenv`:

```
require_once __DIR__.'/vendor/autoload.php';

$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();
```

### Step 2: Initialize the Library

[](#step-2-initialize-the-library)

Create an instance of the M-Pesa service:

```
use ApeliMpesa\Mpesa\Mpesa;

$mpesa = new Mpesa([
    'consumer_key' => getenv('MPESA_CONSUMER_KEY'),
    'consumer_secret' => getenv('MPESA_CONSUMER_SECRET'),
    'shortcode' => getenv('MPESA_SHORTCODE'),
    'passkey' => getenv('MPESA_PASSKEY'),
    'environment' => getenv('APP_ENV'), // 'development' or 'production'
]);
```

### Step 3: Perform Transactions

[](#step-3-perform-transactions)

#### 1. STK Push (Lipa Na M-Pesa Online)

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

```
$response = $mpesa->stkPush([
    'amount' => 100,
    'phone' => '+254712345678',
    'reference' => 'Order123',
    'description' => 'Payment for Order123',
    'callback_url' => 'https://yourdomain.com/api/stk/callback',
]);

if ($response->isSuccessful()) {
    echo "STK Push initiated successfully. CheckoutRequestID: " . $response->getCheckoutRequestID();
} else {
    echo "Error: " . $response->getErrorMessage();
}
```

#### 2. Query Transaction Status

[](#2-query-transaction-status)

```
$response = $mpesa->queryTransactionStatus('CheckoutRequestID123');

if ($response->isSuccessful()) {
    echo "Transaction completed successfully.";
} else {
    echo "Error: " . $response->getErrorMessage();
}
```

#### 3. Reverse a Transaction

[](#3-reverse-a-transaction)

```
$response = $mpesa->reverseTransaction([
    'transaction_id' => 'TransactionID123',
    'amount' => 100,
    'receiver' => '600000',
    'receiver_type' => 'Paybill',
    'callback_url' => 'https://yourdomain.com/api/reversal/callback',
]);

if ($response->isSuccessful()) {
    echo "Transaction reversed successfully.";
} else {
    echo "Error: " . $response->getErrorMessage();
}
```

---

Testing with Sandbox
--------------------

[](#testing-with-sandbox)

When `APP_ENV=development`, the library uses M-Pesa's sandbox environment. No real money is transferred during testing.

For production, set:

```
APP_ENV=production
```

---

Security Notes
--------------

[](#security-notes)

- Use different credentials for development and production environments.
- Keep your `.env` file secure and avoid committing it to version control.

---

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

[](#requirements)

- PHP 7.4 or higher
- Composer
- cURL extension enabled

---

License
-------

[](#license)

This library is open-source and available under the [MIT License](LICENSE).

###  Health Score

27

—

LowBetter than 49% of packages

Maintenance49

Moderate activity, may be stable

Popularity8

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity37

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.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

378d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/405370fd60c95a7738b68f0a1fdd30417316c28adba8a28c78f57e0a71d7fa85?d=identicon)[apeli](/maintainers/apeli)

---

Top Contributors

[![ApeliDev](https://avatars.githubusercontent.com/u/146568151?v=4)](https://github.com/ApeliDev "ApeliDev (1 commits)")

---

Tags

b2cc2bmobile-moneympesampesa-apimpesa-sdkpayment-integrationreversalsafaricomstkpushapipaymentmpesamobile-moneykenyaafricasafaricom

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/apelimpesa-mpesa-php/health.svg)

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

###  Alternatives

[smodav/mpesa

M-Pesa API implementation

16363.7k1](/packages/smodav-mpesa)[checkout/checkout-sdk-php

Checkout.com SDK for PHP

553.3M7](/packages/checkout-checkout-sdk-php)[convertkit/convertkitapi

Kit PHP SDK for the Kit API

2167.1k1](/packages/convertkit-convertkitapi)[samerior/mobile-money

Mobile payments API - Kenya

252.3k](/packages/samerior-mobile-money)

PHPackages © 2026

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