Download the PHP package kemboielvis/mpesa-sdk-php without Composer
On this page you can find all versions of the php package kemboielvis/mpesa-sdk-php. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Informations about the package mpesa-sdk-php
M-Pesa PHP SDK
A PHP SDK for Safaricom M-Pesa APIs with batteries included: STK Push, C2B, B2C, Reversals, Transaction Status, and more. Now with multi-process safe token caching (lock + atomic writes).
Requirements
- PHP 8.0+
- ext-curl, ext-openssl (installed by default on most PHP builds)
- Composer for library installation
Installation
Quick start
Each call such as $mpesa->stk() returns a new service with its own copy of the settings.
Set shared values (business code, pass key, certificate, URLs) on $mpesa first; values you
set on a service (e.g. setPartyA()) only apply to that service.
For Buy Goods, where the till number differs from the store number used as the business code:
Multi-process safe token cache
The SDK caches the OAuth access token on disk to minimize network calls. The cache is safe for concurrent use by multiple PHP processes:
- A lock file prevents the "thundering herd" when the token needs refreshing.
- Cache writes are atomic (temp file + rename) to avoid partial or corrupt files.
- Malformed/expired cache is ignored and re-fetched safely by a single lock holder.
Details:
- Default cache name:
mpesa_api_cache.json. If you pass only a filename, it is stored under the system temp directory. You can provide an absolute or relative path. - Lock file location: same directory as the cache file with
.locksuffix. For stream paths (e.g.,php://memory), the lock is stored in the system temp directory. - Methods:
Mpesa::setStoreFile(string $path)— sets the token cache file and refreshes the internal client.Mpesa::clearTokenCache()— clears the current token cache.Mpesa::getResolvedStoreFilePath()— returns the resolved absolute path the SDK uses for the cache.Mpesa::setDebug(bool $on)— enable debug logging to troubleshoot token flow.
Services and examples
-
STK Push (Lipa Na M-Pesa)
-
Query STK Push status
-
Customer to Business (C2B) — Register URLs
-
C2B — Simulate payment
-
Business to Customer (B2C)
-
B2C Hakikisha (check who owns a number before paying; requires Safaricom approval)
-
Mobile Number Validation (check a number is registered under an ID; commercial, billed per call)
-
Mobile Data Bundles (sell Safaricom data bundles in your app)
-
Business to Pochi (pay a customer's Pochi la Biashara wallet)
-
Reversal
-
Business Pay Bill (pay a paybill from your business account)
- Business Buy Goods (pay a till / merchant store from your business account)
It takes the same setters as Business Pay Bill.
-
B2C Account Top Up (load funds into a B2C shortcode)
- Account Balance
The actual balance arrives later on your ResultURL. Parse it with:
-
Pull Transactions (recover C2B transactions from the last 48 hours)
- Tax Remittance (pay KRA)
PartyB is fixed to KRA's shortcode 572572. The final result (Result.ResultCode, TransactionID, ...) is posted to your ResultURL.
- B2B Express Checkout (USSD Push to Till)
The callback posted to your callbackUrl has resultCode (0 = success, 4001 = user cancelled), resultDesc, requestId, amount, and on success transactionId and status.
-
Dynamic QR code
- Lipa na Bonga (accept Bonga points as payment)
The payment result is sent to your C2B confirmation URL, so register it first with customerToBusiness()->registerUrl().
-
Age on Network (when was a number registered? commercial, billed per call)
- IoT SIM Management (manage Safaricom IoT SIMs and their messages)
Some failures (e.g. a SIM that is not in your account) still return responseCode 200, so check getBody() as well.
Error handling
Wrap service calls in try/catch:
Advanced configuration
- Security credentials (B2C, Reversal, Transaction Status, Account Balance, ...)
M-Pesa expects the initiator password encrypted with Safaricom's public key certificate (RSA, PKCS #1 v1.5). Use one of these:
If a credential is set and there is no certificate, a password passed to a service is ignored
and the credential is used. With neither, passing a password throws an InvalidArgumentException.
- SSL / TLS certificate verification
Off by default. With it off, anyone on the network path can impersonate Safaricom's servers and read your consumer key, secret and tokens, so turn it on in production:
If requests then fail with certificate errors, update your system CA certificates
(e.g. the ca-certificates package, or curl.cainfo in php.ini) rather than turning it off.
-
Timeouts
- Token cache file
The default cache file is mpesa_token_<sha256 of your credentials>.json in the system temp
directory, readable only by the PHP user.
-
Debug logs
- Test-only: override base URL For automated tests or proxies (not usually needed in apps). Set it before creating services:
Testing
The repository ships with a few simple tests, including concurrency/tamper checks for the token cache.
-
Manual sandbox STK push (credentials come from environment variables, never from the code)
-
Smoke test: cache read path
-
Concurrency test: verifies single network fetch with many parallel processes
- Tamper concurrency test: corrupts the cache mid-flight; ensures consistency and minimal re-fetch
Notes:
- These tests use a local fake server and do not hit Safaricom endpoints.
- If you see permission issues for the cache path, choose a directory writable by your PHP processes (e.g.,
/tmpor a shared run directory) and useMpesa::setStoreFile().
Troubleshooting
- Token cache not updating:
- Ensure the process has write permission to the cache directory.
- Check for SELinux/AppArmor restrictions if applicable.
- Enable debug with
$mpesa->setDebug(true)to see lock/cache logs in error_log.
- SSL errors after
setVerifySsl(true): update your CA certificates (ca-certificatespackage orcurl.cainfoin php.ini); keep verification on in production.
License
MIT License. See LICENSE in this repository.
Support
Open an issue with details (PHP version, OS, logs, and a minimal repro). Pull requests welcome.
All versions of mpesa-sdk-php with dependencies
ext-curl Version *
ext-openssl Version *