PHPackages                             josemodi97/yii2-safaricom-daraja - 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. josemodi97/yii2-safaricom-daraja

ActiveYii2-extension

josemodi97/yii2-safaricom-daraja
================================

Yii2 component for Safaricom Daraja, M-Pesa, Ratiba, B2B, B2C, C2B, STK Push, Pull Transactions, Lipa na Bonga, IMSI/SWAP, and IoT SIM portal API requests.

v1.0.7(1mo ago)05↓75%MITPHPPHP &gt;=5.4

Since Jul 16Pushed 1mo agoCompare

[ Source](https://github.com/JoseModi97/yii2-safaricom-daraja)[ Packagist](https://packagist.org/packages/josemodi97/yii2-safaricom-daraja)[ Docs](https://github.com/JoseModi97/yii2-safaricom-daraja)[ RSS](/packages/josemodi97-yii2-safaricom-daraja/feed)WikiDiscussions main Synced 1w ago

READMEChangelogDependencies (8)Versions (9)Used By (0)

Yii2 Safaricom Daraja Extension
===============================

[](#yii2-safaricom-daraja-extension)

Yii2 Composer extension generated from `Safaricom APIs Copy.postman_collection.json`.

This package wraps the Safaricom Daraja and related sandbox APIs in a Yii2 component so you can call them from normal Yii2 MVC code: models/forms validate user input, controllers call `Yii::$app->daraja`, and callback actions receive Safaricom asynchronous responses.

The code supports PHP `>=5.4` through current PHP versions supported by Yii2. It avoids PHP 7+ syntax, scalar type declarations, return types, nullable types, short arrays, and other syntax that breaks older Yii2 projects. HTTP transport is handled by `yiisoft/yii2-httpclient`.

Example Application
-------------------

[](#example-application)

[JoseModi97/use-daraja](https://github.com/JoseModi97/use-daraja) is a Yii2 advanced template application repository that uses this extension and demonstrates all of its supported values and configuration options.

For Yii2 basic template applications, use the same extension configuration in `config/web.php` from the application root.

Compatibility
-------------

[](#compatibility)

- PHP `5.4+`
- Yii2 `2.0.6+`
- PHPUnit `4.8+` through `9.x` for the included tests
- Composer package name: `josemodi97/yii2-safaricom-daraja`

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

[](#installation)

All paths in this guide are relative to the root of the Yii2 application that will use this package. For a basic Yii2 app, that is the folder that contains `composer.json`, `config/`, `controllers/`, `models/`, and `views/`.

After publishing to Packagist:

```
composer require josemodi97/yii2-safaricom-daraja
```

If the package is kept in a local folder, edit the consuming Yii2 app's `composer.json`:

Path from Yii2 app root: `composer.json`

```
{
  "repositories": [
    {
      "type": "path",
      "url": "../yii2-safaricom-daraja"
    }
  ],
  "require": {
    "josemodi97/yii2-safaricom-daraja": "*"
  }
}
```

Then run:

```
composer update josemodi97/yii2-safaricom-daraja
```

Yii2 Configuration
------------------

[](#yii2-configuration)

Add the component to the Yii2 application config.

### Basic Yii2 Template

[](#basic-yii2-template)

Add the component in the basic application config:

- App config: `config/web.php`

### Advanced Yii2 Template

[](#advanced-yii2-template)

Add the component in each application config that needs Daraja access:

- Frontend: `frontend/config/main.php`
- Backend: `backend/config/main.php`
- Console: `console/config/main.php`

```
'components' => [
    'daraja' => [
        'class' => 'Safaricom\\Daraja\\Daraja',
        'environment' => 'sandbox',
        'consumerKey' => getenv('DARAJA_CONSUMER_KEY'),
        'consumerSecret' => getenv('DARAJA_CONSUMER_SECRET'),
        'callbackBaseUrl' => getenv('DARAJA_CALLBACK_BASE_URL') ?: null,
    ],
],
```

Use `environment => 'production'` for `https://api.safaricom.co.ke`.

`callbackBaseUrl` is optional in normal web requests. If it is not set, the component tries to derive the base URL from the current Yii request, for example `https://housing.example.com`. Set it explicitly for console jobs, queue workers, reverse-proxy deployments, or local development through a public tunnel.

Recommended app params can go in the same config file, or in your Yii params file.

Common paths from Yii2 app root:

- Basic app config: `config/web.php`
- Basic app params: `config/params.php`
- Advanced app common params: `common/config/params.php`

```
'params' => [
    'daraja.shortCode' => getenv('DARAJA_SHORT_CODE'),
    'daraja.passkey' => getenv('DARAJA_PASSKEY'),
    'daraja.initiatorName' => getenv('DARAJA_INITIATOR_NAME'),
    'daraja.initiatorPassword' => getenv('DARAJA_INITIATOR_PASSWORD'),
    'daraja.certificatePath' => '@app/certs/SafaricomSandboxCertificate.cer',
],
```

Environment Variables
---------------------

[](#environment-variables)

Create a `.env` file in the Yii2 application root if your app uses dotenv-style environment loading.

Path from Yii2 basic app root: `.env`

Path from Yii2 advanced project root: `.env`

```
DARAJA_ENVIRONMENT=sandbox
DARAJA_CONSUMER_KEY=your_consumer_key
DARAJA_CONSUMER_SECRET=your_consumer_secret
DARAJA_SHORT_CODE=174379
DARAJA_PASSKEY=your_lipa_na_mpesa_passkey
DARAJA_INITIATOR_NAME=your_initiator_name
DARAJA_INITIATOR_PASSWORD=your_initiator_password
DARAJA_CALLBACK_BASE_URL=https://your-domain.example
DARAJA_IOT_API_KEY=your_iot_api_key
DARAJA_IOT_MSISDN=254700000000
```

Yii2 does not load `.env` files by default in every template. If your application already loads `.env`, `getenv('DARAJA_CONSUMER_KEY')` will work as shown above. If it does not, install and bootstrap a dotenv loader in the Yii2 application, or set these variables in your server environment.

If you choose the dotenv approach, install the loader in the Yii2 application:

```
composer require vlucas/phpdotenv
```

Example using `vlucas/phpdotenv` in a Yii2 basic app:

Path from Yii2 app root: `web/index.php`

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

if (class_exists('Dotenv\\Dotenv')) {
    $dotenv = Dotenv\Dotenv::createImmutable(dirname(__DIR__));
    $dotenv->safeLoad();
}

require __DIR__ . '/../vendor/yiisoft/yii2/Yii.php';
```

Example using `vlucas/phpdotenv` in a Yii2 advanced app:

Common entry files from project root:

- Frontend: `frontend/web/index.php`
- Backend: `backend/web/index.php`
- Console: `yii`

Load `.env` before requiring `common/config/bootstrap.php` or before reading config files:

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

if (class_exists('Dotenv\\Dotenv')) {
    $dotenv = Dotenv\Dotenv::createImmutable(dirname(__DIR__, 2));
    $dotenv->safeLoad();
}
```

Do not hard-code real consumer keys, secrets, passkeys, initiator passwords, or API keys in code. The Postman collection may contain sample values; move all secrets to environment variables.

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

[](#basic-usage)

Place these calls inside your own controller action, service class, console command, or model method. The MVC example below uses these paths:

- Form model: `models/StkPushForm.php`
- Controller: `controllers/DarajaController.php`
- Optional payment view: `views/daraja/stk-push.php`

Generate an OAuth access token:

```
$tokenResponse = Yii::$app->daraja->generateAccessToken();
$accessToken = $tokenResponse['access_token'];
```

Most API calls do not need you to pass the token manually. The component automatically generates and refreshes the bearer token when `consumerKey` and `consumerSecret` are configured.

Use named helper methods where available:

```
$response = Yii::$app->daraja->stkPush($payload);
$response = Yii::$app->daraja->c2bRegisterUrl($payload);
$response = Yii::$app->daraja->accountBalance($payload);
```

Use the generic endpoint catalog for any endpoint:

```
use Safaricom\Daraja\EndpointCatalog;

$response = Yii::$app->daraja->request(EndpointCatalog::PULL_QUERY, [
    'ShortCode' => Yii::$app->params['daraja.shortCode'],
    'StartDate' => '2026-07-01 00:00:00',
    'EndDate' => '2026-07-16 23:59:59',
    'OffSetValue' => '0',
]);
```

Yii2 MVC Pattern
----------------

[](#yii2-mvc-pattern)

A clean Yii2 integration usually looks like this:

- Model or form: validates phone numbers, amount, account reference, date ranges, and required business fields.
- Controller: receives the user request, builds the Daraja payload, calls the component, and returns a Yii response.
- Callback controller action: receives Safaricom result/confirmation/validation callbacks and stores them.
- Service or ActiveRecord layer: saves payment requests, checkout request IDs, transaction IDs, and callback result codes.

Example Model: STK Push Form
----------------------------

[](#example-model-stk-push-form)

Create the form model.

Path from Yii2 app root: `models/StkPushForm.php`

```
