Table of Contents
-
Introduction
-
Installation
-
Configuration
-
Core Functionality
-
Transaction Types
-
Error Handling
-
Security Best Practices
-
Advanced Usage
-
Testing
-
Support and Contributing
1. Introduction
The M-Pesa PHP SDK is a robust, comprehensive package designed to simplify integration with Safaricom's M-Pesa payment services. This SDK provides developers with a streamlined approach to implementing mobile payment solutions across various transaction types.
Key Features
-
Complete M-Pesa API integration
-
Support for sandbox and production environments
-
Automatic access token management
-
Built-in phone number formatting
-
Comprehensive error handling
-
Support for multiple transaction types
2. Installation
Composer Installation
Install the SDK using Composer:
composer require codexoft/mpesa-sdk
Composer.json Configuration
Add the following to your composer.json
:
{
"require": {
"codexoft/mpesa-sdk": "^1.0"
}
}
3. Configuration
Environment Configuration
Option 1: Direct Configuration
use codexoft\MpesaSdk\Mpesa;
$config = [
'env' => 'sandbox', // or 'production'
'credentials' => [
'passKey' => 'your-pass-key',
'initiatorPass' => 'your-initiator-pass',
'initiatorName' => 'your-initiator-name'
],
'appInfo' => [
'consumerKey' => 'your-consumer-key',
'consumerSecret' => 'your-consumer-secret'
],
'businessShortCode' => 'your-shortcode',
'shortCodeType' => 'paybill', // or 'till'
'requester' => 'your-requester-id'
];
try {
$mpesa = new Mpesa($config);
} catch (Exception $e) {
// Handle configuration errors
log_error("Configuration Error: " . $e->getMessage());
}
Option 2: Environment Variables (Recommended)
Create a .env
file:
MPESA_ENV=sandbox
MPESA_PASS_KEY=your-pass-key
MPESA_INITIATOR_PASS=your-initiator-pass
MPESA_INITIATOR_NAME=your-initiator-name
MPESA_CONSUMER_KEY=your-consumer-key
MPESA_CONSUMER_SECRET=your-consumer-secret
MPESA_BUSINESS_SHORTCODE=your-shortcode
MPESA_SHORTCODE_TYPE=paybill
MPESA_REQUESTER=your-requester-id
4. Core Functionality
Initializing the SDK
try {
$mpesa = new Mpesa($config);
} catch (InvalidArgumentException $e) {
log_error("Configuration Error: " . $e->getMessage());
} catch (Exception $e) {
log_error("Initialization Error: " . $e->getMessage());
}
5. Transaction Types
5.1 STK Push (M-Pesa Express)
try {
$response = $mpesa->stkPush(
amount: 100,
phoneNumber: '254712345678',
accountNumber: 'INV001',
callBackUrl: 'https://example.com/callback',
description: 'Payment for Invoice 001'
);
print_r($response);
} catch (Exception $e) {
echo $e->getMessage();
}
5.2 B2C Payments
try {
$response = $mpesa->initiateB2C(
amount: 100,
phoneNumber: '254712345678',
commandID: 'BusinessPayment',
resultUrl: 'https://example.com/b2c-result',
queueTimeoutUrl: 'https://example.com/b2c-timeout',
remarks: 'Salary Payment'
);
print_r($response);
} catch (Exception $e) {
echo $e->getMessage();
}
5.3 QR Code Generation
try {
$response = $mpesa->generateQRCode(
amount: 100,
accountNumber: 'INV001',
size: 300 // Size in pixels
);
print_r($response);
} catch (Exception $e) {
echo $e->getMessage();
}
6. Error Handling
Comprehensive Error Management
try {
// M-Pesa API call
} catch (InvalidArgumentException $e) {
// Handle validation errors
error_log("Validation error: " . $e->getMessage());
} catch (Exception $e) {
// Handle API errors
error_log("API error: " . $e->getMessage());
// Get HTTP status code if available
if (property_exists($e, 'httpCode')) {
error_log("HTTP Status: " . $e->httpCode);
}
}
7. Security Best Practices
Security Recommendations
-
Use environment variables for sensitive data
-
Never commit credentials to version control
-
Always use HTTPS for callbacks
-
Validate and sanitize all input data
-
Implement IP whitelisting for callbacks
8. Advanced Usage
Webhook Integration
<?php
// webhook.php
$callbackData = file_get_contents('php://input');
if (!$callbackJson = json_decode($callbackData, true)) {
header('HTTP/1.1 400 Bad Request');
exit('Invalid JSON');
}
// Process callback based on transaction type
switch ($callbackJson['TransactionType'] ?? '') {
case 'Pay Bill':
processC2BPayment($callbackJson);
break;
case 'B2B Payment':
processB2BPayment($callbackJson);
break;
}
// Respond to M-Pesa
header('Content-Type: application/json');
echo json_encode([
'ResultCode' => 0,
'ResultDesc' => 'Success'
]);
9. Testing
Sandbox Testing
-
Use
$config['env'] = 'sandbox'
-
Test Phone Numbers:
-
254708374149
-
254708374150
-
10. Support and Contributing
Requirements
-
PHP 8.0+
-
Extensions: curl, json, openssl
-
Composer
-
HTTPS-enabled web server
Contributing
Contributions are welcome! Please submit pull requests or open issues on the project repository.
Conclusion
The M-Pesa PHP SDK provides a comprehensive, secure, and easy-to-use solution for integrating M-Pesa payment services into PHP applications. By abstracting complex API interactions and providing robust error handling, the SDK significantly reduces development complexity.