1. Mpesa Authentication Process
Objective: Understand how Mpesa authenticates API requests and the importance of access tokens.
-
What is Authentication in Mpesa?
Mpesa APIs use OAuth 2.0 for authentication. To access Mpesa services, you must generate an access token using your consumer key and consumer secret, which are provided during Daraja API registration. -
Why Use Access Tokens?
Access tokens serve as temporary keys that grant secure access to Mpesa’s API endpoints. Tokens are valid for a limited time (e.g., 1 hour). -
Steps in Authentication:
- Encode the consumer key and secret using Base64.
- Send them in the HTTP
Authorization
header to the OAuth endpoint. - Receive an access token in the response.
2. API Endpoint
Objective: Familiarize yourself with the endpoint used for generating access tokens.
-
OAuth API Endpoint:
The Mpesa OAuth endpoint is as follows:https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials
-
HTTP Method:
The endpoint uses theGET
method. -
Headers:
You must include the following headers in your request:Authorization
: This contains the Base64-encoded string ofconsumerKey:consumerSecret
.- Example Header:
Authorization: Basic Base64Encoded(consumerKey:consumerSecret)
3. Code Implementation
Objective: Implement a function to automate the token generation process.
-
Example in PHP:
function generateAccessToken() { $consumerKey = 'your_consumer_key'; $consumerSecret = 'your_consumer_secret'; $credentials = base64_encode("$consumerKey:$consumerSecret"); $url = "https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials"; $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_HTTPHEADER, ["Authorization: Basic $credentials"]); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($curl); curl_close($curl); $result = json_decode($response); return $result->access_token; }
-
Example in Node.js:
const axios = require('axios'); async function generateAccessToken() { const consumerKey = 'your_consumer_key'; const consumerSecret = 'your_consumer_secret'; const credentials = Buffer.from(`${consumerKey}:${consumerSecret}`).toString('base64'); try { const response = await axios.get( 'https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials', { headers: { Authorization: `Basic ${credentials}` } } ); return response.data.access_token; } catch (error) { console.error('Error generating access token:', error.message); } }
4. Error Handling
Objective: Anticipate and handle issues during token generation.
-
Potential Errors:
- Invalid Credentials: Occurs if the consumer key or secret is incorrect.
- Network Issues: Caused by poor connectivity or server downtime.
- API Limitations: Repeated requests may trigger rate limits.
-
How to Handle Errors:
- Validate consumer key and secret before making the request.
- Use try-catch blocks (in Node.js or Python) or check
curl_exec
errors (in PHP). - Log error responses for debugging.
5. Testing Access Token Generation
Objective: Verify your implementation works as expected.
-
Using Postman:
- Create a new request.
- Set the request type to
GET
and paste the OAuth endpoint URL. - Add a header:
- Key:
Authorization
- Value:
Basic Base64Encoded(consumerKey:consumerSecret)
- Key:
- Click Send.
- Inspect the response body for the access token.
-
Sample Response:
{ "access_token": "hq0Xh...Cw", "expires_in": "3599" }