We use cookies
We use cookies to improve your experience and analyze site traffic. Do you accept analytics cookies?
Authorization API M-Pesa Kenya: Complete Expert Guide to Access Tokens for Developers (2026)

Introduction to Authorization API in M-Pesa Integration
When building any system around the M-Pesa integration website in Kenya, the Authorization API is your foundation. Without it, nothing works: no payments, no disbursements, no API calls.
The Authorization API, provided by Safaricom, generates a time-bound access token that allows your application to securely communicate with the Daraja platform.
Think of it like a digital passport; every API request must carry it.
What is the Authorization API?
The Authorization API is responsible for generating an OAuth 2.0 access token used to authenticate all M-Pesa API requests.
Core Features
- Uses OAuth 2.0 authentication
- Token validity: 3600 seconds (1 hour)
- Required for ALL Daraja APIs
- Supports sandbox testing and production environments
Important: This API must always be called before any other API.
How the Authorization API Works
Here’s a simplified workflow:
- You retrieve:
- Consumer Key
- Consumer Secret
- Your application sends a request using Basic Authentication
- Safaricom validates credentials
- You receive:
access_tokenexpires_in
- You use the token in all subsequent API calls
Getting Started
Prerequisites
- Create a Daraja Account on the Safaricom Developer Portal.
- Create a sandbox app in the portal to get API credentials.
- Retrieve Consumer Key & Consumer Secret from your sandbox app on My Apps.
Good to Know
- Token Expiry: Tokens expire after 3600 seconds (1 hour).
Environments
| Environment | Description |
|---|---|
| Sandbox | Testing environment. |
| Production | Live environment for real transactions. |
Authorization API Endpoint
Sandbox (Testing Environment)
https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials
Production (Live Environment)
https://api.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials
Prerequisites for Authorization API Integration
Before generating an access token, ensure you have:
1. Daraja Developer Account
Register on the Safaricom Developer Portal.
Create a Daraja Account on the Safaricom Developer Portal.
2. Create a Sandbox App
Create a sandbox app in the portal to get API credentials. From your dashboard:
- Generate credentials
- Enable APIs
3. Retrieve Credentials
Retrieve Consumer Key & Consumer Secret from your sandbox app on My Apps. You’ll need:
- Consumer Key
- Consumer Secret
4. REST Client or Backend Setup
You can use:
- Postman
- Node.js
- Python
- PHP
Step-by-Step: Generate an Access Token
Step 1: Prepare Credentials
Combine:
ConsumerKey:ConsumerSecret
Then encode in Base64
Step 2: Send Request
cURL Example
curl -X GET "https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials" \
-u "YOUR_CONSUMER_KEY:YOUR_CONSUMER_SECRET"
Step 3: Request Structure
Headers
{
"Authorization": "Basic BASE64_ENCODED_STRING"
}
Query Params
grant_type=client_credentials
Step 4: Sample Response
{
"access_token": "c9SQxWWhmdVRlyh0zh8gZDTkubVF",
"expires_in": 3599
}
Using the Access Token
Once generated, include the token in every request:
Authorization: Bearer ACCESS_TOKEN
Example (Node.js)
const axios = require('axios');
async function generateToken() {
const key = "YOUR_KEY";
const secret = "YOUR_SECRET";
const auth = Buffer.from(`${key}:${secret}`).toString('base64');
const res = await axios.get(
"https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials",
{
headers: {
Authorization: `Basic ${auth}`
}
}
);
return res.data.access_token;
}
Example (Python)
import requests
from requests.auth import HTTPBasicAuth
url = "https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials"
response = requests.get(url, auth=HTTPBasicAuth("KEY", "SECRET"))
print(response.json())
Token Expiry and Management Strategy
Token Lifecycle
- Valid for: 3600 seconds
- After expiry → must regenerate
Best Practices for Token Handling
- Cache tokens in memory or a database
- Avoid generating a token per request
- Refresh token automatically before expiry
Recommended Workflow
| Step | Action |
|---|---|
| 1 | Generate token |
| 2 | Store token |
| 3 | Use for API calls |
| 4 | Refresh after expiry |
Testing Authorization API
Option 1: Daraja Simulator
Safaricom provides a built-in simulator:
- Select your app
- Auto-populates credentials
- Generates token instantly
Option 2: Postman
Steps:
- Set method to GET
- Add Basic Auth (Key & Secret)
- Add query param
grant_type=client_credentials - Send request
Common Errors and How to Fix Them
1. Invalid Grant Type
Error Code: 400.008.02
Cause: Wrong grant type
Fix:
grant_type=client_credentials
2. Invalid Authentication Type
Error Code: 400.008.01
Cause: Wrong auth method
Fix:
- Use Basic Authentication
3. Token Not Working
Cause:
- Token expired
Fix:
- Generate a new token
4. Unauthorized (401 Error)
Cause:
- Wrong credentials
Fix:
- Verify Consumer Key & Secret
Security Best Practices
1. Protect Credentials
- Store in
.envfiles - Never expose in the frontend
2. Use HTTPS Only
- Mandatory for production
3. Backend-Only Authentication
- Never generate tokens on the frontend
4. Token Rotation
- Refresh periodically
Advanced Insights for Developers
1. Token Invalidation Rule
Each new token invalidates the previous one
Implication:
- Avoid multiple simultaneous token requests
2. Centralized Token Service
For large systems:
- Create a token service layer
- Share token across services
3. Microservices Setup
- Use Redis or a cache for token storage
- Sync token across services
Real-World Use Case
Let’s say you’re building a Kenyan e-commerce platform:
- User clicks “Pay with M-Pesa.”
- Backend:
- Generates an access token
- Calls STK Push API
- Payment request sent to the user
No Authorization API = No payment flow
Internal SEO Linking Strategy
To improve rankings, link this article to:
/mpesa-stk-push-integration-kenya/c2b-mpesa-api-guide/b2c-mpesa-disbursement-kenya
FAQs: Authorization API (Access Token)
1. What is the Authorization API in M-Pesa?
It generates an access token used to authenticate API calls.
2. How long does an access token last?
3600 seconds (1 hour).
3. Can I generate multiple tokens?
Yes, but each new token invalidates the previous one.
4. What happens if my token expires?
All API calls will fail until you generate a new one.
5. Do I need a token for every API request?
Yes, but you can reuse the same token until expiry.
6. Is the Authorization API required for all Daraja APIs?
Yes, it is mandatory for every request.
Conclusion: The Gateway to M-Pesa Integration
The Authorization API is the backbone of any M-Pesa integration website Kenya project. It ensures secure communication between your system and Safaricom’s infrastructure.
Once you master:
- Token generation
- Authentication flow
- Security practices
You unlock the full power of M-Pesa APIs.
Related Articles
Continue reading with these related posts

How to Integrate M-Pesa on Your Website in Kenya: Powerful Beginner’s Guide to Daraja APIs (2026 Edition)
Learn how to set up M-Pesa integration website Kenya using Safaricom Daraja APIs. Full beginner-frie...
Read More
How Churches in Kenya Can Accept Tithes and Offerings Online
Simple, practical ways to set up secure and convenient church online giving in Kenya. Introduction T...
Read More
E-Commerce Website Cost in Kenya: Honest Pricing Breakdown
If you’ve Googled ‘how much does an e-commerce website cost in Kenya’ and got vagu...
Read MoreStay Updated
Get the latest insights delivered straight to your inbox. No spam, just valuable content.
Join our newsletter for regular updates
