PHPackages                             codexoft/mpesa-sdk - 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. codexoft/mpesa-sdk

ActiveLibrary[Payment Processing](/categories/payments)

codexoft/mpesa-sdk
==================

A PHP SDK for seamless integration with M-Pesa payment gateway, providing easy-to-use methods for transactions and payment processing

v1.0.2(1y ago)38[1 issues](https://github.com/codexoft-ke/mpesa-sdk/issues)MITPHPCI failing

Since Dec 30Pushed 1y ago1 watchersCompare

[ Source](https://github.com/codexoft-ke/mpesa-sdk)[ Packagist](https://packagist.org/packages/codexoft/mpesa-sdk)[ RSS](/packages/codexoft-mpesa-sdk/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependenciesVersions (4)Used By (0)

M-Pesa PHP SDK
==============

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

A comprehensive PHP SDK for integrating with Safaricom's M-Pesa payment services. This package provides a simple and elegant way to interact with various M-Pesa APIs, including STK Push, B2B, B2C, C2B, QR Code generation, tax remittance, and more.

Table of Contents
-----------------

[](#table-of-contents)

- [Features](#features)
- [Installation](#installation)
- [Configuration](#configuration)
- [Available Methods](#available-methods)
    - [STK Push](#stk-push)
    - [STK Push Query](#stk-push-query)
    - [QR Code Generation](#qr-code-generation)
    - [C2B URL Registration](#c2b-url-registration)
    - [B2C Payments](#b2c-payments)
    - [B2B Payments](#b2b-payments)
    - [B2B Express Checkout](#b2b-express-checkout)
    - [Transaction Status](#transaction-status)
    - [Account Balance](#account-balance)
    - [Transaction Reversal](#transaction-reversal)
    - [Tax Remittance](#tax-remittance)
    - [Standing Orders (M-Pesa Ratiba)](#standing-orders-m-pesa-ratiba)
- [Error Handling](#error-handling)
- [Webhook Integration](#webhook-integration)
- [Advanced Usage](#advanced-usage)
- [Requirements](#requirements)
- [Security Best Practices](#security-best-practices)
- [Testing](#testing)
- [Contributing](#contributing)
- [License](#license)
- [Support](#support)
- [Credits](#credits)
- [Changelog](#changelog)

Features
--------

[](#features)

- Complete M-Pesa API integration
- Environment support for both sandbox and production
- Automatic access token management
- Built-in phone number formatting
- Comprehensive error handling and validation
- Webhook handling support
- Certificate management for security credentials
- Support for all M-Pesa transaction types:
    - Customer-to-Business (C2B)
    - Business-to-Customer (B2C)
    - Business-to-Business (B2B)
    - STK Push (M-Pesa Express)
    - QR Code Payments
    - Tax Remittance
    - Standing Orders

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

[](#installation)

Install the package via Composer:

```
composer require codexoft/mpesa-sdk
```

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

[](#configuration)

### Basic Configuration

[](#basic-configuration)

```
use codexoft\MpesaSdk\Mpesa;

$config = [
    'env' => 'sandbox', // or 'production'
    'credentials' => [
        'passKey' => 'your-pass-key',
        'initiatorPass' => 'your-initiator-pass',
        'initiatorName' => 'your-initiator-name'
    ],
    'appInfo' => [
        'consumerKey' => 'your-consumer-key',
        'consumerSecret' => 'your-consumer-secret'
    ],
    'businessShortCode' => 'your-shortcode',
    'shortCodeType' => 'paybill', // or 'till'
    'requester' => 'your-requester-id'
];
```

### Using Environment Variables (Recommended)

[](#using-environment-variables-recommended)

Create a .env file:

```
MPESA_ENV=sandbox
MPESA_PASS_KEY=your-pass-key
MPESA_INITIATOR_PASS=your-initiator-pass
MPESA_INITIATOR_NAME=your-initiator-name
MPESA_CONSUMER_KEY=your-consumer-key
MPESA_CONSUMER_SECRET=your-consumer-secret
MPESA_BUSINESS_SHORTCODE=your-shortcode
MPESA_SHORTCODE_TYPE=paybill
MPESA_REQUESTER=your-requester-id
```

Load configuration from environment:

```
$config = [
    'env' => $_ENV['MPESA_ENV'],
    'credentials' => [
        'passKey' => $_ENV['MPESA_PASS_KEY'],
        'initiatorPass' => $_ENV['MPESA_INITIATOR_PASS'],
        'initiatorName' => $_ENV['MPESA_INITIATOR_NAME']
    ],
    'appInfo' => [
        'consumerKey' => $_ENV['MPESA_CONSUMER_KEY'],
        'consumerSecret' => $_ENV['MPESA_CONSUMER_SECRET']
    ],
    'businessShortCode' => $_ENV['MPESA_BUSINESS_SHORTCODE'],
    'shortCodeType' => $_ENV['MPESA_SHORTCODE_TYPE'],
    'requester' => $_ENV['MPESA_REQUESTER']
];
```

Basic Usage
-----------

[](#basic-usage)

Initialize the SDK:

```
try {
    $mpesa = new Mpesa($config);
} catch (InvalidArgumentException $e) {
    // Handle configuration errors
    log_error("Configuration Error: " . $e->getMessage());
} catch (Exception $e) {
    // Handle other initialization errors
    log_error("Initialization Error: " . $e->getMessage());
}
```

Available Methods
-----------------

[](#available-methods)

### STK Push

[](#stk-push)

Initiate an STK push request (M-Pesa Express):

```
try {
    $response = $mpesa->stkPush(
        amount: 100,
        phoneNumber: '254712345678',
        accountNumber: 'INV001',
        callBackUrl: 'https://example.com/callback',
        description: 'Payment for Invoice 001'
    );

    print_r($response);
} catch (Exception $e) {
    echo $e->getMessage();
}
```

### STK Push Query

[](#stk-push-query)

Check the status of an STK push request:

```
try {
    $response = $mpesa->stkPushQuery(
        checkoutRequestCode: 'ws_CO_123456789'
    );

    print_r($response);
} catch (Exception $e) {
    echo $e->getMessage();
}
```

### QR Code Generation

[](#qr-code-generation)

Generate a dynamic QR code for payments:

```
try {
    $response = $mpesa->generateQRCode(
        amount: 100,
        accountNumber: 'INV001',
        size: 300 // Size in pixels
    );

    print_r($response);
} catch (Exception $e) {
    echo $e->getMessage();
}
```

### C2B URL Registration

[](#c2b-url-registration)

Register URLs for C2B payment notifications:

```
try {
    $response = $mpesa->registerUrl(
        responseType: 'Completed|Cancelled',
        confirmationUrl: 'https://example.com/confirmation',
        validationUrl: 'https://example.com/validation'
    );

    print_r($response);
} catch (Exception $e) {
    echo $e->getMessage();
}
```

### B2C Payments

[](#b2c-payments)

Send money to customers (Business to Customer):

```
try {
    $response = $mpesa->initiateB2C(
        amount: 100,
        phoneNumber: '254712345678',
        commandID: 'BusinessPayment|SalaryPayment|PromotionPayment', // or 'SalaryPayment', 'PromotionPayment'
        resultUrl: 'https://example.com/b2c-result',
        queueTimeoutUrl: 'https://example.com/b2c-timeout',
        remarks: 'Salary Payment'
    );

    print_r($response);
} catch (Exception $e) {
    echo $e->getMessage();
}
```

### B2B Payments

[](#b2b-payments)

Make payments to other businesses:

```
try {
    $response = $mpesa->initiateB2B(
        amount: 1000,
        paymentType: 'PaybillToPaybill|PaybillToTill|B2BAccountTopUp', // or 'PaybillToTill', 'B2BAccountTopUp'
        shortCode: '600000',
        accountNumber: 'ACC001',
        resultUrl: 'https://example.com/b2b-result',
        queueTimeoutUrl: 'https://example.com/b2b-timeout'
    );

    print_r($response);
} catch (Exception $e) {
    echo $e->getMessage();
}
```

### B2B Express Checkout

[](#b2b-express-checkout)

Initiate a B2B Express Checkout (USSD Push):

```
try {
    $response = $mpesa->initiateB2BExpressCheckout(
        amount: 1000,
        receiverShortCode: '600000',
        callBackUrl: 'https://example.com/express-callback',
        partnerName: 'Vendor Name',
        paymentRef: 'PAY123', // optional
        requestRef: 'REQ123'  // optional
    );

    print_r($response);
} catch (Exception $e) {
    echo $e->getMessage();
}
```

### Transaction Status

[](#transaction-status)

Query the status of any transaction:

```
try {
    $response = $mpesa->transactionStatus(
        transactionID: 'SLU000000',
        resultUrl: 'https://example.com/status-result',
        queueTimeoutUrl: 'https://example.com/status-timeout'
    );

    print_r($response);
} catch (Exception $e) {
    echo $e->getMessage();
}
```

### Account Balance

[](#account-balance)

Check your business account balance:

```
try {
    $response = $mpesa->accountBalance(
        resultUrl: 'https://example.com/balance-result',
        queueTimeoutUrl: 'https://example.com/balance-timeout'
    );

    print_r($response);
} catch (Exception $e) {
    echo $e->getMessage();
}
```

### Transaction Reversal

[](#transaction-reversal)

Reverse a completed transaction:

```
try {
    $response = $mpesa->reverseTransaction(
        amount: 100,
        transactionID: 'SLU000000',
        resultUrl: 'https://example.com/reversal-result',
        queueTimeoutUrl: 'https://example.com/reversal-timeout'
    );

    print_r($response);
} catch (Exception $e) {
    echo $e->getMessage();
}
```

### Tax Remittance

[](#tax-remittance)

Process tax payments to KRA:

```
try {
    $response = $mpesa->taxRemittance(
        amount: 1000,
        paymentRegistrationNo: 'PRN12345',
        resultUrl: 'https://example.com/tax-result',
        queueTimeoutUrl: 'https://example.com/tax-timeout'
    );

    print_r($response);
} catch (Exception $e) {
    echo $e->getMessage();
}
```

### Standing Orders (M-Pesa Ratiba)

[](#standing-orders-m-pesa-ratiba)

Create recurring payment orders:

```
try {
    $response = $mpesa->mpesaRatiba(
        amount: 1000,
        phoneNumber: '254712345678',
        accountReference: 'ACC001',
        startDate: '2024-01-01',
        endDate: '2024-12-31',
        standingOrderName: 'Monthly Subscription',
        callBackUrl: 'https://example.com/ratiba-callback',
        frequency: '4' // Monthly
    );

    print_r($response);
} catch (Exception $e) {
    echo $e->getMessage();
}
```

Frequency options:

- 1: One Off
- 2: Daily
- 3: Weekly
- 4: Monthly
- 5: Bi-Monthly
- 6: Quarterly
- 7: Half Year
- 8: Yearly

Error Handling
--------------

[](#error-handling)

The SDK implements comprehensive error handling:

```
try {
    // M-Pesa API call
} catch (InvalidArgumentException $e) {
    // Handle validation errors
    error_log("Validation error: " . $e->getMessage());
} catch (Exception $e) {
    // Handle API errors
    error_log("API error: " . $e->getMessage());

    // Get HTTP status code if available
    if (property_exists($e, 'httpCode')) {
        error_log("HTTP Status: " . $e->httpCode);
    }
}
```

Webhook Integration
-------------------

[](#webhook-integration)

Example webhook handler for callbacks:

```
