Skip to content

MPESA Express

Juma Allan edited this page Apr 24, 2018 · 7 revisions

Simple use cases with MPESA Express (STKPush) will look something like this:

//For Sandbox Mode
Daraja daraja = Daraja.with(CONSUMER_KEY, CONSUMER_SECRET, new DarajaListener<AccessToken>() {
            @Override
            public void onResult(@NonNull AccessToken accessToken) {
                Log.i(MainActivity.this.getClass().getSimpleName(), accessToken.getAccess_token());
            }

            @Override
            public void onError(String error) {
                Log.e(MainActivity.this.getClass().getSimpleName(), error);
            }
        });

//For Production Mode
Daraja daraja = Daraja.with(CONSUMER_KEY, CONSUMER_SECRET, Env.PRODUCTION, new DarajaListener<AccessToken>() {
            @Override
            public void onResult(@NonNull AccessToken accessToken) {
                Log.i(MainActivity.this.getClass().getSimpleName(), accessToken.getAccess_token());
            }

            @Override
            public void onError(String error) {
                Log.e(MainActivity.this.getClass().getSimpleName(), error);
            }
        });

Notice the Env.SANDBOX is OPTIONAL. Daraja uses SANDBOX as the Default Mode. To switch to Production Mode, pass the Env.PRODUCTION and let Daraja do the rest!

This initializes Daraja and also generates a Token to be used for further requests. This should be done in your Application onCreate Method, to allow Daraja generate the Authorization Token as early as possible.

With the Token generated, create a LNMExpress Object, to be able to pass it to the sendSTKPush method as shown below. Replace with actual values.

LNMExpress lnmExpress = new LNMExpress(
                "BUSINESS_SHORT_CODE",
                "PASS_KEY",
                "AMOUNT",
                "PARTY_A",
                "PARTY_B",
                "PHONE_NUMBER",
                "CALLBACK_URL",
                "ACCOUNT_REFERENCE",
                "TRANSACTION_DESCRIPTION"
        );

You can now request an STKPush with ease.Just call the sendSTKPush as shown here:

//For both Sandbox and Production Mode
button.setOnClickListener(v -> daraja.sendSTKPush(lnmExpress,
                new DarajaListener<LNMResult>() {
                    @Override
                    public void onResult(@NonNull LNMResult lnmResult) {
                        Log.i(MainActivity.this.getClass().getSimpleName(), lnmResult.ResponseDescription);
                    }

                    @Override
                    public void onError(String error) {
                        Log.i(MainActivity.this.getClass().getSimpleName(), error);
                    }
                }
        ));

This sanitizes all the data, as required by Safaricom before making a request for the STKPush. You only need to pass the parameters and Daraja will do the rest!

Lipa na M-Pesa Online Payment API

The following table highlights the requirements needed by Daraja, as described in the Safaricom Developer API Page

Name Description Parameter Type Possible Values
BusinessShortCode The organization shortcode used to receive the transaction Numeric Shortcode (6 digits)
Passkey Lipa Na Mpesa Online PassKey Alpha-Numeric
Amount The amount to be transacted Numeric 100
PartyA The entity sending the funds Numeric MSISDN (12 digits)
PartyB The organization receiving the funds Numeric Shortcode (6 digits)
PhoneNumber The MSISDN sending the funds Numeric MSISDN (12 digits)
CallBackURL Call Back URL URL https://ip or domain:port/path
AccountReference Account Reference Alpha-Numeric Any combinations of letters and numbers
TransactionDesc Description of the transaction String any string of less then 20 characters

Get the Pass Key Here : https://developer.safaricom.co.ke/test_credentials

Daraja Example

Make a simple Daraja request as shown in the code sample below. First, make sure your import these dependencies (or let Android Studio auto-import), and initialize a few configurations

import com.twigafoods.daraja.Daraja;
import com.twigafoods.daraja.DarajaListener;
import com.twigafoods.daraja.model.AccessToken;
import com.twigafoods.daraja.model.LNMExpress;
import com.twigafoods.daraja.model.LNMResult;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.editTextPhoneNumber)
    EditText editTextPhoneNumber;
    @BindView(R.id.sendButton)
    Button sendButton;

    //Declare Daraja :: Global Variable
    Daraja daraja;

    String phoneNumber;

Inside your onCreate Method, set up Initialize Daraja as shown below:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        //Init Daraja
        //TODO :: REPLACE WITH YOUR OWN CREDENTIALS  :: THIS IS SANDBOX DEMO
        daraja = Daraja.with("EG6TJgOCyuVGHKUeJs0uLXKsLCANRjbo", "4F3tAlRZ4OzNZt0Y", new DarajaListener<AccessToken>() {
            @Override
            public void onResult(@NonNull AccessToken accessToken) {
                Log.i(MainActivity.this.getClass().getSimpleName(), accessToken.getAccess_token());
                Toast.makeText(MainActivity.this, "TOKEN : " + accessToken.getAccess_token(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(String error) {
                Log.e(MainActivity.this.getClass().getSimpleName(), error);
            }
        });

Make the Daraja STKPush request with ease now:

//TODO :: THIS IS A SIMPLE WAY TO DO ALL THINGS AT ONCE!!! DON'T DO THIS :)
        sendButton.setOnClickListener(v -> {

            //Get Phone Number from User Input
            phoneNumber = editTextPhoneNumber.getText().toString().trim();

            if (TextUtils.isEmpty(phoneNumber)) {
                editTextPhoneNumber.setError("Please Provide a Phone Number");
                return;
            }

            //TODO :: REPLACE WITH YOUR OWN CREDENTIALS  :: THIS IS SANDBOX DEMO
            LNMExpress lnmExpress = new LNMExpress(
                    "174379",
                    "bfb279f9aa9bdbcf158e97dd71a467cd2e0c893059b10f78e6b72ada1ed2c919",  //https://developer.safaricom.co.ke/test_credentials
                    "100",
                    "254708374149",
                    "174379",
                    phoneNumber,
                    "http://mycallbackurl.com/checkout.php",
                    "001ABC",
                    "Goods Payment"
            );

            daraja.sendSTKPush(lnmExpress,
                    new DarajaListener<LNMResult>() {
                        @Override
                        public void onResult(@NonNull LNMResult lnmResult) {
                            Log.i(MainActivity.this.getClass().getSimpleName(), lnmResult.ResponseDescription);
                        }

                        @Override
                        public void onError(String error) {
                            Log.i(MainActivity.this.getClass().getSimpleName(), error);
                        }
                    }
            );
        });

The whole process looks similar to these screenshots:

Clone this wiki locally