The following two tabs change content below.
Hi, I have written and developed this site to share my experience and ideas with other colleagues. I also started to prepare interview questions and answers for job seekers. I hope it will help you a lot.

From last 2-3 days I was facing problem to integrate with PayU payment gateway. But finally I have achieved it successfully and solution I would like to share with you also may be this will help to someone.

Prerequisite to start with PayU payment gateway

Download full application code 

1. Have you sign-up on PayU? if no then please try to sign-up as merchant using PayU website . Else login to your PayU merchant account and you will get MID,Key,Salt value. These are the credential which is required to integrate Payment Gateway.

Note: Don’t share MID/KEY/Salt value with anyone

2. Create a sample project or use your existing android project and add the following dependency.

compile 'com.payumoney.sdkui:plug-n-play:1.0.0'

3. If you would like to add Crashlytics then please add below dependency

While Crashlytics gives you powerful crash reporting, with one additional click you can enable real-time analytics that help you understand what’s happening in your app. Fabric’s analytics engine provides insights into your core goals, such as growth, retention, and engagement

compile('com.crashlytics.sdk.android:crashlytics:2.6.8@aar') {
    transitive = true;
}

How to integrate PayU payment gateway with Android ?

As we mention need to setup some dependency so I am sharing full build.gradle(app) code here:

 

buildscript {
    repositories {
        maven { url 'https://maven.fabric.io/public' }
    }

    dependencies {
        classpath 'io.fabric.tools:gradle:1.+'
    }
}
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'
android {
    compileSdkVersion 25
    buildToolsVersion "26.0.0"
    defaultConfig {
        applicationId "com.kpblogs.payuintegration"
        minSdkVersion 17
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }

    }
}
repositories{
    maven { url 'https://maven.fabric.io/public' }
}
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.payumoney.sdkui:plug-n-play:1.0.0'
    compile('com.crashlytics.sdk.android:crashlytics:2.6.8@aar') {
        transitive = true;
    }
    testCompile 'junit:junit:4.12'
}

For Crashlytics we need to give specific repository URL also as below build.gradle (Project file)

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
        maven { url 'https://maven.fabric.io/public' }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
        classpath 'io.fabric.tools:gradle:1.+'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Define Internet permission and Crashlytics API_KEY in the Manifest file :

 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.kpblogs.payuintegration">
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        android:name=".Application"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".TestActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <meta-data
            android:name="io.fabric.ApiKey"
            android:value="API_KEY_Value" />

    </application>

</manifest>

 

So now its time to setup PayU credential so create a Java ENUM (Environment.java) file with both Test/Live environment:

package com.kpblogs.payuintegration;

/**
 * Created by khushvinder
 */
public enum Environment {

    TEST {
        @Override
        public String merchant_Key() {
            return "LLKwG0";
        }

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

        @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 boolean debug() {
            return true;
        }
    },
    PRODUCTION {
        @Override
        public String merchant_Key() {
            return "O15vkB";
        }

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

        @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 boolean debug() {
            return false;
        }
    };

    public abstract String merchant_Key();

    public abstract String merchant_ID();

    public abstract String furl();

    public abstract String surl();
    
    public abstract boolean debug();

}

 

Using application class we change the Environment from Test to Live/Production or Live to Test. If you want to create UI you also do this by creating some UI control on activity layout. Application.Java

package com.kpblogs.payuintegration;

/**
 * Created by khushvinder
 */
public class Application extends android.app.Application {

    Environment environment;

    @Override
    public void onCreate() {
        super.onCreate();
        environment = Environment.TEST;
    }

    public Environment getEnvironment() {
        return environment;
    }

    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }
}

 

So now PayU credential are set and its time to pass extra information like Transaction ID, Product Info, Price, Phone Number etc to server to get MD5 hashcode.

Calculate Server-Side Hash

The only server side change required while integrating PayUmoney Android SDK is generating a hash parameter for both the payment request & response.

A hash is an encrypted value (checksum) that must be sent by the merchant in a payment request that is then sent back by PayUmoney in the payment response. A hash is used to protect transactions against “man in the middle” attacks.

I am attaching the server side code to get the Hash Code: getHashCode.php

<?php
 
function getHashes($txnid, $amount, $productinfo, $firstname, $email, $user_credentials, $udf1, $udf2, $udf3, $udf4, $udf5)
{
 // $firstname, $email can be "", i.e empty string if needed. Same should be sent to PayU server (in request params) also.
 $key = 'LLKwG0';
 $salt = 'qauKbEAJ';
 
 $payhash_str = $key . '|' . checkNull($txnid) . '|' .checkNull($amount) . '|' .checkNull($productinfo) . '|' . checkNull($firstname) . '|' . checkNull($email) . '|' . checkNull($udf1) . '|' . checkNull($udf2) . '|' . checkNull($udf3) . '|' . checkNull($udf4) . '|' . checkNull($udf5) . '||||||' . $salt;
 $paymentHash = strtolower(hash('sha512', $payhash_str));
 $arr['payment_hash'] = $paymentHash;
 
 $cmnNameMerchantCodes = 'get_merchant_ibibo_codes';
 $merchantCodesHash_str = $key . '|' . $cmnNameMerchantCodes . '|default|' . $salt ;
 $merchantCodesHash = strtolower(hash('sha512', $merchantCodesHash_str));
 $arr['get_merchant_ibibo_codes_hash'] = $merchantCodesHash;
 
 $cmnMobileSdk = 'vas_for_mobile_sdk';
 $mobileSdk_str = $key . '|' . $cmnMobileSdk . '|default|' . $salt;
 $mobileSdk = strtolower(hash('sha512', $mobileSdk_str));
 $arr['vas_for_mobile_sdk_hash'] = $mobileSdk;
 
 $cmnPaymentRelatedDetailsForMobileSdk1 = 'payment_related_details_for_mobile_sdk';
 $detailsForMobileSdk_str1 = $key . '|' . $cmnPaymentRelatedDetailsForMobileSdk1 . '|default|' . $salt ;
 $detailsForMobileSdk1 = strtolower(hash('sha512', $detailsForMobileSdk_str1));
 $arr['payment_related_details_for_mobile_sdk_hash'] = $detailsForMobileSdk1;
 
 //used for verifying payment(optional) 
 $cmnVerifyPayment = 'verify_payment';
 $verifyPayment_str = $key . '|' . $cmnVerifyPayment . '|'.$txnid .'|' . $salt;
 $verifyPayment = strtolower(hash('sha512', $verifyPayment_str));
 $arr['verify_payment_hash'] = $verifyPayment;
 
 if($user_credentials != NULL & $user_credentials != '')
 {
 $cmnNameDeleteCard = 'delete_user_card';
 $deleteHash_str = $key . '|' . $cmnNameDeleteCard . '|' . $user_credentials . '|' . $salt ;
 $deleteHash = strtolower(hash('sha512', $deleteHash_str));
 $arr['delete_user_card_hash'] = $deleteHash;
 
 $cmnNameGetUserCard = 'get_user_cards';
 $getUserCardHash_str = $key . '|' . $cmnNameGetUserCard . '|' . $user_credentials . '|' . $salt ;
 $getUserCardHash = strtolower(hash('sha512', $getUserCardHash_str));
 $arr['get_user_cards_hash'] = $getUserCardHash;
 
 $cmnNameEditUserCard = 'edit_user_card';
 $editUserCardHash_str = $key . '|' . $cmnNameEditUserCard . '|' . $user_credentials . '|' . $salt ;
 $editUserCardHash = strtolower(hash('sha512', $editUserCardHash_str));
 $arr['edit_user_card_hash'] = $editUserCardHash;
 
 $cmnNameSaveUserCard = 'save_user_card';
 $saveUserCardHash_str = $key . '|' . $cmnNameSaveUserCard . '|' . $user_credentials . '|' . $salt ;
 $saveUserCardHash = strtolower(hash('sha512', $saveUserCardHash_str));
 $arr['save_user_card_hash'] = $saveUserCardHash;
 
 $cmnPaymentRelatedDetailsForMobileSdk = 'payment_related_details_for_mobile_sdk';
 $detailsForMobileSdk_str = $key . '|' . $cmnPaymentRelatedDetailsForMobileSdk . '|' . $user_credentials . '|' . $salt ;
 $detailsForMobileSdk = strtolower(hash('sha512', $detailsForMobileSdk_str));
 $arr['payment_related_details_for_mobile_sdk_hash'] = $detailsForMobileSdk;
 }
 
 
 // if($udf3!=NULL &amp;&amp; !empty($udf3)){
 $cmnSend_Sms='send_sms';
 $sendsms_str=$key . '|' . $cmnSend_Sms . '|' . $udf3 . '|' . $salt;
 $send_sms = strtolower(hash('sha512',$sendsms_str));
 $arr['send_sms_hash']=$send_sms;
 // }
 
 return $arr;
}
 
function checkNull($value) {
 if ($value == null) {
 return '';
 } else {
 return $value;
 }
 }
 
$output=getHashes($_POST["txnid"], $_POST["amount"], $_POST["productinfo"], $_POST["firstname"], $_POST["email"], $_POST["user_credentials"], $_POST["udf1"], $_POST["udf2"], $_POST["udf3"], $_POST["udf4"], $_POST["udf5"]);
 
echo json_encode($output);
 ?>

As mine setup below will be the server URL:

URL: https://www.kpblogs.com/getHashCode.php

So now creating the Activity and Layout to start Integration. Below is the Activity layout where we have given EditText to accept the price and “PayNow” button to start the Payment Gateway. activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.kpblogs.payuintegration.TestActivity">

    <EditText

        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="Enter Amount for test"
        android:id="@+id/price"
        android:inputType="numberDecimal"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/payNow"
        android:text="Pay with PayUMoney"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

 

In the below section showing the activity code to share the other required details.  Function to launch PayUmoney

/**
 * This function prepares the data for payment and launches payumoney plug n play sdk
 */
private void launchPayUMoney() {

    PayUmoneyConfig payUmoneyConfig = PayUmoneyConfig.getInstance();

    //Use this to set your custom text on result screen button
    payUmoneyConfig.setDoneButtonText("Done");

    //Use this to set your custom title for the activity
    payUmoneyConfig.setPayUmoneyActivityTitle("Test Account");

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


    String txnId = System.currentTimeMillis() + "";
    String phone = "9810093311";
    String productName = "Chair";
    String firstName = "khushvinder";
    String email = "khushvinder.sharma@gmail.com";
    String udf1 = "";
    String udf2 = "";
    String udf3 = "";
    String udf4 = "";
    String udf5 = "";


    Environment appEnvironment = ((Application) getApplication()).getEnvironment();
    builder.setAmount(price)
            .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)
            .setIsDebug(appEnvironment.debug())
            .setKey(appEnvironment.merchant_Key())
            .setMerchantId(appEnvironment.merchant_ID());

    try {
        paymentParam = builder.build();
        generateHashFromServer(paymentParam);

    } catch (Exception e) {
        Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
    }
}

 

Once we set all the information then call function generateHashFromServer(PayUmoneySdkInitializer.PaymentParam paymentParam) to hit the API to get MD5 hashcode from paymentParam.

Note: Please don’t Keep both Salt and Key on client code that’s why we are putting Salt on server to get hash code.

public void generateHashFromServer(PayUmoneySdkInitializer.PaymentParam paymentParam) {


    HashMap<String, String> params = paymentParam.getParams();

    // lets create the post params
    StringBuffer postParamsBuffer = new StringBuffer();
    postParamsBuffer.append(concatParams(PayUmoneyConstants.KEY, params.get(PayUmoneyConstants.KEY)));
    postParamsBuffer.append(concatParams(PayUmoneyConstants.AMOUNT, params.get(PayUmoneyConstants.AMOUNT)));
    postParamsBuffer.append(concatParams(PayUmoneyConstants.TXNID, params.get(PayUmoneyConstants.TXNID)));
    postParamsBuffer.append(concatParams(PayUmoneyConstants.EMAIL, params.get(PayUmoneyConstants.EMAIL)));
    postParamsBuffer.append(concatParams("productinfo", params.get(PayUmoneyConstants.PRODUCT_INFO)));
    postParamsBuffer.append(concatParams("firstname", params.get(PayUmoneyConstants.FIRSTNAME)));
    postParamsBuffer.append(concatParams(PayUmoneyConstants.UDF1, params.get(PayUmoneyConstants.UDF1)));
    postParamsBuffer.append(concatParams(PayUmoneyConstants.UDF2, params.get(PayUmoneyConstants.UDF2)));
    postParamsBuffer.append(concatParams(PayUmoneyConstants.UDF3, params.get(PayUmoneyConstants.UDF3)));
    postParamsBuffer.append(concatParams(PayUmoneyConstants.UDF4, params.get(PayUmoneyConstants.UDF4)));
    postParamsBuffer.append(concatParams(PayUmoneyConstants.UDF5, params.get(PayUmoneyConstants.UDF5)));


    String postParams = postParamsBuffer.charAt(postParamsBuffer.length() - 1) == '&' ? postParamsBuffer.substring(0, postParamsBuffer.length() - 1).toString() : postParamsBuffer.toString();

    // lets make an api call
    GetHashesFromServerTask getHashesFromServerTask = new GetHashesFromServerTask();
    getHashesFromServerTask.execute(postParams);
}

Below is the AsyncTask to call server API:

 

/**
 * This AsyncTask generates hash from server.
 */
private class GetHashesFromServerTask extends AsyncTask<String, String, String> {
    private ProgressDialog progressDialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = new ProgressDialog(TestActivity.this);
        progressDialog.setMessage("Please wait...");
        progressDialog.show();
    }

    @Override
    protected String doInBackground(String... postParams) {

        String merchantHash = "";
        try {
            //TODO Below url is just for testing purpose, merchant needs to replace this with their server side hash generation url
            URL url = new URL("https://www.kpblogs.com/getHashCode.php");

            String postParam = postParams[0];

            byte[] postParamsByte = postParam.getBytes("UTF-8");

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Content-Length", String.valueOf(postParamsByte.length));
            conn.setDoOutput(true);
            conn.getOutputStream().write(postParamsByte);

            InputStream responseInputStream = conn.getInputStream();
            StringBuffer responseStringBuffer = new StringBuffer();
            byte[] byteContainer = new byte[1024];
            for (int i; (i = responseInputStream.read(byteContainer)) != -1; ) {
                responseStringBuffer.append(new String(byteContainer, 0, i));
            }

            System.out.println("Response "+responseStringBuffer.toString());
            JSONObject response = new JSONObject(responseStringBuffer.toString());

            Iterator<String> payuHashIterator = response.keys();
            while (payuHashIterator.hasNext()) {
                String key = payuHashIterator.next();
                switch (key) {
                    /**
                     * This hash is mandatory and needs to be generated from merchant's server side
                     */
                    case "payment_hash":
                        merchantHash = response.getString(key);
                        break;
                    default:
                        break;
                }
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return merchantHash;
    }

    @Override
    protected void onPostExecute(String merchantHash) {
        super.onPostExecute(merchantHash);

        progressDialog.dismiss();
        if (merchantHash.isEmpty() || merchantHash.equals("")) {
            Toast.makeText(TestActivity.this, "Could not generate hash", Toast.LENGTH_SHORT).show();
        } else {
            paymentParam.setMerchantHash(merchantHash);
            PayUmoneyFlowManager.startPayUMoneyFlow(paymentParam, TestActivity.this, R.style.AppTheme_default, false);
        }
    }
}

 

Below is the full activity code:

package com.kpblogs.payuintegration;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.crashlytics.android.Crashlytics;
import com.payumoney.core.PayUmoneyConfig;
import com.payumoney.core.PayUmoneyConstants;
import com.payumoney.core.PayUmoneySdkInitializer;
import com.payumoney.sdkui.ui.utils.PayUmoneyFlowManager;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Iterator;

import io.fabric.sdk.android.Fabric;

/**
 * @author Khushvinder
 */

public class TestActivity extends AppCompatActivity {

    private  PayUmoneySdkInitializer.PaymentParam paymentParam;
    private double price;
    private EditText priceEditText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Fabric.with(this, new Crashlytics());
        setContentView(R.layout.activity_main);

        priceEditText = (EditText)findViewById(R.id.price);
        Button payNow = (Button)findViewById(R.id.payNow);
        payNow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                price = Double.valueOf(priceEditText.getText().toString());
                launchPayUMoney();
            }
        });
    }


    /**
     * This function prepares the data for payment and launches payumoney plug n play sdk
     */
    private void launchPayUMoney() {

        PayUmoneyConfig payUmoneyConfig = PayUmoneyConfig.getInstance();

        //Use this to set your custom text on result screen button
        payUmoneyConfig.setDoneButtonText("Done");

        //Use this to set your custom title for the activity
        payUmoneyConfig.setPayUmoneyActivityTitle("Test Account");

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


        String txnId = System.currentTimeMillis() + "";
        String phone = "9810093311";
        String productName = "Chair";
        String firstName = "khushvinder";
        String email = "khushvinder.sharma@gmail.com";
        String udf1 = "";
        String udf2 = "";
        String udf3 = "";
        String udf4 = "";
        String udf5 = "";


        Environment appEnvironment = ((Application) getApplication()).getEnvironment();
        builder.setAmount(price)
                .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)
                .setIsDebug(appEnvironment.debug())
                .setKey(appEnvironment.merchant_Key())
                .setMerchantId(appEnvironment.merchant_ID());

        try {
            paymentParam = builder.build();
            generateHashFromServer(paymentParam);

        } catch (Exception e) {
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }


    public void generateHashFromServer(PayUmoneySdkInitializer.PaymentParam paymentParam) {


        HashMap<String, String> params = paymentParam.getParams();

        // lets create the post params
        StringBuffer postParamsBuffer = new StringBuffer();
        postParamsBuffer.append(concatParams(PayUmoneyConstants.KEY, params.get(PayUmoneyConstants.KEY)));
        postParamsBuffer.append(concatParams(PayUmoneyConstants.AMOUNT, params.get(PayUmoneyConstants.AMOUNT)));
        postParamsBuffer.append(concatParams(PayUmoneyConstants.TXNID, params.get(PayUmoneyConstants.TXNID)));
        postParamsBuffer.append(concatParams(PayUmoneyConstants.EMAIL, params.get(PayUmoneyConstants.EMAIL)));
        postParamsBuffer.append(concatParams("productinfo", params.get(PayUmoneyConstants.PRODUCT_INFO)));
        postParamsBuffer.append(concatParams("firstname", params.get(PayUmoneyConstants.FIRSTNAME)));
        postParamsBuffer.append(concatParams(PayUmoneyConstants.UDF1, params.get(PayUmoneyConstants.UDF1)));
        postParamsBuffer.append(concatParams(PayUmoneyConstants.UDF2, params.get(PayUmoneyConstants.UDF2)));
        postParamsBuffer.append(concatParams(PayUmoneyConstants.UDF3, params.get(PayUmoneyConstants.UDF3)));
        postParamsBuffer.append(concatParams(PayUmoneyConstants.UDF4, params.get(PayUmoneyConstants.UDF4)));
        postParamsBuffer.append(concatParams(PayUmoneyConstants.UDF5, params.get(PayUmoneyConstants.UDF5)));


        String postParams = postParamsBuffer.charAt(postParamsBuffer.length() - 1) == '&' ? postParamsBuffer.substring(0, postParamsBuffer.length() - 1).toString() : postParamsBuffer.toString();

        // lets make an api call
        GetHashesFromServerTask getHashesFromServerTask = new GetHashesFromServerTask();
        getHashesFromServerTask.execute(postParams);
    }


    protected String concatParams(String key, String value) {
        return key + "=" + value + "&";
    }

    /**
     * This AsyncTask generates hash from server.
     */
    private class GetHashesFromServerTask extends AsyncTask<String, String, String> {
        private ProgressDialog progressDialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog = new ProgressDialog(TestActivity.this);
            progressDialog.setMessage("Please wait...");
            progressDialog.show();
        }

        @Override
        protected String doInBackground(String... postParams) {

            String merchantHash = "";
            try {
                //TODO Below url is just for testing purpose, merchant needs to replace this with their server side hash generation url
                URL url = new URL("https://www.kpblogs.com/getHashCode.php");

                String postParam = postParams[0];

                byte[] postParamsByte = postParam.getBytes("UTF-8");

                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                conn.setRequestProperty("Content-Length", String.valueOf(postParamsByte.length));
                conn.setDoOutput(true);
                conn.getOutputStream().write(postParamsByte);

                InputStream responseInputStream = conn.getInputStream();
                StringBuffer responseStringBuffer = new StringBuffer();
                byte[] byteContainer = new byte[1024];
                for (int i; (i = responseInputStream.read(byteContainer)) != -1; ) {
                    responseStringBuffer.append(new String(byteContainer, 0, i));
                }

                System.out.println("Response "+responseStringBuffer.toString());
                JSONObject response = new JSONObject(responseStringBuffer.toString());

                Iterator<String> payuHashIterator = response.keys();
                while (payuHashIterator.hasNext()) {
                    String key = payuHashIterator.next();
                    switch (key) {
                        /**
                         * This hash is mandatory and needs to be generated from merchant's server side
                         */
                        case "payment_hash":
                            merchantHash = response.getString(key);
                            break;
                        default:
                            break;
                    }
                }

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (ProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return merchantHash;
        }

        @Override
        protected void onPostExecute(String merchantHash) {
            super.onPostExecute(merchantHash);

            progressDialog.dismiss();
            if (merchantHash.isEmpty() || merchantHash.equals("")) {
                Toast.makeText(TestActivity.this, "Could not generate hash", Toast.LENGTH_SHORT).show();
            } else {
                paymentParam.setMerchantHash(merchantHash);
                PayUmoneyFlowManager.startPayUMoneyFlow(paymentParam, TestActivity.this, R.style.AppTheme_default, false);
            }
        }
    }
}

Download full application code 

below are the temporary card details to for test account (with test account you cannot validate net banking options)

 Credit Card Number – 5123 4567 8901 2346
 Name on the Card – Any name
 Card Expiry – May, 20 for Success and June, 20 for Failure
 CVV – 123 for success and 000 to fail the transaction.

 

Screenshots of integration

payu_money
payu_money

 

payu_landing_page
payu_landing_page

 

payu_landing_with_netbanking
payu_landing_with_netbanking

After entering the temporary card details below are the successfully receipt screenshot.

payment_done
payment_done

 

6,127 total views, 12 views today

22 thoughts on “PayUmoney payment gateway integration with android”

  1. PayUmoneyFlowManager.startPayUMoneyFlow(paymentParam, TestActivity.this, R.style.AppTheme_default, false); line causinhg error…saying some error occured .Any Idea..?

  2. compile ‘com.payumoney.sdkui:plug-n-play:1.0.0’
    on syncing my project after adding the above line gives me an error :
    Error:Execution failed for task ‘:app:processDebugManifest’.> Manifest merger failed with multiple errors, see logs
    please help me resolve this.

  3. Hello sir,

    It’s Nice tutorial and working correctly but I want to to know after payment done I have to call another API so how can I do it.

  4. Hi,
    Can you please tell me, how to do in a fragment.
    Environment appEnvironment = ((Application) getApplication()).getEnvironment();
    I am getting type casting issue when doing like below
    Environment appEnvironment = ((Application) getActivity().getApplication()).getEnvironment();

  5. Unable to find explicit activity class {com.example.mmai5.paymentdemo/com.payumoney.sdkui.ui.activities.PayUmoneyActivity}; have you declared this activity in your AndroidManifest.xml?

  6. Hello sir,
    I m facing error while sync io-fabric….So what should I do??
    Error :- Could not find any matches for io.fabric.tools:gradle:1.+ as no versions of io.fabric.tools:gradle are available.

  7. Hi,
    I have added getHashCode.php file to my server and I did everything same as mentioned in this post. But instead of merchant hash, I am getting contents of the getHashCode.php file as response to my hash generation request. What am I doing wrong?

Leave a Reply

Your email address will not be published. Required fields are marked *