android_mpesa_stk
Android Mpesa library to initiate stk push
MPESA just unveiled their new API, Daraja 2.0. It has been hailed as the height of developer heaven with its crisp clear structure, solid security and great syntax. So this library is a wrapper around the API to help you intiate MPESA STK push easily on your Android apps.
Download
Gradle
Add the codes below to your root build.gradle
file:
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
And add the dependency below to your module‘s build.gradle
file:
dependencies {
implementation 'com.github.Carrieukie:android_mpesa_stk:v1.0.2-beta'
}
Usage
Copy this fuction into your Activity
/Fragment
/Composable
and replace with your credentials.
private fun sendStkPush(amount: String, phoneNumber: String) {
val stkPushRequest = STKPushRequest(
businessShortCode = BUSINESS_SHORT_CODE,
password = getPassword(BUSINESS_SHORT_CODE, PASS_KEY, timestamp),
timestamp = timestamp,
transactionType = "CustomerPayBillOnline",
amount = amount,
partyA = sanitizePhoneNumber(phoneNumber),
partyB = BUSINESS_SHORT_CODE,
phoneNumber = sanitizePhoneNumber(phoneNumber),
callBackURL = CALLBACKURL,
accountReference = "Dlight", // Account reference
transactionDesc = "Dlight STK PUSH" // Transaction description
)
val darajaDriver = DarajaDriver(
consumerKey = BuildConfig.CONSUMER_KEY,
consumerSecret = BuildConfig.CONSUMER_SECRET
)
lifecycleScope.launch {
darajaDriver.performStkPush(stkPushRequest).collectLatest { result ->
when (result) {
is Resource.Error -> {
Toast.makeText(
applicationContext,
"${result.errorMessage ?: result.error?.message}",
Toast.LENGTH_SHORT
).show()
}
is Resource.Loading -> {
Toast.makeText(applicationContext, "Loading...", Toast.LENGTH_SHORT).show()
}
is Resource.Success -> {
Toast.makeText(
applicationContext,
"${result.data?.otpResult?.customerMessage}",
Toast.LENGTH_SHORT
).show()
}
}
}
}
}
License
Copyright 2022 Carrieukie
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.