PHPackages                             statum/safaricom-daraja-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. [HTTP &amp; Networking](/categories/http)
4. /
5. statum/safaricom-daraja-sdk

ActiveLibrary[HTTP &amp; Networking](/categories/http)

statum/safaricom-daraja-sdk
===========================

PHP 8.2+ Safaricom Daraja SDK for production payment, IoT SIM portal management, and GSM/network-level utility integrations across web and mobile apps.

v1.1.0(3d ago)00MITPHP ^8.2

Since Jul 7Compare

[ Source](https://github.com/StatumKE/safaricom-daraja-sdk)[ Packagist](https://packagist.org/packages/statum/safaricom-daraja-sdk)[ Docs](https://developer.safaricom.co.ke/apis)[ Fund](https://developer.safaricom.co.ke/)[ RSS](/packages/statum-safaricom-daraja-sdk/feed)WikiDiscussions Synced today

READMEChangelog (2)Dependencies (7)Versions (3)Used By (0)

PHP Safaricom Daraja SDK (M-Pesa Payments &amp; Network Utilities)
==================================================================

[](#php-safaricom-daraja-sdk-m-pesa-payments--network-utilities)

[![PHP Version](https://camo.githubusercontent.com/962aced9b09d89716dbebf186ff899754a096ff1068b6b7988675c2d9fab9331/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253545382e322d626c75652e737667)](https://packagist.org/packages/statum/safaricom-daraja-sdk)[![Latest Stable Version](https://camo.githubusercontent.com/c3be291606fa674765932529e7529b97597adb0135ed321af7853710612b58eb/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f73746174756d2f736166617269636f6d2d646172616a612d73646b2e737667)](https://packagist.org/packages/statum/safaricom-daraja-sdk)[![License](https://camo.githubusercontent.com/75c5996fb4dc92c517d4027fc66df1b61eaf2a9601d8fb6ca51fe66568f74ef7/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f53746174756d4b452f736166617269636f6d2d646172616a612d73646b2e737667)](https://github.com/StatumKE/safaricom-daraja-sdk/blob/master/LICENSE)

A modern, type-safe PHP 8.2+ SDK for Safaricom Daraja integration. It provides framework-agnostic core libraries with typed request/response DTOs, Guzzle 7 transport, and clean Laravel service bindings for M-Pesa payments, B2B/B2C payouts, KYC lookup, Standing Orders, and SIM portal operations.

---

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

[](#table-of-contents)

- [Features](#features)
- [Getting Started](#getting-started)
- [Installation](#installation)
- [Quick Start in 2 Minutes](#quick-start-in-2-minutes)
    - [1. Plain PHP Setup](#1-plain-php-setup)
    - [2. Laravel Setup](#2-laravel-setup)
- [Core Integration Examples](#core-integration-examples)
    - [STK Push (M-Pesa Express)](#stk-push-m-pesa-express)
    - [C2B Simulation (Paybill vs. Till)](#c2b-simulation-paybill-vs-till)
    - [B2B Hakikisha (Verify Org)](#b2b-hakikisha-verify-org)
    - [Mobile Number Validation (KYC)](#mobile-number-validation-kyc)
- [Error &amp; Exception Handling](#error--exception-handling)
- [Documentation Directory](#documentation-directory)
- [Sandbox Environment Gotchas](#sandbox-environment-gotchas)
- [Running Tests](#running-tests)
- [License](#license)

---

Features
--------

[](#features)

- **Framework-Agnostic Core**: Can be used in raw PHP scripts, Wordpress, Symfony, or Laravel.
- **Type-Safe Request DTOs**: Strict constructors validate your payloads before making outgoing HTTP requests.
- **Automatic OAuth Lifecycle**: Token fetching, caching, and token refresh are handled invisibly under the hood.
- **Full Laravel Binding**: Auto-discovered ServiceProvider binds `SafaricomClient` singleton with optional config publishing.
- **Comprehensive API Coverage**: Payments (STK, C2B, B2B, B2C, Reversals), standing orders, SIM query, and KYC lookups.

---

Getting Started
---------------

[](#getting-started)

1. **Sign up for a Safaricom Developer Account**: Visit the [Safaricom Developer Portal](https://developer.safaricom.co.ke/) and register a developer profile.
2. **Create a Developer Application**:
    - Navigate to the **My Apps** section from your developer dashboard.
    - Click **Create New App**.
    - Set an application name and select the API products you want to access (e.g., *M-Pesa Sandbox API*).
    - Once created, copy the generated **Consumer Key** and **Consumer Secret** credentials.
3. **Configure the SDK**: Follow the [Installation](#installation) and configuration guidelines below.

---

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

[](#installation)

Install the package via Composer:

```
composer require statum/safaricom-daraja-sdk
```

---

Quick Start in 2 Minutes
------------------------

[](#quick-start-in-2-minutes)

Ensure your Safaricom credentials are saved in your `.env` or system environment:

```
SAFARICOM_CONSUMER_KEY=your-consumer-key
SAFARICOM_CONSUMER_SECRET=your-consumer-secret
SAFARICOM_ENVIRONMENT=sandbox # sandbox or production
```

### 1. Plain PHP Setup

[](#1-plain-php-setup)

```
use Statum\Safaricom\Daraja\Client\SafaricomClient;
use Statum\Safaricom\Daraja\Config\SafaricomConfig;
use Statum\Safaricom\Daraja\Environment\Environment;

$config = new SafaricomConfig(
    consumerKey: $_ENV['SAFARICOM_CONSUMER_KEY'],
    consumerSecret: $_ENV['SAFARICOM_CONSUMER_SECRET'],
    environment: $_ENV['SAFARICOM_ENVIRONMENT'] === 'production'
        ? Environment::Production
        : Environment::Sandbox
);

$client = SafaricomClient::create($config);
```

### 2. Laravel Setup

[](#2-laravel-setup)

Publish the package configuration:

```
php artisan vendor:publish --tag=safaricom-daraja-config
```

The config matches your `.env` keys automatically. Now simply inject `SafaricomClient` into your controller, action, or command:

```
use Statum\Safaricom\Daraja\Client\SafaricomClient;

class PaymentController extends Controller
{
    public function __construct(private readonly SafaricomClient $client) {}

    public function pay() {
        // Ready to make type-safe calls!
    }
}
```

---

Core Integration Examples
-------------------------

[](#core-integration-examples)

### STK Push (M-Pesa Express)

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

Initiate an interactive popup on a customer's phone to request payment:

```
use Statum\Safaricom\Daraja\Dto\Request\StkPushRequest;
use Statum\Safaricom\Daraja\Support\MpesaPasswordGenerator;

// Generate transaction password using shortcode, passkey, and current timestamp
$timestamp = (new DateTimeImmutable('now', new DateTimeZone('Africa/Nairobi')))->format('YmdHis');
$password = MpesaPasswordGenerator::generate('174379', 'your-passkey', new DateTimeImmutable($timestamp));

$request = new StkPushRequest(
    businessShortCode: '174379',
    password: $password,
    timestamp: $timestamp,
    transactionType: 'CustomerPayBillOnline',
    amount: 10,
    partyA: '2547XXXXXXXX', // Customer phone number
    partyB: '174379',       // Same as BusinessShortCode
    phoneNumber: '2547XXXXXXXX',
    callBackURL: 'https://your-domain.com/callbacks/stk',
    accountReference: 'Invoice-1234',
    transactionDesc: 'Payment for goods'
);

$response = $client->stkPush($request);
print_r($response->json());
```

### C2B Simulation (Paybill vs. Till)

[](#c2b-simulation-paybill-vs-till)

```
use Statum\Safaricom\Daraja\Dto\Request\C2bSimulateRequest;

// 1. Simulating C2B Paybill payment
$paybillRequest = new C2bSimulateRequest(
    shortCode: '600984',
    commandID: 'CustomerPayBillOnline',
    amount: 1,
    msisdn: '2547XXXXXXXX',
    billRefNumber: 'INV-9988' // Required string reference for Paybill
);
$response = $client->c2bSimulate($paybillRequest);

// 2. Simulating C2B Till payment (CustomerBuyGoodsOnline)
$tillRequest = new C2bSimulateRequest(
    shortCode: '600984',
    commandID: 'CustomerBuyGoodsOnline',
    amount: 1,
    msisdn: '2547XXXXXXXX',
    billRefNumber: null // IMPORTANT: Must be null for Till simulations
);
$response = $client->c2bSimulate($tillRequest);
```

### B2B Hakikisha (Verify Org)

[](#b2b-hakikisha-verify-org)

Verify organization shortcode ownership before transferring funds:

```
use Statum\Safaricom\Daraja\Dto\Request\B2bHakikishaRequest;

$request = new B2bHakikishaRequest(
    identifierType: '4', // IMPORTANT: Use string '4' for Shortcode, '1' for MSISDN
    identifier: '600984'
);
$response = $client->b2bHakikisha($request);
print_r($response->json());
```

### Mobile Number Validation (KYC)

[](#mobile-number-validation-kyc)

Verify whether a mobile number matches a specific National ID:

```
use Statum\Safaricom\Daraja\Dto\Request\MobileNumberValidationRequest;

$request = new MobileNumberValidationRequest(
    requestRefID: 'req-' . uniqid(),
    shortCode: '600984',
    msisdn: '2547XXXXXXXX',
    idType: '01', // IMPORTANT: Use '01' for National ID, '02' for Military ID, '05' for Passport
    idNumber: '12345678'
);
$response = $client->mobileNumberValidation($request);
print_r($response->json());
```

---

Error &amp; Exception Handling
------------------------------

[](#error--exception-handling)

The SDK exposes distinct exceptions you should catch in your application logic:

```
use Statum\Safaricom\Daraja\Exception\ApiException;
use Statum\Safaricom\Daraja\Exception\ConfigurationException;
use Statum\Safaricom\Daraja\Exception\TransportException;

try {
    $response = $client->stkPush($request);
} catch (ConfigurationException $e) {
    // Local configuration error or validation checks failed
    echo "Config/Data Error: " . $e->getMessage();
} catch (TransportException $e) {
    // Network-level transport / DNS failure
    echo "Network Connection Failed: " . $e->getMessage();
} catch (ApiException $e) {
    // Safaricom API returned HTTP errors (4xx/5xx)
    $apiResponse = $e->response();
    echo "API HTTP " . $apiResponse->statusCode() . ": " . $apiResponse->body();
}
```

---

Documentation Directory
-----------------------

[](#documentation-directory)

For deep integration guidance, use the provided documentation guides:

- [docs/endpoint-guide.md](docs/endpoint-guide.md) - The primary mapping of DTO constructor properties and parameters.
- [docs/examples.md](docs/examples.md) - Contains expanded setup walkthroughs and copy-paste integration blocks.
- [docs/api-reference.md](docs/api-reference.md) - Key structural specifications and DTO serialization properties.

---

Sandbox Environment Gotchas
---------------------------

[](#sandbox-environment-gotchas)

When testing against Safaricom's Sandbox environment, pay attention to these limitations:

1. **Forbidden Words in URLs**: When calling `c2bRegisterUrl()`, your `confirmationURL` and `validationURL` **cannot** contain the word `"mpesa"` (case-insensitive). If included, Sandbox returns an HTTP 400 Bad Request error.
2. **Till Simulation limitations**: Not all sandbox apps support `CustomerBuyGoodsOnline` simulations. When simulating, ensure your `billRefNumber` is set to `null` to prevent validation mapper errors.
3. **Network &amp; IMSI lookups**: Sandbox lookups are not mapped to live network carriers and typically return `410 Backend System Unavailable` or `404 Not Found`.

---

Running Tests
-------------

[](#running-tests)

Verify local SDK behaviors by executing PHPUnit tests:

```
composer install
composer test
```

---

License
-------

[](#license)

This project is licensed under the MIT License. See [LICENSE](LICENSE) for details.

###  Health Score

39

—

LowBetter than 84% of packages

Maintenance99

Actively maintained with recent releases

Popularity0

Limited adoption so far

Community2

Small or concentrated contributor base

Maturity47

Maturing project, gaining track record

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

Total

2

Last Release

3d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/931a6f10226e9d76e5c3c90b76f680f4b1cd1f648e5e2f8c464c4fdf205f3f6b?d=identicon)[sirBobz](/maintainers/sirBobz)

---

Tags

laravelsdkGuzzlepaymentsmpesasafaricomdaraja

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/statum-safaricom-daraja-sdk/health.svg)

```
[![Health](https://phpackages.com/badges/statum-safaricom-daraja-sdk/health.svg)](https://phpackages.com/packages/statum-safaricom-daraja-sdk)
```

###  Alternatives

[aws/aws-sdk-php

AWS SDK for PHP - Use Amazon Web Services in your PHP project

6.3k543.5M2.7k](/packages/aws-aws-sdk-php)[eslazarev/wildberries-sdk

Wildberries OpenAPI clients (generated).

293.1k](/packages/eslazarev-wildberries-sdk)

PHPackages © 2026

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