Git Product home page Git Product logo

payhero-android-mpesa's Introduction

Payhero Android MPESA Library 

Android MPESA library to request STK Push using MPESA Daraja API.

Screenshots

 

(Please note that this library is still under development,Feel free to contact me personally if you meet any challenge,Thanks)

Sample of Implementation can be found here:

https://github.com/bensalcie/Trivia-Money

How to use the library

Step 1. Add the JitPack repository to your build file

Add it in your root build.gradle at the end of repositories:

  allprojects {
    repositories {
      ...
      maven { url 'https://jitpack.io' }
    }
  }

Step 2. Add the dependency

    dependencies {
            implementation 'com.squareup.retrofit2:retrofit:2.5.0'
            implementation 'com.github.bensalcie:payhero-android-mpesa:0.1.6'
    }

Step 3. Add this in onCreate() method.

     private var mApiClient: DarajaApiClient? = null //Intitialization before on create

         mApiClient = DarajaApiClient(
           "xxxconsumerkeyxxxxx",
           "xxxxxconsumersecretxxxx",
           Environment.SANDBOX
       )
       //use Environment.PRODUCTION when on production
     //get consumerkey and secret from https://developer.safaricom.co.ke/user/me/apps
         mApiClient!!.setIsDebug(true) //Set True to enable logging, false to disable.
         getAccessToken()//make request availabe and ready for processing.

Step 4.Define access token method.

    //Access token Method being called.
     private fun getAccessToken() {
     mApiClient!!.setGetAccessToken(true)
     mApiClient!!.mpesaService()!!.getAccessToken().enqueue(object : Callback<AccessToken> {
     override fun onResponse(call: Call<AccessToken?>, response: Response<AccessToken>) {
     if (response.isSuccessful) {
          mApiClient!!.setAuthToken(response.body()?.accessToken)
        }
          }
          override fun onFailure(call: Call<AccessToken?>, t: Throwable) {}
      })
        }

Step 5. Initiate STK Push

   btnDeposit.setOnClickListener {
              val amount = etAmount.text.toString()
              val phone =etPhone.text.toString()
                  if (amount.isNotEmpty() && phone.isNotEmpty()) {
                          btnDeposit.text = getString(R.string.processing)
                      performSTKPush(phone, amount)
                  } else {
                      etPhone.error = getString(R.string.errorm)
                      etAmount.error = getString(R.string.errorm)
                  }
              }
    private fun performSTKPush(amount: String, phone_number: String) {
          //Handle progresss here
    //credentials here are test credentials
          val timestamp = Utils.getTimestamp()
          val stkPush = STKPush("acc ref",amount,"business number","callback url",
              Utils.sanitizePhoneNumber(phone_number)!!,"business number",Utils.getPassword("business number", 
        "passkey", timestamp!!)!!
              , Utils.sanitizePhoneNumber(phone_number)!!,timestamp,"Trans. desc",Environment.TransactionType.CustomerPayBillOnline)
          mApiClient!!.setGetAccessToken(false)
           mApiClient!!.mpesaService()!!.sendPush(stkPush).enqueue(object : Callback<STKResponse> {
            override fun onResponse(call: Call<STKResponse>, response: Response<STKResponse>) {
                mProgressDialog!!.dismiss()
                try {
                    if (response.isSuccessful) {
                     if (response.body() != null) {
                    Log.d("PAYMENTS", "onResponse: Time to process, confirm etc : "+response.body().component1());
                      //handle response here
                      //response contains CheckoutRequestID,CustomerMessage,MerchantRequestID,ResponseCode,ResponseDescription
                          }
                   
                    } else {
                        //Timber.e("Response %s", response.errorBody()!!.string())
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }

            override fun onFailure(call: Call<STKResponse>, t: Throwable) {
                //mProgressDialog!!.dismiss()
                //Timber.e(t)
            }
        })
      }
      

Buy Me A Coffee

See Real Demo Here

payhero-android-mpesa's People

Contributors

bensalcie avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.