Authentication

Authentication

Overview

The M-Pesa SDK uses OAuth 2.0 for authentication. This guide explains how to handle authentication and manage access tokens.

Basic Authentication

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);

Authenticating

try {
    $mpesa->authenticate();
    // Authentication successful
} catch (AuthenticationException $e) {
    // Handle authentication error
    echo "Authentication failed: " . $e->getMessage();
}

Token Management

Access Token

The SDK automatically manages access tokens. You can access the current token:

$token = $mpesa->getAuth()->getToken();

Token Expiration

Tokens expire after a certain period. The SDK handles token refresh automatically:

// Check if token is expired
if ($mpesa->getAuth()->isExpired()) {
    // Token will be refreshed automatically on next request
    $mpesa->authenticate();
}

Security Best Practices

1. Environment Variables

Always use environment variables for credentials:

$config->setConsumerKey($_ENV['MPESA_CONSUMER_KEY'])
    ->setConsumerSecret($_ENV['MPESA_CONSUMER_SECRET']);

2. SSL Verification

Enable SSL verification in production:

$config->setVerifySSL(true);

3. Error Handling

Implement proper error handling:

try {
    $mpesa->authenticate();
} catch (AuthenticationException $e) {
    // Handle authentication errors
    error_log("Authentication Error: " . $e->getMessage());
} catch (NetworkException $e) {
    // Handle network errors
    error_log("Network Error: " . $e->getMessage());
} catch (Exception $e) {
    // Handle other errors
    error_log("Unexpected Error: " . $e->getMessage());
}

Common Issues

1. Invalid Credentials

  • Verify your consumer key and secret
  • Check if credentials are properly set
  • Ensure environment matches credentials

2. Network Issues

  • Check internet connectivity
  • Verify API endpoint accessibility
  • Check firewall settings

3. SSL Issues

  • Ensure valid SSL certificates
  • Check certificate chain
  • Verify SSL configuration

Production Considerations

1. Monitoring

Implement monitoring for authentication issues:

$logger = new MpesaLogger();
$logger->setLogPath('/path/to/logs');
$mpesa->setLogger($logger);

Testing

1. Sandbox Environment

Use sandbox environment for testing:

$config->setEnvironment('sandbox')
    ->setBaseUrl("https://apisandbox.safaricom.et");

Related Topics