Integrate PayUMoney Payments In Android Application

Posted By : Keshav Gupta | 04-Dec-2017

Here are steps to integrate in application:

Step1: Integrate PayUmoney sdk first.So add following dependencies in app/build.gradle.

/*   dependencies for Payumoney intergration*/
    compile('com.payumoney.sdkui:plug-n-play:1.0.0') {
        transitive = true;
        exclude module: 'payumoney-sdk'
    }
    compile 'com.payumoney.core:payumoney-sdk:7.0.1'

Step2: Create a test account on test url of payumoney for sandbox account and create another account for production on payumoney production site.Here are site url for testing and production respectively.Register yourself and get MerchantId,key and salt respectively.

//  sandbox account
https://test.payumoney.com/

//production account
https://www.payumoney.com/

Step3:Now create a enum class named as AppEnvironment in which we will define two enum values SANDBOX and PRODUCTION and will have some abstract methods declared inside it such that enum can override these abstract methods.We will define methods like such they will return MerchantId,key,salt,surl and furl values based on set environment in application.So code for this class will be like.Please update fields according to your PayUmoney credentials.

package com.eimarsmlm.payumoneycontroller;


/**
 * Created by Some on 04/12/17.
 */
public enum AppEnvironment {

    SANDBOX {
        @Override
        public String merchant_Key() {
            return "aYY2VbER";
        }

        @Override
        public String merchant_ID() {
            return "4949956";
        }

        @Override
        public String furl() {
            return "https://www.payumoney.com/mobileapp/payumoney/failure.php";
        }

        @Override
        public String surl() {
            return "https://www.payumoney.com/mobileapp/payumoney/success.php";
        }

        @Override
        public String salt() {
            return "JadHizxIqn";
        }

        @Override
        public boolean debug() {
            return true;
        }
    },
    PRODUCTION {
        @Override
        public String merchant_Key() {
            return "PHMg2iSs";
        }

        @Override
        public String merchant_ID() {
            return "0985619";
        }

        @Override
        public String furl() {
            return "https://www.payumoney.com/mobileapp/payumoney/failure.php";
        }

        @Override
        public String surl() {
            return "https://www.payumoney.com/mobileapp/payumoney/success.php";
        }

        @Override
        public String salt() {
            return "je2PoYUI89";
        }

        @Override
        public boolean debug() {
            return false;
        }
    };

    public abstract String merchant_Key();

    public abstract String merchant_ID();

    public abstract String furl();

    public abstract String surl();

    public abstract String salt();

    public abstract boolean debug();

}

Step4:Create a application class named as MyApplication which will extend Application and set appEnvironment to SANDBOX.Code will be like:

package com.eimarsmlm.utilities.utils;

import android.app.Application;
import android.content.Context;

import com.eimarsmlm.payumoneycontroller.AppEnvironment;

/**
 * Created by keshav on 04/12/17.
 */

public class MyApplication extends Application {
    private AppEnvironment appEnvironment;
    @Override
    public void onCreate() {
        super.onCreate();
        
     appEnvironment=AppEnvironment.SANDBOX;
    }

    public AppEnvironment getAppEnvironment() {
        return appEnvironment;
    }

    public void setAppEnvironment(AppEnvironment appEnvironment) {
        this.appEnvironment = appEnvironment;
    }

    }

 Step5: First we will need to generate server side hash to process further.We will create a class named as PaymentActivity which will be having a button to launch PayUmoney.Now we will set hash as merchant hash in PayuMoney params and initiate the payment flow on button click.Code will be like this.

package com.eimarsmlm.payumoneycontroller;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.eimarsmlm.R;
import com.eimarsmlm.utilities.customViews.CustomButton;
import com.eimarsmlm.utilities.utils.Logger;
import com.eimarsmlm.utilities.utils.MyApplication;
import com.eimarsmlm.utilities.utils.UtilityMethods;
import com.payumoney.core.PayUmoneyConfig;
import com.payumoney.core.PayUmoneyConstants;
import com.payumoney.core.PayUmoneySdkInitializer;
import com.payumoney.core.entity.TransactionResponse;
import com.payumoney.sdkui.ui.utils.PayUmoneyFlowManager;
import com.payumoney.sdkui.ui.utils.ResultModel;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by keshav on 04/12/17.
 */

public class PaymentActivity1 extends AppCompatActivity{
    @BindView(R.id.btn_Pay) CustomButton btnPay;
    private PayUmoneySdkInitializer.PaymentParam mPaymentParams;
    private AppCompatActivity activity;
    private double amountPacakges;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_layout_payment);
        ButterKnife.bind(this);
        init();
    }

    private void init()
    {
        activity=PaymentActivity1.this;
    }
    
    private PayUmoneySdkInitializer.PaymentParam calculateServerSideHashAndInitiatePayment1(final PayUmoneySdkInitializer.PaymentParam paymentParam) {

        StringBuilder stringBuilder = new StringBuilder();
        HashMap<String, String> params = paymentParam.getParams();
        stringBuilder.append(params.get(PayUmoneyConstants.KEY) + "|");
        stringBuilder.append(params.get(PayUmoneyConstants.TXNID) + "|");
        stringBuilder.append(params.get(PayUmoneyConstants.AMOUNT) + "|");
        stringBuilder.append(params.get(PayUmoneyConstants.PRODUCT_INFO) + "|");
        stringBuilder.append(params.get(PayUmoneyConstants.FIRSTNAME) + "|");
        stringBuilder.append(params.get(PayUmoneyConstants.EMAIL) + "|");
        stringBuilder.append(params.get(PayUmoneyConstants.UDF1) + "|");
        stringBuilder.append(params.get(PayUmoneyConstants.UDF2) + "|");
        stringBuilder.append(params.get(PayUmoneyConstants.UDF3) + "|");
        stringBuilder.append(params.get(PayUmoneyConstants.UDF4) + "|");
        stringBuilder.append(params.get(PayUmoneyConstants.UDF5) + "||||||");
        AppEnvironment appEnvironment = ((MyApplication) getApplication()).getAppEnvironment();
        stringBuilder.append(appEnvironment.salt());
        Logger.LogError("hashsequence",stringBuilder.toString());
        String hash = hashCal("SHA-512",stringBuilder.toString());
      /*  AppEnvironment appEnvironment = ((BaseApplication) getApplication()).getAppEnvironment();
        stringBuilder.append(appEnvironment.salt());

        //String hash = hashCal(stringBuilder.toString());*/
        paymentParam.setMerchantHash(hash);

        return paymentParam;
    }
// method to create server side hash 
    public static String hashCal(String type, String hashString) {
        StringBuilder hash = new StringBuilder();
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance(type);
            messageDigest.update(hashString.getBytes());
            byte[] mdbytes = messageDigest.digest();
            for (byte hashByte : mdbytes) {
                hash.append(Integer.toString((hashByte & 0xff) + 0x100, 16).substring(1));
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return hash.toString();
    }
    @OnClick({R.id.btn_Pay})
    public void onClick(View view) {
        switch (view.getId())
        {
            case R.id.btn_Pay:
              //  btnPay.setEnabled(false);
                if (UtilityMethods.isInternetAvailable(activity)) {
                    launchPayUMoneyFlow();
                } else {
                    Toast.makeText(activity, R.string.internetalert, Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }
    
    private void launchPayUMoneyFlow() {

        PayUmoneyConfig payUmoneyConfig = PayUmoneyConfig.getInstance();

        //Use this to set your custom text on result screen button
       // payUmoneyConfig.setDoneButtonText(((EditText) findViewById(R.id.status_page_et)).getText().toString());

        //Use this to set your custom title for the activity
       //payUmoneyConfig.setPayUmoneyActivityTitle(((EditText) findViewById(R.id.activity_title_et)).getText().toString());

        PayUmoneySdkInitializer.PaymentParam.Builder builder = new PayUmoneySdkInitializer.PaymentParam.Builder();

        double amount = 0;
        try {
            amount = Double.parseDouble("20");

        } catch (Exception e) {
            e.printStackTrace();
        }
        String txnId = System.currentTimeMillis() + "";
        String phone = "987654321";
        String productName ="product name";
        String firstName = "marcony";
        String email = "[email protected]";
        String udf1 = "";
        String udf2 = "";
        String udf3 = "";
        String udf4 = "";
        String udf5 = "";
        String udf6 = "";
        String udf7 = "";
        String udf8 = "";
        String udf9 = "";
        String udf10 = "";

        AppEnvironment appEnvironment = ((MyApplication) getApplication()).getAppEnvironment();
        builder.setAmount(amount)
                .setTxnId(txnId)
                .setPhone(phone)
                .setProductName(productName)
                .setFirstName(firstName)
                .setEmail(email)
                .setsUrl(appEnvironment.surl())
                .setfUrl(appEnvironment.furl())
                .setUdf1(udf1)
                .setUdf2(udf2)
                .setUdf3(udf3)
                .setUdf4(udf4)
                .setUdf5(udf5)
                .setUdf6(udf6)
                .setUdf7(udf7)
                .setUdf8(udf8)
                .setUdf9(udf9)
                .setUdf10(udf10)
                .setIsDebug(appEnvironment.debug())
                .setKey(appEnvironment.merchant_Key())
                .setMerchantId(appEnvironment.merchant_ID());

        try {
            mPaymentParams = builder.build();

            /*
            * Hash should always be generated from your server side.
            * */
           /* generateHashFromServer(mPaymentParams);*/

            /**
             * Do not use below code when going live
             * Below code is provided to generate hash from sdk.
             * It is recommended to generate hash from server side only.
             * */
            mPaymentParams = calculateServerSideHashAndInitiatePayment1(mPaymentParams);

            if (AppPreference.selectedTheme != -1) {
                PayUmoneyFlowManager.startPayUMoneyFlow(mPaymentParams,PaymentActivity1.this, AppPreference.selectedTheme,false);
            } else {
                PayUmoneyFlowManager.startPayUMoneyFlow(mPaymentParams,PaymentActivity1.this, R.style.AppTheme_default,false);
            }

        } catch (Exception e) {
            // some exception occurred
            Log.e("Message",e.getStackTrace().toString());
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
            btnPay.setEnabled(true);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // Result Code is -1 send from Payumoney activity
        Log.d("MainActivity", "request code " + requestCode + " resultcode " + resultCode);
        if (requestCode == PayUmoneyFlowManager.REQUEST_CODE_PAYMENT && resultCode == RESULT_OK && data !=
                null) {
            TransactionResponse transactionResponse = data.getParcelableExtra(PayUmoneyFlowManager
                    .INTENT_EXTRA_TRANSACTION_RESPONSE);

            ResultModel resultModel = data.getParcelableExtra(PayUmoneyFlowManager.ARG_RESULT);

            // Check which object is non-null
            if (transactionResponse != null && transactionResponse.getPayuResponse() != null) {
                if (transactionResponse.getTransactionStatus().equals(TransactionResponse.TransactionStatus.SUCCESSFUL)) {
                    //Success Transaction

                } else {
                    //Failure Transaction
                }

                // Response from Payumoney
                String payuResponse = transactionResponse.getPayuResponse();

                // Response from SURl and FURL
                String merchantResponse = transactionResponse.getTransactionDetails();

                new AlertDialog.Builder(this)
                        .setCancelable(false)
                        .setMessage("Payu's Data : " + payuResponse + "\n\n\n Merchant's Data: " + merchantResponse)
                        .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                dialog.dismiss();
                            }
                        }).show();

            } else if (resultModel != null && resultModel.getError() != null) {
                Log.d("PAYU", "Error response : " + resultModel.getError().getTransactionResponse());
            } else {
                Log.d("PAYU", "Both objects are null!");
            }
        }
    }
    
}

Step6: That's all you have to do for PayUmoney integration.

 

 

 

 

About Author

Author Image
Keshav Gupta

Keshav Gupta is Android Developer in Oodles, he always look forward for new tasks and new things to learn more.

Request for Proposal

Name is required

Comment is required

Sending message..