Integrating UPI payments in an Android application

Last updated Aug 06, 2020

In this post, we'll learn how to integrate UPI payments into an Android application.

UPI is a popular mode of payment for customers which allows them to make payments directly through their bank accounts without entering debit card or netbanking details

 

o achieve UPI payment by using the Payment Intent.

Benefits of using UPI Intent:

  • User need not remember his VPA for making UPI payment
  • Users do not need to switch between your merchant App, UPI PSP App, and SMS.
  • Flexibility for the user to use any UPI PSP App available on the device.
  • Ease of making payment and better user experience results in higher conversion rate

 

Let's check the code

Step 1: Create an Android application in Android Studio

 

Step 2: Update XML file with below code

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:background="#FFF"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    <ImageView
            android:layout_centerHorizontal="true"
            android:id="@+id/img"
            android:layout_margin="16dp"
            android:layout_width="wrap_content" android:layout_height="wrap_content"
    android:src="@drawable/upi"
    />

    <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Amount"
            android:layout_below="@+id/img"
            android:textColor="#000"
            android:textColorHint="#000"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp"
            android:layout_marginTop="20dp"
            android:id="@+id/amount_et"
            android:inputType="number"/>

    <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="michel@xxx"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp"
            android:layout_marginTop="20dp"
            android:id="@+id/upi_id"
            android:textColor="#000"
            android:textColorHint="#000"
            android:layout_below="@+id/amount_et"
            android:text="mouli150388-1@okhdfcbank"/>

    <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Name"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp"
            android:layout_marginTop="20dp"
            android:id="@+id/name"
            android:textColor="#000"
            android:textColorHint="#000"
            android:layout_below="@+id/upi_id"
            android:text="Chandu"/>

    <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Note"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp"
            android:layout_marginTop="20dp"
            android:id="@+id/note"
            android:textColor="#000"
            android:textColorHint="#000"
            android:layout_below="@+id/name"
            android:text="Here's some money bro!"/>

    <Button
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:background="@color/colorAccent"
            android:textColor="#FFF"
            android:id="@+id/send"
            android:layout_below="@+id/note"
            android:layout_marginTop="20dp"
            android:layout_centerHorizontal="true"
            android:text="Pay Amout"/>


</RelativeLayout>

 

Step 3: Add required permissions in manifest file


 

Step 4: Update mainactivity file

package com.rrtutors.upiintegration

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.Toast

import android.net.ConnectivityManager
import android.util.Log


class MainActivity : AppCompatActivity() {
val  UPI_PAYMENT=100
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        var amount_ed=findViewById(R.id.amount_et)
        var upi_idEd=findViewById(R.id.upi_id)
        var nameEd=findViewById(R.id.name)
        var noteEd=findViewById(R.id.note)
        var send=findViewById(R.id.send)
        send.setOnClickListener(View.OnClickListener {

            var amount=amount_ed.text.toString().trim();
            var id=upi_idEd.text.toString().trim();
            var name=nameEd.text.toString().trim();
            var note=noteEd.text.toString().trim();

            if(amount.length>0) {
                var uri = Uri.parse("upi://pay").buildUpon()
                    .appendQueryParameter("pa", id)
                    .appendQueryParameter("pn", name)
                    .appendQueryParameter("tn", note)
                    .appendQueryParameter("am", amount)
                    .appendQueryParameter("cu", "INR")
                    .build();

                var intent = Intent(Intent.ACTION_VIEW);
                intent.data = uri
                var intentChooser = Intent.createChooser(intent, "Pay with")
                if (null != intentChooser.resolveActivity(getPackageManager())) {
                    startActivityForResult(intentChooser, UPI_PAYMENT);
                } else {
                    Toast.makeText(
                        MainActivity@ this,
                        "No UPI app found, please install one to continue",
                        Toast.LENGTH_SHORT
                    ).show();
                }
            }else
            {
                Toast.makeText(MainActivity@this,"Please enter amount",Toast.LENGTH_SHORT).show();

            }
        })

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        when(requestCode)
        {
            UPI_PAYMENT->{
                if(resultCode== Activity.RESULT_OK||resultCode==1)
                {
                    var list:ArrayList
                    if(data!=null)
                    {
                        list= ArrayList()
                        data.getStringExtra("resposne")?.let { list.add(it) }

                    }else
                    {
                        list= ArrayList()
                        list.add("No Reponse")
                    }
                }else
                {
                    var list:ArrayList
                    list= ArrayList()
                    list.add("Error")

                    checkPaymentStatus(list)
                }
            }
        }
    }

    private fun checkPaymentStatus(list: java.util.ArrayList) {

        if(isConnectionAvailable(applicationContext))
        {
            var str=list.get(0);
            Log.d("UPIPAY", "upiPaymentDataOperation: "+str);
            if(str==null)
                str="discard"
            var status: String? =null;
            var txtnNo:String? =null;
            var paymentCancel:String? =null;

            var response=str.split("&")
            for (i in 0 until response.size) {
                val equalStr = response[i].split("=")
                if (equalStr.size >= 2) {
                    if (equalStr[0].toLowerCase() == "Status".toLowerCase()) {
                        status = equalStr[1].toLowerCase()
                    } else if (equalStr[0].toLowerCase() == "ApprovalRefNo".toLowerCase() || equalStr[0].toLowerCase() == "txnRef".toLowerCase()) {
                        txtnNo = equalStr[1]
                    }
                } else {
                    paymentCancel = "Payment cancelled by user."
                }
            }
            if (status.equals("success")) {
                //Code to handle successful transaction here.
                Toast.makeText(MainActivity@this, "Transaction successful.", Toast.LENGTH_SHORT).show();
                Log.d("UPI", "responseStr: "+txtnNo);
            }
            else if("Payment cancelled by user.".equals(paymentCancel)) {
                Toast.makeText(MainActivity@this, "Payment cancelled by user.", Toast.LENGTH_SHORT).show();
            }
            else {
                Toast.makeText(MainActivity@this, "Transaction failed.Please try again", Toast.LENGTH_SHORT).show();
            }

        }else
        {
            Toast.makeText(MainActivity@this,"Please check your network",Toast.LENGTH_SHORT).show();

        }

    }

    fun isConnectionAvailable(context: Context): Boolean {
        val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        if (connectivityManager != null) {
            val netInfo = connectivityManager.activeNetworkInfo
            if (netInfo != null && netInfo.isConnected
                && netInfo.isConnectedOrConnecting
                && netInfo.isAvailable
            ) {
                return true
            }
        }
        return false
    }
}

Step 5: Let's run the application

UPI Payments

Tags UPI android how to add upi in androidhow to pay using upi in androidupi payments java android

 

Related Example

Flutter Pizza App with Firebase Razorpay

Flutter Strip Paymentgateway integration

How do i integrate Razorpay Payment gateway in PHP Mysql website

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

1953 Views