Easily integrate M-PESA APIs into your PHP or Laravel applications using the Safaricom-Ethiopia-PLC/mpesa-php-sdk package.
- Authentication: Generate access tokens effortlessly.
- STK Push (NI Push): Initiate customer-to-business payments with USSD prompts.
- C2B Support: Register URLs and handle customer payments.
- B2C Payouts: Process business-to-customer disbursements.
- Modular Design: Well-structured and extensible codebase.
- Error Handling: Robust, developer-friendly error management.
- PHP 7.4 or higher
- cURL extension enabled
- Composer
-
Install the SDK via Composer:
composer require Safaricom-Ethiopia-PLC/mpesa-php-sdk:dev-main
-
Since this package is hosted on GitHub, add the repository to your
composer.json:"repositories": [ { "type": "vcs", "url": "https://github.com/Safaricom-Ethiopia-PLC/mpesa-php-sdk.git" } ], "require": { "Safaricom-Ethiopia-PLC/mpesa-php-sdk": "dev-main" }, "minimum-stability": "dev"
Then run:
composer update
-
If using Laravel, publish the configuration file (if supported by your SDK):
php artisan vendor:publish --tag=mpesa-config
-
The
Authentication.phpfile centralizes configuration. Customize it with:$config = [ 'base_url' => 'https://apisandbox.safaricom.et/mpesa/', 'consumer_key' => 'your_consumer_key', 'consumer_secret' => 'your_consumer_secret', ]; $securityCredential = 'your_security_credential';
-
Configuration is managed via
config/mpesa.phpin Laravel projects. After publishing the config file withphp artisan vendor:publish --tag=mpesa-config, customize it with your credentials. Use environment variables in your.envfile:APP_ENV=development #production DEV_MPESA_BASE_URL=https://apisandbox.safaricom.et/ DEV_MPESA_CONSUMER_KEY=your_consumer_key DEV_MPESA_CONSUMER_SECRET=your_consumer_secret DEV_SECURITY_CREDENTIAL=your_security_credential PROD_MPESA_BASE_URL=https://apisandbox.safaricom.et/ PROD_MPESA_CONSUMER_KEY=your_consumer_key PROD_MPESA_CONSUMER_SECRET=your_consumer_secret PROD_SECURITY_CREDENTIAL=your_security_credential
In a Laravel controller:
<?php namespace App\Http\Controllers; use Mpesa\Sdk\Authentication as MpesaAuth; use Mpesa\Sdk\Client; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Log; class MpesaController extends Controller { private function getClient(): Client { $env = env('APP_ENV', 'development'); $config = config("mpesa.{$env}", [ 'base_url' => 'https://apisandbox.safaricom.et/mpesa/', 'consumer_key' => 'YOUR_CONSUMER_KEY', 'consumer_secret' => 'YOUR_CONSUMER_SECRET', ]); return new Client(array_merge($config, [ 'timeout' => 1, 'retries' => 5, 'retry_delay' => 10, ])); } private function authenticate(Client $client): string { $auth = new MpesaAuth($client); $token = $auth->generateToken(); Log::info("M-Pesa Auth Success", ['token' => $token->accessToken]); return $token->accessToken; } private function getAccessToken(): string { return Cache::remember('mpesa_access_token', 3599, fn() => $this->authenticate($this->getClient())); } public function testSdk() { try { return response()->json(['token' => $this->getAccessToken()]); } catch (\Exception $e) { return response()->json(['error' => $e->getMessage()], 500); } } }
Api Route
Route::get('/test-mpesa', [MpesaController::class, 'testSdk']); Route::prefix('mpesa')->group(function () { Route::get('/auth', [MpesaController::class, 'getToken']); Route::post('/balance', [MpesaController::class, 'checkBalance']); Route::post('/b2c/payout', [MpesaController::class, 'b2cPayout']); Route::post('/c2b/register', [MpesaController::class, 'c2bRegister']); Route::post('/c2b/simulate', [MpesaController::class, 'simulateTransaction']); Route::post('/stk/push', [MpesaController::class, 'stkPush']); Route::post('/reverse', [MpesaController::class, 'reverseTransaction']); Route::post('/status', [MpesaController::class, 'transactionStatus']); });
-
-
Service Classes: Each service class (e.g.,
StkPushService) encapsulates an API operation. Copy the full implementations from your project files. -
Logging: Logs are written to the
logs/directory. Ensure it exists and is writable. -
UUID: Some examples use
ramsey/uuid. Install it with:
composer require ramsey/uuid
- Sandbox vs Production: Update
base_urlinAuthentication.phpfor production use:
'base_url' => 'https://apisandbox.safaricom.et/mpesa'
-
This SDK provides a Client class for API interactions and service classes for each M-PESA API endpoint. Below are usage examples for authentication and various API operations.
All API requests require an access token. Use Authentication.php to authenticate a Client instance:
require __DIR__ . '/vendor/autoload.php';
require __DIR__ . '/Authentication.php'; // Adjust path as needed
use Mpesa\Sdk\Client;
$client = getClient();
authenticate($client, __DIR__ . '/logs/auth.log');
// The client is now ready for API requestsInitiate an STK Push payment request using StkPushService:
require __DIR__ . '/vendor/autoload.php';
require __DIR__ . '/Authentication.php';
require __DIR__ . '/StkPushService.php';
use Ramsey\Uuid\Uuid;
$service = new StkPushService();
$service->run();Check your account balance using AccountBalanceService:
require __DIR__ . '/vendor/autoload.php';
require __DIR__ . '/Authentication.php';
require __DIR__ . '/AccountBalanceService.php';
$service = new AccountBalanceService();
$service->run();Register C2B callback URLs using C2BRegisterService:
require __DIR__ . '/vendor/autoload.php';
require __DIR__ . '/Authentication.php';
require __DIR__ . '/C2BRegisterService.php';
$service = new C2BRegisterService();
$service->run();Initiate a B2C payout using B2CPayOutService:
require __DIR__ . '/vendor/autoload.php';
require __DIR__ . '/Authentication.php';
require __DIR__ . '/B2CPayOutService.php';
$service = new B2CPayOutService();
$service->run();Query transaction status using TransactionStatusService:
require __DIR__ . '/vendor/autoload.php';
require __DIR__ . '/Authentication.php';
require __DIR__ . '/TransactionStatusService.php';
$service = new TransactionStatusService();
$service->run();Reverse a transaction using TransactionReversalService:
require __DIR__ . '/vendor/autoload.php';
require __DIR__ . '/Authentication.php';
require __DIR__ . '/TransactionReversalService.php';
$service = new TransactionReversalService();
$service->run();Simulate a B2C transaction using SimulateTransactionService:
require __DIR__ . '/vendor/autoload.php';
require __DIR__ . '/Authentication.php';
require __DIR__ . '/SimulateTransactionService.php';
$service = new SimulateTransactionService();
$service->run();Contributions are welcome! Please follow these steps:
-
Fork the repository on GitHub.
-
Clone your fork to your local machine.
git clone https://github.com/Safaricom-Ethiopia-PLC/mpesa-php-sdk.git
-
Create a new feature branch.
git checkout -b feature/<your-feature-name>
-
Make your changes and commit them.
git commit -am "Add new <short feature description>" -
Push your branch to your fork.
git push origin feature/<your-feature-name>
-
Open a pull request from your branch to the main repository.
This project is licensed under the MIT License. See the LICENSE file for more details.
Happy coding with M-Pesa PHP SDK!