Installation
Requirements
- PHP 7.4 or higher
- Composer
- M-Pesa API credentials (Consumer Key and Secret)
- SSL certificate for production use
Installation Steps
- Install the package via Composer:
composer require mesasdk/php-mpesa
- Configure your environment variables:
MPESA_CONSUMER_KEY=your_consumer_key
MPESA_CONSUMER_SECRET=your_consumer_secret
MPESA_ENVIRONMENT=sandbox # or production
MPESA_BASE_URL=https://apisandbox.safaricom.et # or production URL
- Initialize the SDK in your application:
use MesaSDK\PhpMpesa\Config;
use MesaSDK\PhpMpesa\Mpesa;
$config = new Config();
$config->setBaseUrl(getenv('MPESA_BASE_URL'))
->setConsumerKey(getenv('MPESA_CONSUMER_KEY'))
->setConsumerSecret(getenv('MPESA_CONSUMER_SECRET'))
->setEnvironment(getenv('MPESA_ENVIRONMENT'))
->setVerifySSL(true); // Always true in production
$mpesa = new Mpesa($config);
Development Setup
- Clone the repository:
git clone https://github.com/Mesele-shishay/PhpMpesaSDK.git
cd PhpMpesaSDK
- Install dependencies:
composer install
- Run tests:
composer test
Production Considerations
- SSL Verification: Always enable SSL verification in production:
$config->setVerifySSL(true);
- Environment Variables: Use environment variables for sensitive data:
$config->setConsumerKey($_ENV['MPESA_CONSUMER_KEY']);
- Error Handling: Implement proper error handling:
try {
$mpesa->authenticate();
} catch (MpesaException $e) {
// Handle M-Pesa specific errors
error_log("M-Pesa Error: " . $e->getMessage());
} catch (Exception $e) {
// Handle unexpected errors
error_log("Unexpected Error: " . $e->getMessage());
}
- Logging: Configure logging for debugging and monitoring:
$logger = new MpesaLogger();
$logger->setLogPath('/path/to/logs');
$mpesa->setLogger($logger);
Troubleshooting
Common Issues
-
SSL Certificate Issues
- Ensure your server has valid SSL certificates
- Check if the certificates are properly configured
- Verify the certificate chain is complete
-
Authentication Failures
- Verify your API credentials
- Check if the credentials are properly set in environment variables
- Ensure the environment (sandbox/production) matches your credentials
-
Network Issues
- Check your server's network connectivity
- Verify firewall settings
- Ensure proper DNS resolution
Getting Help
If you encounter issues:
- Check the FAQ section
- Review the error handling guide
- Open an issue on GitHub
- Contact support