accessToken static method
Retrieves an access token from the M-Pesa Daraja API for authentication.
Returns the access token as a String if the request is successful, otherwise returns null.
Throws an Exception with the error message if the request fails.
Implementation
/*This function retrieves an access token from the M-Pesa Daraja API for authentication purposes. Here's a breakdown of what the function does:
It encodes the consumer key and consumer secret using base64 encoding.
Prepares the headers for the HTTP request, including the encoded credentials.
Defines the URL to request the access token from the API.
Sends a GET request to the token URL with the prepared headers.
Decodes the response body into a map.
If the response status code is not 200, it throws an exception with the error message received.
If the response status code is 200, it returns the access token from the response body.
You can use this function to obtain an access token required for subsequent requests to the M-Pesa Daraja API. */
static Future<String?> accessToken() async {
// Encode consumer key and consumer secret using base64
String credentials =
base64.encode(utf8.encode('$_consumerKey:$_consumerSecret'));
// Prepare headers for the HTTP request
Map<String, String> headers = {
'Authorization': 'Basic $credentials',
'Content-Type': 'application/json'
};
// Set the URL to request the access token
String tokenUrl =
'https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials';
// Send a GET request to the token URL with the headers
final response = await http.get(Uri.parse(tokenUrl), headers: headers);
// Decode the response body into a map
Map<String, dynamic> responseData = json.decode(response.body);
// Check if the response status code is not 200 (OK)
if (response.statusCode != 200) {
throw Exception(responseData['errorMessage']);
}
// Return the access token if the response status code is 200
return response.statusCode != 200 ? null : responseData['access_token'];
}