PayU Money is a digital payment gateway for accepting online payments. Reputed companies like NETFLIX, Dream11, Myntra use PayU Money as their Payment Gateway. Furthermore, It supports collecting payments via QR Code, Sharable Link, Web Page, Invoices takes payment solution to the next level. Above all collecting payments via Excel Sheet is a cool feature(requires plugin). PayU Money also provides Payment Gateway which is available for web and mobile platforms. It has a vast variety of payment options like Credit/Debit Card, Net Banking, UPI, International payment, etc. In this article, we are going to learn how to integrate PayU Money Payment Gateway Integration in a simple eCommerce application. Making eCommerce is a bit complex each and every class can not be covered here So, I have prepared a sample project you can find it here.

DEMO

PayUMoney Payment Gateway Integration in android | loopwiki.com

1. Fashion Shop Application

This application has a limited amount of screens. Application created using design library components like RecyclerView, CardView, etc. To reduce view initialization boilerplate code we are using the butterknife library.

  • Fashion Shop Home- This screen lists available products. Here we are creating product data programmatically. You can load products from the server by tweaking a little bit of code. Each product contains a thumbnail, name, price.
  • Fashion Shop Cart- Lists products that are added to the cart. A button to remove products from the cart, and a button to proceed to checkout.
  • PayU Money Checkout- This screen is initiated when we start the checkout flow. It will contain all the available payment options.

Below are some screenshots of the PayU Money payment flow.

  • Shopping home screen
  • Shooping cart screen
  • PayUMoney Payment Screen
  • Payment successful screen

2. PayU Money Payment Lifecycle

PayU Money android SDK is very easy to integrate and gives almost full control over the payment flow.

  1. Preparing Order: When a customer adds products to the cart and goes to the cart screen we calculate the total amount to be paid.
  2. Initiate PayU Money Checkout: Once the customer adds products from the cart and clicks the checkout button then PayU Money checkout will be initiated. The checkout screen will have different payment options. The customer will choose one of them and completes the payment.
  3. Order Status: PayU Money will return the appropriate payment status code to the application. The application will handle the status code and will show the message accordingly.

3. PayU Money Integration

While building applications we need to take care of modern architecture and security measures. This article is made to demonstrate the PayU Money payment gateway so I tried to keep the application as minimum as possible to understand it better.

Step 1: Create Account at PayU Money.

Step 2: You can activate your account step by step wizard will be presented by PayU Money. I am going to use a test account credential for this application.

Step 3: Add dependency for PayU Money android SDK in build.gradle file. Below is the latest dependency while creating this article.

dependencies {
    implementation 'com.payumoney.sdkui:plug-n-play:1.6.0'
}

Step 4: Open the dashboard and go to Dashboard -> Integration Details. Copy Merchant Key and Merchant Salt.

PayU Money Integration Details
PayU Money Integration Details

Step 5: Then go to Dashboard -> Profile and copy Merchant ID.

PayU Money Merchant ID Details
PayU Money Merchant ID Details

Step 6: Add Marchand Key, Marchand Salt and Merchant ID to strings.xml file as shown below.

<resources>
    <string name="app_name">PayUMoney Checkout example</string>
    <string name="ruppi_symbol">₹</string>
    <string name="product_added">Product Added to Cart</string>
    <string name="product_removed">Product Removed from Cart</string>
    <! – TODO: Remove or change Marchand Key, Marchand Salt and Merchant ID – >
    <string name="MerchantKey">Your MerchantKey</string>
    <string name="MerchantId">Your MerchantId</string> 
    <string name="MerchantSalt">Your MerchantSalt</string>
    <string name="sUrl">https://test.payumoney.com/mobileapp/payumoney/success.php</string>
    <string name="fUrl">https://test.payumoney.com/mobileapp/payumoney/failure.php</string>
</resources>

4. PayU Money Android SDK Integration

1. When the activity launches productFragment will be shown. Customer will select the products.

2. After that customer clicks the cart icon fragment manager will place cartFragment in the main content.

3. When Customer clicks Proceed to Pay button launchPayUMoneyFlow method gets called and PayU Money payment flow will start.

4. PayU Money will provide payment options for example Credit/Debit Card, UPI, Net Banking will be presented by PayU Money and the customer completes the payment.

5. PayU Money will call onActivityResult passing status code. After that application will show an appropriate status message.

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;

import com.loopwiki.payumoneycheckout.Fragment.CartFragment;
import com.loopwiki.payumoneycheckout.Fragment.ProductsFragment;
import com.loopwiki.payumoneycheckout.Model.Product;
import com.loopwiki.payumoneycheckout.R;
import com.loopwiki.payumoneycheckout.Util.Helper;
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.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class PaymentActivity extends AppCompatActivity implements ProductsFragment.ProductInteractionListener, CartFragment.CartInteractionListener {
    public static final String TAG = PaymentActivity.class.getSimpleName();
    FragmentManager fragmentManager;
    ProductsFragment productsFragment;
    int cartCount = 0;
    @BindView(R.id.textViewCartCount)
    TextView textViewCartCount;
    @BindView(R.id.imageViewCart)
    ImageView imageViewCart;
    List<Product> products;

    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_payment);
        ButterKnife.bind(this);
        fragmentManager = getSupportFragmentManager();
        productsFragment = ProductsFragment.newInstance();
        products = getProducts();
        productsFragment.products = products;
        fragmentManager.beginTransaction().replace(R.id.main_content, productsFragment).commit();
        imageViewCart.setOnClickListener(v -> {
            CartFragment cartFragment = new CartFragment();
            List<Product> productList = new ArrayList<>();
            for (Product product : products) {
                if (product.isAddedToCart()) {
                    productList.add(product);
                }
            }
            cartFragment.products = productList;
            fragmentManager.beginTransaction().replace(R.id.main_content, cartFragment).addToBackStack(ProductsFragment.TAG).commit();
        });

    }

    // Callback from Products fragment when product is added
    @Override
    public void ProductAddedToCart(Product product) {
        cartCount++;
        textViewCartCount.setVisibility(View.VISIBLE);
        textViewCartCount.setText(String.valueOf(cartCount));
        Toast.makeText(this, getString(R.string.product_added), Toast.LENGTH_SHORT).show();
    }

    // Callback from Products fragment when product is removed
    @Override
    public void ProductRemovedFromCart(Product product) {
        cartCount--;
        textViewCartCount.setText(String.valueOf(cartCount));
        if (cartCount == 0) {
            textViewCartCount.setVisibility(View.GONE);
        }
        Toast.makeText(this, getString(R.string.product_removed), Toast.LENGTH_SHORT).show();
    }

    // method to create dummy product
    private List<Product> getProducts() {
        List<Product> products = new ArrayList<>();
        int[] ImageUrl = {R.drawable.one, R.drawable.two, R.drawable.three, R.drawable.four, R.drawable.five, R.drawable.six};
        String[] Title = {"HRX by Hrithik", "Crew STREET", "Royal Enfield", "Kook N Keech", "ADIDAS", "UNDER ARMOUR"};
        int[] Price = {5000, 2000, 1500, 3000, 1256, 700};
        boolean[] IsNew = {true, false, false, true, true, false};
        for (int i = 0; i < ImageUrl.length; i++) {
            Product product = new Product();
            product.setName(Title[i]);
            product.setImageResourceId(ImageUrl[i]);
            product.setNew(IsNew[i]);
            product.setPrice(Price[i]);
            products.add(product);
        }
        return products;

    }

    // Back button press method
    @Override
    public void onBackPressed() {
        if (fragmentManager.getBackStackEntryCount() == 0) {
            super.onBackPressed();
        } else {
            fragmentManager.popBackStackImmediate();
        }

    }

    // Method called when product is removed from cart
    @Override
    public void RemoveProduct(Product product) {
        int index = this.products.indexOf(product);
        Product ProductToRemove = this.products.get(index);
        ProductToRemove.setAddedToCart(false);
        ProductRemovedFromCart(product);
    }

    // method to clear cart
    public void clearCart() {
        for (Product product : products) {
            if (product.isAddedToCart()) {
                product.setAddedToCart(false);
            }
        }
    }

    // Method is called when we click on Pay button
    @Override
    public void ProceedToPay(int TotalPrice) {
        launchPayUMoneyFlow(TotalPrice);
    }

    // This method takes amount as parameter and launches PayUMoney checkout
    private void launchPayUMoneyFlow(double amount) {
        PayUmoneySdkInitializer.PaymentParam.Builder builder = new PayUmoneySdkInitializer.PaymentParam.Builder();

        String txnId = "0nf7" + System.currentTimeMillis();
        // String txnId = "TXNID720431525261327973";
        String phone = "7777777777";
        String productName = "Sample Product";
        String firstName = "loopwiki";
        String email = "[email protected]";
        String udf1 = "";
        String udf2 = "";
        String udf3 = "";
        String udf4 = "";
        String udf5 = "";

        //AppEnvironment appEnvironment = ((BaseApplication) getApplication()).getAppEnvironment();
        builder.setAmount(String.valueOf(amount))
                .setTxnId(txnId)
                .setPhone(phone)
                .setProductName(productName)
                .setFirstName(firstName)
                .setEmail(email)
                .setsUrl(getString(R.string.sUrl))
                .setfUrl(getString(R.string.fUrl))
                .setUdf1(udf1)
                .setUdf2(udf2)
                .setUdf3(udf3)
                .setUdf4(udf4)
                .setUdf5(udf5)
                .setIsDebug(true)
                .setKey(getString(R.string.MerchantKey))
                .setMerchantId(getString(R.string.MerchantId));

        try {
            PayUmoneySdkInitializer.PaymentParam 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);

            PayUmoneyFlowManager.startPayUMoneyFlow(mPaymentParams, PaymentActivity.this, R.style.AppTheme_Green, false);

        } catch (Exception e) {
            // some exception occurred
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }
    // Method to create hash
    public static String hashCal(String str) {
        byte[] hashseq = str.getBytes();
        StringBuilder hexString = new StringBuilder();
        try {
            MessageDigest algorithm = MessageDigest.getInstance("SHA-512");
            algorithm.reset();
            algorithm.update(hashseq);
            byte messageDigest[] = algorithm.digest();
            for (byte aMessageDigest : messageDigest) {
                String hex = Integer.toHexString(0xFF &amp; aMessageDigest);
                if (hex.length() == 1) {
                    hexString.append("0");
                }
                hexString.append(hex);
            }
        } catch (NoSuchAlgorithmException ignored) {
        }
        return hexString.toString();
    }


    /**
     * Note : Hash value must be calculated from server only for testing purpose you can generate
     * using this method
     * Thus function calculates the hash for transaction
     *
     * @param paymentParam payment params of transaction
     * @return payment params along with calculated merchant hash
     */
    private PayUmoneySdkInitializer.PaymentParam calculateServerSideHashAndInitiatePayment1(final PayUmoneySdkInitializer.PaymentParam paymentParam) {

        StringBuilder stringBuilder = new StringBuilder();
        HashMap<String, String> params = paymentParam.getParams();
        stringBuilder.append(params.get(PayUmoneyConstants.KEY)).append("|");
        stringBuilder.append(params.get(PayUmoneyConstants.TXNID)).append("|");
        stringBuilder.append(params.get(PayUmoneyConstants.AMOUNT)).append("|");
        stringBuilder.append(params.get(PayUmoneyConstants.PRODUCT_INFO)).append("|");
        stringBuilder.append(params.get(PayUmoneyConstants.FIRSTNAME)).append("|");
        stringBuilder.append(params.get(PayUmoneyConstants.EMAIL)).append("|");
        stringBuilder.append(params.get(PayUmoneyConstants.UDF1)).append("|");
        stringBuilder.append(params.get(PayUmoneyConstants.UDF2)).append("|");
        stringBuilder.append(params.get(PayUmoneyConstants.UDF3)).append("|");
        stringBuilder.append(params.get(PayUmoneyConstants.UDF4)).append("|");
        stringBuilder.append(params.get(PayUmoneyConstants.UDF5)).append("||||||");

        stringBuilder.append(R.string.MerchantSalt);

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

        return paymentParam;
    }

    @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("PaymentActivity", "request code " + requestCode + " resultcode " + resultCode);
        if (requestCode == PayUmoneyFlowManager.REQUEST_CODE_PAYMENT &amp;&amp; resultCode == RESULT_OK &amp;&amp; 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 &amp;&amp; transactionResponse.getPayuResponse() != null) {
                if (transactionResponse.getTransactionStatus().equals(TransactionResponse.TransactionStatus.SUCCESSFUL)) {
                    //Success Transaction
                    Dialog dialog = Helper.getSuccessDialog(this);
                    TextView textViewGoHome = dialog.findViewById(R.id.textViewGoHome);
                    textViewGoHome.setOnClickListener(v -> {
                        dialog.dismiss();
                        clearCart();
                        cartCount = 0;
                        textViewCartCount.setVisibility(View.GONE);
                        fragmentManager.beginTransaction().replace(R.id.main_content, productsFragment).commit();
                    });
                    dialog.show();
                    Toast.makeText(this, "Payment Successful", Toast.LENGTH_SHORT).show();
                } else {
                    //Failure Transaction
                }

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

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

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

5. Testing the Application

After PayU Money integration you can test the application using test card details. PayU Money provides test card details which only work with test mode API Key. You can find the latest card details here.

  • Test Card Details
Card issuerNumberMonthYearCVV
Visa40120010371411120121123
MasterCard51000523845368910121123
Test Card Details

6. References

Below are useful links to use while working the project.

  1. PayU Money Dashboard
  2. Test Card Details
  3. Credentials
  4. PayU Money Documentation

I hope you understand PayU Money android integration. If you still have any queries, please post them in the comments section below, I will be happy to help you.

7. Other Links

  1. Android Razorpay Payment Gateway Integration – Ecommerce App.
Author

Hello there, My name is Amardeep founder of loopwiki.com. I have experience in many technologies like Android, Java, Php, etc. In this variety of technologies, I love Android App Development. If you have any idea and you want me to develop for you then let's have chat Conatct

1 Comment

  1. Secured payment gateway platform solution helps your businesses grow and have your business in the palm of your hands and Its provides features like hassle-free sign-up, load and send money, withdraw cash, pay merchants, buy tickets, instant notification, limited liability, etc.

Write A Comment