Configuration
Overview
The M-Pesa SDK provides a flexible configuration system that allows you to customize various aspects of the integration. This guide explains how to configure the SDK effectively.
Basic Configuration
Initial Setup
use MesaSDK\PhpMpesa\Config;
use MesaSDK\PhpMpesa\Mpesa;
$config = new Config();
$config->setBaseUrl("https://apisandbox.safaricom.et")
->setConsumerKey("your_consumer_key")
->setConsumerSecret("your_consumer_secret")
->setEnvironment('sandbox');
$mpesa = new Mpesa($config);
Configuration Options
1. Environment Settings
// Set environment (sandbox or production)
$config->setEnvironment('sandbox');
// Set base URL
$config->setBaseUrl("https://apisandbox.safaricom.et");
// Set SSL verification
$config->setVerifySSL(true); // Always true in production
2. API Credentials
// Set API credentials
$config->setConsumerKey("your_consumer_key")
->setConsumerSecret("your_consumer_secret");
// Set shortcode
$config->setShortCode("123456");
// Set passkey
$config->setPasskey("your_passkey");
3. Callback URLs
// Set callback URLs
$config->setCallbackUrl("https://your-domain.com/callback")
->setResultUrl("https://your-domain.com/result")
->setQueueTimeOutUrl("https://your-domain.com/timeout");
4. Logging Configuration
// Configure logging
$logger = new MpesaLogger();
$logger->setLogPath('/path/to/logs');
$config->setLogger($logger);
5. HTTP Client Configuration
// Set timeout
$config->setTimeout(30);
// Set retry attempts
$config->setRetryAttempts(3);
Environment Variables
Using Environment Variables
$config->setBaseUrl($_ENV['MPESA_BASE_URL'])
->setConsumerKey($_ENV['MPESA_CONSUMER_KEY'])
->setConsumerSecret($_ENV['MPESA_CONSUMER_SECRET'])
->setEnvironment($_ENV['MPESA_ENVIRONMENT']);
Environment File Example
MPESA_BASE_URL=https://apisandbox.safaricom.et
MPESA_CONSUMER_KEY=your_consumer_key
MPESA_CONSUMER_SECRET=your_consumer_secret
MPESA_ENVIRONMENT=sandbox
MPESA_SHORTCODE=123456
MPESA_PASSKEY=your_passkey
MPESA_CALLBACK_URL=https://your-domain.com/callback
MPESA_RESULT_URL=https://your-domain.com/result
MPESA_TIMEOUT_URL=https://your-domain.com/timeout
Configuration Validation
Validating Configuration
try {
$config->validate();
} catch (ValidationException $e) {
// Handle validation errors
echo "Configuration Error: " . $e->getMessage();
}
Required Fields
- Base URL
- Consumer Key
- Consumer Secret
- Environment
- Shortcode (for some operations)
- Passkey (for some operations)
Production Configuration
1. Performance Settings
$config->setTimeout(30)
->setRetryAttempts(3);
2. Monitoring Settings
$logger = new MpesaLogger();
$logger->setLogPath('/path/to/logs')
->setLogLevel('info');
$config->setLogger($logger);
Testing Configuration
1. Sandbox Environment
$config->setEnvironment('sandbox')
->setBaseUrl("https://apisandbox.safaricom.et")
->setVerifySSL(false);
2. Mock Configuration
$mockConfig = new MockConfig();
$mockConfig->setEnvironment('sandbox')
->setBaseUrl("https://mock-api.example.com");
$mpesa = new Mpesa($mockConfig);