mSTKRequest method
Future<Map<String, String> >
mSTKRequest({
- required String mBusinessShortCode,
- required String nPassKey,
- required String mTransactionType,
- required String mTimeStamp,
- required double mAmount,
- required String partyA,
- required String partyB,
- required String mPhoneNumber,
- required Uri mCallBackURL,
- required String mAccountReference,
- String? mTransactionDesc,
Implementation
Future<Map<String, String>> mSTKRequest(
{required String mBusinessShortCode,
required String nPassKey,
required String mTransactionType,
required String mTimeStamp,
required double mAmount,
required String partyA,
required String partyB,
required String mPhoneNumber,
required Uri mCallBackURL,
required String mAccountReference,
String? mTransactionDesc}) async {
///set access token before starting the party.
await setAccessToken();
///create the payload that should not be changed until the request is done.
final stkPushPayload = {
"BusinessShortCode": mBusinessShortCode,
"Password": generatePassword(
mShortCode: mBusinessShortCode,
mPassKey: nPassKey,
actualTimeStamp: mTimeStamp),
"Timestamp": mTimeStamp,
"Amount": mAmount,
"PartyA": partyA,
"PartyB": partyB,
"PhoneNumber": mPhoneNumber,
"CallBackURL": mCallBackURL.toString(),
"AccountReference": mAccountReference,
"TransactionDesc": mTransactionDesc == null? "" : mTransactionDesc,
"TransactionType": mTransactionType
};
final Map<String, String> result = new Map<String, String>();
///Actual request starts here.
HttpClient client = new HttpClient();
return await client.postUrl(generateSTKPushUrl()).then((req) async {
req.headers.add("Content-Type", "application/json");
req.headers.add("Authorization", "Bearer " + mAccessToken);
req.write(jsonEncode(stkPushPayload)); // write is non-blocking
HttpClientResponse res = await req.close();
await res.transform(utf8.decoder).forEach((bodyString) {
dynamic mJsonDecodeBody = jsonDecode(bodyString);
if (res.statusCode == 200) {
result["MerchantRequestID"] =
mJsonDecodeBody["MerchantRequestID"].toString();
result["CheckoutRequestID"] =
mJsonDecodeBody["CheckoutRequestID"].toString();
result["ResponseCode"] = mJsonDecodeBody["ResponseCode"].toString();
result["ResponseDescription"] =
mJsonDecodeBody["ResponseDescription"].toString();
result["CustomerMessage"] =
mJsonDecodeBody["CustomerMessage"].toString();
} else {
result["requestId"] = mJsonDecodeBody["requestId"].toString();
result["errorCode"] = mJsonDecodeBody["errorCode"].toString();
result["errorMessage"] = mJsonDecodeBody["errorMessage"].toString();
}
});
return result;
}).catchError((error) {
///the user should expect anything here, from network errors to
///timeout issues or whatever an http error is!
result["error"] = error.toString();
return result;
});
}