Download the PHP package josemodi97/yii2-safaricom-daraja without Composer

On this page you can find all versions of the php package josemodi97/yii2-safaricom-daraja. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package yii2-safaricom-daraja

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

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

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:

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

Path from Yii2 app root: composer.json

Then run:

Yii2 Configuration

Add the component to the Yii2 application config.

Basic Yii2 Template

Add the component in the basic application config:

Advanced Yii2 Template

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

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:

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

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:

Example using vlucas/phpdotenv in a Yii2 basic app:

Path from Yii2 app root: web/index.php

Example using vlucas/phpdotenv in a Yii2 advanced app:

Common entry files from project root:

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

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

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

Generate an OAuth 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:

Use the generic endpoint catalog for any endpoint:

Yii2 MVC Pattern

A clean Yii2 integration usually looks like this:

Example Model: STK Push Form

Create the form model.

Path from Yii2 app root: models/StkPushForm.php

Example Controller

Create the controller.

Path from Yii2 app root: controllers/DarajaController.php

STK Push and Query

Start a Lipa na M-Pesa Online payment:

Query an STK payment using the CheckoutRequestID returned by Safaricom:

C2B URL Registration and Simulation

Put the registration/simulation calls in a controller action, console command, or service class. For example:

Register confirmation and validation URLs:

Sandbox C2B simulation:

Callback examples can be added as methods inside the same web controller.

Path from Yii2 app root: controllers/DarajaController.php

B2C, B2B, and B2Pochi

Put these payout/request examples in your own service class, console command, or controller action.

Suggested paths from Yii2 app root:

Generate a security credential from your initiator password and Safaricom public certificate:

B2C payment request:

B2B payment request:

B2Pochi payment request:

Reversal, Transaction Status, and Account Balance

Put these examples in your own service class, console command, or controller action.

Suggested paths from Yii2 app root:

Reverse a transaction:

Query transaction status:

Query account balance:

M-Pesa Ratiba Standing Orders

Put these examples in your own service class, console command, or controller action.

Suggested paths from Yii2 app root:

Create a standing order for Paybill:

Create a standing order for Buy Goods:

Lipa na Bonga

Put these examples in your own service class, console command, or controller action.

Suggested paths from Yii2 app root:

Redeem Bonga points to Paybill:

Calculate points:

IMSI and SWAP CheckATI

Put this example in your own service class, console command, or controller action.

Suggested paths from Yii2 app root:

Pull Transactions API

Put these examples in your own service class, console command, or controller action.

Suggested paths from Yii2 app root:

Register a callback URL:

Query transactions:

IoT SIM Portal APIs

Put these examples in your own service class, console command, or controller action.

Suggested paths from Yii2 app root:

The IoT SIM portal endpoints from the collection use the same request() engine, but they commonly need additional headers such as x-api-key, x-source-system, X-MSISDN, X-App, and X-MessageID. Use Daraja::iot($endpointKey, $data, $headers, $query).

The package also exposes named IoT helpers such as iotSearchMessages(), iotSendSingleMessage(), iotAllSims(), and iotSuspendUnsuspendSub(). These helpers call the same endpoints as iot() and accept the same payload/header/query style where paging is needed.

Search messages:

Send one message:

SIM activation:

All Tools and Endpoints from the Collection

Import the constant class where you need generic access:

Tool / API from Postman Helper method Endpoint constant
OAuth access token generateAccessToken() EndpointCatalog::OAUTH_TOKEN
M-Pesa Ratiba Paybill standing order ratibaCreatePaybill($data) EndpointCatalog::RATIBA_CREATE_PAYBILL
M-Pesa Ratiba Buy Goods standing order ratibaCreateBuyGoods($data) EndpointCatalog::RATIBA_CREATE_BUY_GOODS
B2B payment request b2bPayment($data) EndpointCatalog::B2B_PAYMENT
B2C payment request b2cPayment($data) EndpointCatalog::B2C_PAYMENT
B2Pochi payment request b2PochiPayment($data) EndpointCatalog::B2POCHI_PAYMENT
C2B URL registration c2bRegisterUrl($data) EndpointCatalog::C2B_REGISTER_URL
C2B simulation c2bSimulate($data) EndpointCatalog::C2B_SIMULATE
STK Push process request stkPush($data) EndpointCatalog::STK_PUSH
STK Push query stkQuery($data) EndpointCatalog::STK_QUERY
Transaction reversal reversal($data) EndpointCatalog::REVERSAL
Transaction status query transactionStatus($data) EndpointCatalog::TRANSACTION_STATUS
Account balance query accountBalance($data) EndpointCatalog::ACCOUNT_BALANCE
Lipa na Bonga redeem Paybill lipaNaBongaRedeemPaybill($data) EndpointCatalog::LIPA_NA_BONGA_REDEEM_PAYBILL
Lipa na Bonga calculate points lipaNaBongaCalculatePoints($data) EndpointCatalog::LIPA_NA_BONGA_CALCULATE_POINTS
IMSI CheckATI imsiCheckAti($data) EndpointCatalog::IMSI_CHECK_ATI
SWAP CheckATI swapCheckAti($data) EndpointCatalog::SWAP_CHECK_ATI
Pull Transactions register URL pullRegister($data) EndpointCatalog::PULL_REGISTER
Pull Transactions query pullQuery($data) EndpointCatalog::PULL_QUERY
IoT search messages iotSearchMessages($data, $headers, $query) or iot() EndpointCatalog::IOT_SEARCH_MESSAGES
IoT filter messages iotFilterMessages($data, $headers, $query) or iot() EndpointCatalog::IOT_FILTER_MESSAGES
IoT delete message thread iotDeleteMessageThread($data, $headers) or iot() EndpointCatalog::IOT_DELETE_MESSAGE_THREAD
IoT get all messages iotGetAllMessages($data, $headers, $query) or iot() EndpointCatalog::IOT_GET_ALL_MESSAGES
IoT send single message iotSendSingleMessage($data, $headers) or iot() EndpointCatalog::IOT_SEND_SINGLE_MESSAGE
IoT delete message iotDeleteMessage($data, $headers) or iot() EndpointCatalog::IOT_DELETE_MESSAGE
IoT all SIMs iotAllSims($data, $headers, $query) or iot() EndpointCatalog::IOT_ALL_SIMS
IoT query lifecycle status iotQueryLifecycleStatus($data, $headers) or iot() EndpointCatalog::IOT_QUERY_LIFECYCLE_STATUS
IoT query customer info iotQueryCustomerInfo($data, $headers) or iot() EndpointCatalog::IOT_QUERY_CUSTOMER_INFO
IoT SIM activation iotSimActivation($data, $headers) or iot() EndpointCatalog::IOT_SIM_ACTIVATION
IoT get activation trends iotGetActivationTrends($data, $headers) or iot() EndpointCatalog::IOT_GET_ACTIVATION_TRENDS
IoT rename asset iotRenameAsset($data, $headers) or iot() EndpointCatalog::IOT_RENAME_ASSET
IoT get location info iotGetLocationInfo($data, $headers) or iot() EndpointCatalog::IOT_GET_LOCATION_INFO
IoT suspend / unsuspend subscriber iotSuspendUnsuspendSub($data, $headers) or iot() EndpointCatalog::IOT_SUSPEND_UNSUSPEND_SUB

Endpoint Paths

All paths use the configured base URL:

Constant Method Path
OAUTH_TOKEN GET /oauth/v1/generate?grant_type=client_credentials
RATIBA_CREATE_PAYBILL POST /standingorder/v1/createStandingOrderExternal
RATIBA_CREATE_BUY_GOODS POST /standingorder/v1/createStandingOrderExternal
B2B_PAYMENT POST /mpesa/b2b/v1/paymentrequest
B2C_PAYMENT POST /mpesa/b2c/v1/paymentrequest
B2POCHI_PAYMENT POST /mpesa/b2c/v1/paymentrequest
C2B_REGISTER_URL POST /mpesa/c2b/v1/registerurl
C2B_SIMULATE POST /mpesa/c2b/v1/simulate
STK_PUSH POST /mpesa/stkpush/v1/processrequest
STK_QUERY POST /mpesa/stkpushquery/v1/query
REVERSAL POST /mpesa/reversal/v1/request
TRANSACTION_STATUS POST /mpesa/transactionstatus/v1/query
ACCOUNT_BALANCE POST /mpesa/accountbalance/v1/query
LIPA_NA_BONGA_REDEEM_PAYBILL POST /v1/lipa/na/bonga/redeem-paybill
LIPA_NA_BONGA_CALCULATE_POINTS POST /v1/lipa/na/bonga/calculator-points
IMSI_CHECK_ATI POST /imsi/v1/checkATI
SWAP_CHECK_ATI POST /imsi/v2/checkATI
PULL_REGISTER POST /pulltransactions/v1/register
PULL_QUERY POST /pulltransactions/v1/query
IOT_SEARCH_MESSAGES POST /simportal/v1/searchmessages
IOT_FILTER_MESSAGES POST /simportal/v1/filtermessages
IOT_DELETE_MESSAGE_THREAD POST /simportal/v1/deleteMessageThread
IOT_GET_ALL_MESSAGES POST /simportal/v1/getallmessages
IOT_SEND_SINGLE_MESSAGE POST /simportal/v1/sendsinglemessage
IOT_DELETE_MESSAGE POST /simportal/v1/deletemessage
IOT_ALL_SIMS POST /simportal/v1/allsims
IOT_QUERY_LIFECYCLE_STATUS POST /simportal/v1/queryLifeCycleStatus
IOT_QUERY_CUSTOMER_INFO POST /simportal/v1/querycustomerinfo
IOT_SIM_ACTIVATION POST /simportal/v1/simactivation
IOT_GET_ACTIVATION_TRENDS POST /simportal/v1/getactivationtrends
IOT_RENAME_ASSET POST /simportal/v1/renameasset
IOT_GET_LOCATION_INFO POST /simportal/v1/getlocationinfo
IOT_SUSPEND_UNSUSPEND_SUB POST /simportal/v1/suspend_unsuspend_sub

Callback and Result URL Notes

Callback actions belong in a web controller because Safaricom calls them over HTTPS.

Suggested path from Yii2 app root: controllers/DarajaController.php

Safaricom sends many responses asynchronously. Any payload with ResultURL, QueueTimeOutURL, CallBackURL, ConfirmationURL, or ValidationURL must point to a publicly reachable HTTPS URL.

Use the component helper when building callback payload fields:

For a deployed housing application, you can omit callbackBaseUrl when Yii sees the correct public host. If the app runs behind a proxy or a queue/console command builds the payload, configure it explicitly:

localhost cannot receive Safaricom callbacks directly because it is only reachable from your own machine. For local development, expose the Yii app through a secure public HTTPS tunnel, then use that tunnel URL as DARAJA_CALLBACK_BASE_URL.

Always store the raw callback JSON before transforming it. This makes reconciliation much easier when Safaricom sends unexpected fields.

Error Handling

Failed HTTP responses throw Safaricom\Daraja\DarajaException.

Testing

Run the package tests:

The included tests check the endpoint catalog and component behavior. Real API calls require valid Safaricom credentials and publicly reachable callback URLs.

Notes


All versions of yii2-safaricom-daraja with dependencies

PHP Build Version
Package Version
Requires php Version >=5.4
yiisoft/yii2 Version ^2.0.6
yiisoft/yii2-httpclient Version ^2.0
yidas/yii2-composer-bower-skip Version ^2.0
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package josemodi97/yii2-safaricom-daraja contains the following files

Loading the files please wait ...