Download the PHP package karson/mpesa-php-sdk without Composer
On this page you can find all versions of the php package karson/mpesa-php-sdk. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Informations about the package mpesa-php-sdk
Mpesa Mozambique PHP SDK
A comprehensive PHP SDK for integrating with M-Pesa Mozambique APIs. This package provides a clean, modern interface for all M-Pesa operations with robust error handling, callback processing, and extensive validation.
Features
- 🚀 Modern PHP 8.1+ Support: Built with modern PHP features including typed properties, named arguments, and enums
- 📦 Unified Response Architecture: Streamlined response classes with eliminated code duplication (~90% reduction)
- 🔄 Callback Handler System: Complete callback processing with event-driven architecture (TODO)
- ✅ Type Safety: Strongly typed responses with specific methods for each operation
- 🏗️ Clean Architecture: Organized structure with dedicated response classes and clear inheritance
- 🔐 Security First: Built-in signature validation, parameter sanitization, and secure token management
- 📊 Transaction Operations: Full support for C2B, B2C, B2B transactions with sync/async modes
- 🔍 Query Operations: Transaction status queries and customer name lookups
- 💰 Refund/Reversal: Complete transaction reversal support with partial refund capabilities
- 🎯 Smart Validation: Comprehensive parameter validation with detailed error messages
- 📱 Laravel Integration: Native Laravel service provider with configuration publishing
- 🔧 Developer Experience: Extensive examples, comprehensive documentation, and debugging tools
Installation
You can install the package via composer:
Usage
Basic Setup
Customer to Business (C2B) Transactions
Business to Customer (B2C) Transactions
Transaction Status Query
Customer Name Query
Business to Business (B2B) Transactions
Transaction Refund/Reversal
Response Objects
All methods return strongly typed response objects based on a unified architecture:
BaseResponse (Unified Response Class)
All transaction responses now inherit from BaseResponse
with common methods:
Transaction Response Classes
- TransactionResponse: Unified response for C2B, B2C, B2B transactions
- TransactionStatusResponse: For transaction status queries
- CustomerNameResponse: For customer name lookups
- ReversalResponse: For refund/reversal operations
Transaction Status Response Methods
getTransactionId()
: Get the transaction IDgetConversationId()
: Get the conversation IDgetTransactionStatus()
: Get the current transaction statusgetAmount()
: Get the transaction amountgetCurrency()
: Get the transaction currencygetReceiverParty()
: Get the receiver party informationgetTransactionCompletedDateTime()
: Get completion timestampisTransactionCompleted()
: Check if transaction is completedisTransactionPending()
: Check if transaction is pendingisTransactionFailed()
: Check if transaction failed
Customer Name Response Methods
getCustomerMSISDN()
: Get the customer phone numbergetFirstName()
: Get the customer's first name (obfuscated)getSecondName()
: Get the customer's second name (obfuscated)getCustomerName()
: Get the full customer nameisCustomerFound()
: Check if customer was found
Refund/Reversal Response Methods
getTransactionId()
: Get the original transaction IDgetReversalTransactionId()
: Get the reversal transaction IDgetReversalAmount()
: Get the reversed amount (for partial reversals)getConversationId()
: Get the conversation IDisReversalSuccessful()
: Check if reversal was successfulisPartialReversal()
: Check if it was a partial reversal
Response Class Architecture
The SDK v2.0 features a completely refactored response architecture that eliminates ~90% of code duplication:
Key Improvements:
- Unified API: All transaction types (C2B, B2C, B2B) now return the same
TransactionResponse
class - Eliminated Duplication: Removed redundant sync/async response classes
- Better Type Safety: Specific methods for each response type with proper return types
- Consistent Interface: All responses share common methods from
BaseResponse
- Simplified Usage: No need to remember different method names for different transaction types
Project Structure
The SDK v2.0 features a streamlined, organized structure:
Key Architectural Improvements:
- Unified Response System: Single
TransactionResponse
class for all transaction types - Callback Handler System: Complete event-driven callback processing
- Streamlined Structure: Eliminated redundant directories and classes
- Better Organization: Clear separation of concerns with dedicated folders
- Enhanced Security: Comprehensive exception handling and validation
API Reference
For detailed API documentation including all endpoints, request/response parameters, and examples, see the API Documentation.
Laravel Integration
Installation in Laravel
Add the following environment variables to your .env
file:
Service Provider Registration
The package includes a Laravel service provider that automatically registers the M-Pesa service. You can inject it into your controllers:
Error Handling
All response objects provide comprehensive error information with the unified API:
Response Structure
Unified Transaction Responses
All transaction methods (C2B, B2C, B2B) now return a unified TransactionResponse
object:
Transaction Status Tracking
Use the conversation ID to track transaction status:
Exception Handling
The SDK provides comprehensive error handling with custom exceptions:
Exception Types
- ValidationException: Thrown when input parameters fail validation
- AuthenticationException: Thrown when API authentication fails
- ApiException: Thrown when M-Pesa API returns an error
Token Management
The SDK includes intelligent token management with caching and optimization:
Token Management Features
- Automatic Generation: Tokens are generated automatically when needed
- Smart Reuse: Existing tokens are reused to improve performance
- Manual Control: Clear tokens when needed
- Thread Safe: Safe for use in concurrent environments
Best Practices
Parameter Validation
The SDK includes built-in parameter validation to ensure data integrity:
Response Code Constants
Use predefined constants for consistent response handling:
Testing
The SDK includes comprehensive unit tests to ensure reliability:
Test Coverage
The test suite covers:
- Constants: Response codes and transaction status validation
- Validation: Parameter validation for all transaction types
- Authentication: Token management and expiration
- Response Classes: All response parsing and methods
- Exceptions: Custom exception handling
Running Tests
What's New in v2.0
🚀 Major Improvements
- Unified API: All transaction methods (C2B, B2C, B2B) now return the same
TransactionResponse
class - Eliminated Code Duplication: ~90% reduction in response class code through unified architecture
- Enhanced Type Safety: Better IDE support with specific typed methods
- Improved Performance: Optimized response parsing and memory usage
- Better Security: Enhanced validation, signature verification, and error handling
🔄 Breaking Changes
Response Classes Unified
Removed getData() Method
📦 New Features
Enhanced Response Methods
Changelog
Please see CHANGELOG for more information what has changed recently.
Contributing
Please see CONTRIBUTING for details.
Security
If you discover any security related issues, please email [email protected] instead of using the issue tracker.
Credits
- Karson Adam
- All Contributors
License
The MIT License (MIT). Please see License File for more information.
PHP Package Boilerplate
This package was generated using the PHP Package Boilerplate.