Payment Plugins

How to integrate Mpesa API with android

Mobile app developers and owners who operate their mobile apps on android OS - based phones and want to use Mpesa for their payments need to be assisted on  How to integrate Mpesa API with android. In this article, I declare to help all interested people, mobile app owners and developers, to add Mpesa payments on their android mobile apps.

Hi there, I will help you integrate MPESA Payment method on your Mobile Apps and Websites at very affordable fees. Just WhatsApp me on +254706745202

What do I mean by How to integrate Mpesa API with android?

To integrate is to form part of an existing program or system or simply mobile app. The mobile app, in this case, exists and operated well but needs to have Mpesa payment method added for either internal payments (Mpesa C2B) or External Payments (Mpesa B2C and B2B).

Let us dive in to How to integrate Mpesa API with android.

The first thing you want to know is the type of Mpesa API that you want to integrate.

It could be:

A). Mpesa C2B general,

B). Mpesa express (STK PUSH),

C). Mpesa B2B.

How to integrate Mpesa C2B API with android

The first and most common Mpesa API that people need guide on how to integrate is the C2B api which I will address in this guide. Other API will come later on other articles to be linked on this one.

Since Mpesa C2B and Mpesa Express APIs are related, I will address then together.

 C2B is very simple. In your app, where all conditions meet for payments to be made, instruct users or customers to make payment via Mpesa by following the Lipa na Mpesa ==> Paybill way and provide their unique account identifier on the payment process as well as the specific amount to be paid. When they follow these steps, everything else will run smoothly.

 When your customers make payment, their accounts should be credited automatically. To make this possible, you need to register the Mpesa C2B urls (confirmation and Validation) with your Paybill or Till number. This is actually the C2B general Integration. That is, to display the Lipa na Mpesa payment process with the unique account for the user or customer or order ID to be paid and the specific amount to be paid.

 How to integrate Mpesa Express API with android (The Lipa na Mpesa online API or STK push).

The desired result of an Mpesa express API integration in android is that; when a user clicks to make payment, a pop up appears asking a user to simply enter a PIN and the rest of the process is automatically handled by the Mobile app backend to complete transaction and update the necessary processes as per written code logic.

 

Mpesa stk push intergration on android
Mpesa stk push intergration on android

 Fig 1: A diagram that demonstrates the desired way of an Mpesa Express integration. An STK push popup looks like this when integrated into any application.

 Preliminary requires for Mpesa Express API integration to android

 1. An Mpesa Paybill or Till Number (Apply this at any safaricom shop or write an email to Mpesa Business).

2. An Mpesa portal admin account (When you get your Paybill or Till number, apply an admin account from Mpesa Business).

3. A daraja account (Get this on developer.safaricom.co.ke).

4. Knowledge and skills in a major programming language and platform (In this case is Java and android studio).

5. Your willingness to complete the integration process. Can be long at times and full of challenges. So be patient enough to complete.

 

To make everything simple, I developed an Mpesa API integration assistant which solves the hectic process of integrating applications with Mpesa. Look at it here: Mpesa API Integration Assistant and how to use it here: How to use the Mpesa C2B API Integration Assistant

 The above is with no MPESA Api integration jargon and can help non-programmers as well as programmers to easily add Mpesa payment method.

Below this sentence is a jargon full guide on those who want to learn how to hardcode a solution that Integrates Mpesa Express on their Mobile apps. It is best for skilled and experienced android developers.

Step 1: Import your android project to your android studio (skip this step if your project is already on android studio).

Step 2: Open the Build.gradle module app file and add the following dependencies:

{source}
implementation 'com.jakewharton:butterknife:10.1.0'
annotationProcessor 'com.jakewharton:butterknife-compiler:10.1.0'
implementation 'com.jakewharton.timber:timber:4.7.1'

implementation 'com.github.jumadeveloper:networkmanager:0.0.2'

implementation 'cn.pedant.sweetalert:library:1.3'

implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'

implementation 'com.squareup.okhttp3:okhttp:3.12.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.12.0'

implementation 'com.google.code.gson:gson:2.8.5'
implementation 'com.squareup.okio:okio:2.1.0'
{/source}

Note: These dependencies are key to the working of your Mpesa STK push.

You will need to sync your gradle to your project after adding these dependencies.

Step 3: Create a new package and name it brian or whichever name you want. Just right click on your project, click new package and enter the name you want. Mine is brian.

Step 4: Inside this package, create a new java class and name it AccessToken and another one and name it STKPush. So you have two java classes under brian package.

The access token java class will carry our Mpesa access token code for authorization purposes. In short, you must be authorized by Mpesa to have your application community to its services and the code is as follows:

{source}
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class AccessToken {
@SerializedName("access_token")
@Expose
public String accessToken;
@SerializedName("expires_in")
@Expose
private String expiresIn;

public AccessToken(String accessToken, String expiresIn) {
this.accessToken = accessToken;
this.expiresIn = expiresIn;
}
}

{/source}

 

 For the STKPush java class, you will need the code with data that needed to execure a successful SIM TOOL KIT popup window. So, we will supply this data.

To get the data that Mpesa requires to successfully PUSH A POPUP on a customer's toolkit, go to developer.safaricom.co.ke and navigate to the APIs and then to Mpesa Express API and finally to Mpesa Express Request.

Scroll down and you will see the the request body Schema for Mpesa Express request as follows:
  

 "BusinessShortCode": "",
      "Password": "",
      "Timestamp": "",
      "TransactionType": "CustomerPayBillOnline",
      "Amount": "",
      "PartyA": "",
      "PartyB": "",
      "PhoneNumber": "",
      "CallBackURL": "",
      "AccountReference": "",
      "TransactionDesc": ""
    }

 

This is the data that Mpesa Express API is waiting to run a POP on the customer's STK.

With this in copy, go to http://www.jsonschema2pojo.org and generate plain java objects using this Json Schema.

Copy the resultant contents of the above view to your STKPush java class as follows:

import com.google.gson.annotations.SerializedName;

public class STKPush {
    @SerializedName("BusinessShortCode")
    private String businessShortCode;
    @SerializedName("Password")
    private String password;
    @SerializedName("Timestamp")
    private String timestamp;
    @SerializedName("TransactionType")
    private String transactionType;
    @SerializedName("Amount")
    private String amount;
    @SerializedName("PartyA")
    private String partyA;
    @SerializedName("PartyB")
    private String partyB;
    @SerializedName("PhoneNumber")
    private String phoneNumber;
    @SerializedName("CallBackURL")
    private String callBackURL;
    @SerializedName("AccountReference")
    private String accountReference;
    @SerializedName("TransactionDesc")
    private String transactionDesc;

    public STKPush(String businessShortCode, String password, String timestamp, String transactionType,
                   String amount, String partyA, String partyB, String phoneNumber, String callBackURL,
                   String accountReference, String transactionDesc) {
        this.businessShortCode = businessShortCode;
        this.password = password;
        this.timestamp = timestamp;
        this.transactionType = transactionType;
        this.amount = amount;
        this.partyA = partyA;
        this.partyB = partyB;
        this.phoneNumber = phoneNumber;
        this.callBackURL = callBackURL;
        this.accountReference = accountReference;
        this.transactionDesc = transactionDesc;
    }
}

Step 4: It is now time to add our Daraja APP key and secret. Open the gradle.properties of your android studio project and add the following code the very bottom of all apps:

Please recall to replace the key and secret (the words between the double quotes) to your own Daraja APP key and secret.

DARAJA_CONSUMER_KEY="add_consumer_key_here"
DARAJA_CONSUMER_SECRET="add_consumer_secret_here"

 

Step 5: The above step necessitates that we add the following BuildTypes on our gradle.build app module:

buildTypes.each {    it.buildConfigField 'String', 'CONSUMER_KEY',DARAJA_CONSUMER_KEY
    it.buildConfigField 'String', 'CONSUMER_SECRET', DARAJA_CONSUMER_SECRET
}

 

SteP 6: Create Intercetors for access token and Authorization.