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.
Download josemodi97/yii2-safaricom-daraja
More information about josemodi97/yii2-safaricom-daraja
Files in josemodi97/yii2-safaricom-daraja
Package yii2-safaricom-daraja
Short Description 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.
License MIT
Homepage https://github.com/JoseModi97/yii2-safaricom-daraja
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
- PHP
5.4+ - Yii2
2.0.6+ - PHPUnit
4.8+through9.xfor the included tests - Composer package name:
josemodi97/yii2-safaricom-daraja
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:
- App config:
config/web.php
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
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
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:
- 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:
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:
- Form model:
models/StkPushForm.php - Controller:
controllers/DarajaController.php - Optional payment view:
views/daraja/stk-push.php
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:
- 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
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:
- Controller path from Yii2 app root:
controllers/DarajaController.php - Console command path from Yii2 app root:
commands/DarajaController.php
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:
- Service class:
components/DarajaService.php - Console command:
commands/DarajaController.php - Web controller:
controllers/DarajaController.php
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:
- Service class:
components/DarajaService.php - Console command:
commands/DarajaController.php - Web controller:
controllers/DarajaController.php
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:
- Service class:
components/DarajaService.php - Console command:
commands/DarajaController.php - Web controller:
controllers/DarajaController.php
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:
- Service class:
components/DarajaService.php - Console command:
commands/DarajaController.php - Web controller:
controllers/DarajaController.php
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:
- Service class:
components/DarajaService.php - Console command:
commands/DarajaController.php - Web controller:
controllers/DarajaController.php
Pull Transactions API
Put these examples in your own service class, console command, or controller action.
Suggested paths from Yii2 app root:
- Service class:
components/DarajaService.php - Console command:
commands/DarajaController.php - Web controller:
controllers/DarajaController.php
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:
- Service class:
components/DarajaService.php - Console command:
commands/DarajaController.php - Web controller:
controllers/DarajaController.php
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:
- Sandbox:
https://sandbox.safaricom.co.ke - Production:
https://api.safaricom.co.ke
| 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
- The extension does not hard-code credentials from the Postman collection.
- Put credentials in environment variables or Yii application params.
- Keep callback actions CSRF-exempt because Safaricom will not send a Yii CSRF token.
- Keep your production and sandbox credentials separate.
- Store IDs returned by Safaricom, especially
MerchantRequestID,CheckoutRequestID,ConversationID,OriginatorConversationID, and transaction IDs.
All versions of yii2-safaricom-daraja with dependencies
yiisoft/yii2 Version ^2.0.6
yiisoft/yii2-httpclient Version ^2.0
yidas/yii2-composer-bower-skip Version ^2.0