Search code examples
androidandroid-studioupi

Adding UPI payment to android app using android studio ,UPI (Unified payment interface) integration android


I am trying to add Upi payment to android app to pay the bill automatically for coffee ordering app(digital payment) . I searched in google but it didn't work. So anyone can explain me the steps in detail.


Solution

  • Create a button which will trigger the intent to open the new activity called upi. Follow these steps carefully 1. To open the upi activity create a activity named bill.xml and bill.java

    bill.xml

    <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginEnd="188dp"
            android:layout_marginBottom="28dp"
            android:text="Pay"
            android:onClick="pay"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.955"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.726" />
    </androidx.constraintlayout.widget.ConstraintLayout>
    

    bill.java

    package com.example.smart_park;
    import com.example.smart_park.Starttimer;
    
    import androidx.appcompat.app.AppCompatActivity;
    
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.TextView;
    import android.widget.Toast;
    
    public class bill extends AppCompatActivity {
    double total_price=89.78;
    
    
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_bill);
    
        }
        public void pay(View view){   //this will be triggered when button is clicked
            Intent myIntent = new Intent(getApplicationContext(),upi.class);
            //ADD the data into bundle and send
    
            Bundle bundle = new Bundle();  //create a bundle and send it to activity called upi class.
            bundle.putString("stuffs", Double.toString(total_price));
            myIntent.putExtras(bundle);
            startActivity(myIntent);      //for more details refer stackoverflow how to send data from one activity to other
    
        }
    
    
    }
    
    

    Now create upi activity FILE-->NEW-->ACTIVITY-->Empty Activity-->Activity name:upi --> click ok

    Now add these to upi.xml

    upi.xml

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout 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=".upi">
    
        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Amount"
            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="UPI ID"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp"
            android:layout_marginTop="20dp"
            android:id="@+id/upi_id"
            android:layout_below="@+id/amount_et"
            android:focusable="false"
            android:text="1234@ybl"/>
    
        <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:layout_below="@+id/upi_id"
            android:focusable="false"
            android:text="Rakshit"/>
    
        <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:focusable="false"
            android:layout_below="@+id/name"
            android:text="Fees charged"/>
    
        <Button
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:background="@color/colorPrimary"
            android:textColor="#fff"
            android:id="@+id/send"
            android:layout_below="@+id/note"
            android:layout_marginTop="20dp"
            android:layout_centerHorizontal="true"
            android:text="send by upi"/>
    
    </RelativeLayout>
    

    Replace 1234@ybl with recievers upi id xxxxxx@ybl or any other upi id

    upi.java

    package com.example.coffee1;
    
    import androidx.appcompat.app.AppCompatActivity;
    
    import android.content.Context;
    import android.content.Intent;
    import android.net.ConnectivityManager;
    import android.net.NetworkInfo;
    import android.net.Uri;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;
    
    import java.util.ArrayList;
    
    public class upi extends AppCompatActivity {
        EditText amountEt, noteEt, nameEt, upiIdEt;
        Button send;
    
        final int UPI_PAYMENT = 0;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_upi);
            initializeViews();
            Bundle bundle = getIntent().getExtras();
            String stuffs = bundle.getString("stuffs");  //price recieved from previous activity is fetched here
            Toast.makeText(getApplicationContext(), "stuff"+stuffs, Toast.LENGTH_SHORT).show();
            amountEt.setText(stuffs);
    
    
            send.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    //Getting the values from the EditTexts
    
    
    
    
                    String amount = amountEt.getText().toString();
                    String note = noteEt.getText().toString();
    
                    String name = nameEt.getText().toString();
                    String upiId = upiIdEt.getText().toString();
                    //upiIdEt.setFocusable(false);
                    payUsingUpi(amount, upiId, name, note);
                }
            });
        }
    
        void initializeViews() {
            send = findViewById(R.id.send);
            amountEt = findViewById(R.id.amount_et);
            noteEt = findViewById(R.id.note);
            nameEt = findViewById(R.id.name);
            upiIdEt = findViewById(R.id.upi_id);
        }
    
        void payUsingUpi(String amount, String upiId, String name, String note) {
    
            Uri uri = Uri.parse("upi://pay").buildUpon()
                    .appendQueryParameter("pa", upiId)
                    .appendQueryParameter("pn", name)
                    .appendQueryParameter("tn", note)
                    .appendQueryParameter("am", amount)
                    .appendQueryParameter("cu", "INR")
                    .build();
    
    
            Intent upiPayIntent = new Intent(Intent.ACTION_VIEW);
            upiPayIntent.setData(uri);
    
            // will always show a dialog to user to choose an app
            Intent chooser = Intent.createChooser(upiPayIntent, "Pay with");
    
            // check if intent resolves
            if(null != chooser.resolveActivity(getPackageManager())) {
                startActivityForResult(chooser, UPI_PAYMENT);
            } else {
                Toast.makeText(this,"No UPI app found, please install one to continue",Toast.LENGTH_SHORT).show();
            }
    
        }
    
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
    
            switch (requestCode) {
                case UPI_PAYMENT:
                    if ((RESULT_OK == resultCode) || (resultCode == 11)) {
                        if (data != null) {
                            String trxt = data.getStringExtra("response");
                            //Log.d("UPI", "onActivityResult: " + trxt);
                            ArrayList<String> dataList = new ArrayList<>();
                            dataList.add(trxt);
                            upiPaymentDataOperation(dataList);
                        } else {
                            //Log.d("UPI", "onActivityResult: " + "Return data is null");
                            ArrayList<String> dataList = new ArrayList<>();
                            dataList.add("nothing");
                            upiPaymentDataOperation(dataList);
                        }
                    } else {
                        //Log.d("UPI", "onActivityResult: " + "Return data is null"); //when user simply back without payment
                        ArrayList<String> dataList = new ArrayList<>();
                        dataList.add("nothing");
                        upiPaymentDataOperation(dataList);
                    }
                    break;
            }
        }
    
        private void upiPaymentDataOperation(ArrayList<String> data) {
            if (isConnectionAvailable(upi.this)) {
                String str = data.get(0);
                //Log.d("UPIPAY", "upiPaymentDataOperation: "+str);
                String paymentCancel = "";
                if(str == null) str = "discard";
                String status = "";
                String approvalRefNo = "";
                String response[] = str.split("&");
                for (int i = 0; i < response.length; i++) {
                    String equalStr[] = response[i].split("=");
                    if(equalStr.length >= 2) {
                        if (equalStr[0].toLowerCase().equals("Status".toLowerCase())) {
                            status = equalStr[1].toLowerCase();
                        }
                        else if (equalStr[0].toLowerCase().equals("ApprovalRefNo".toLowerCase()) || equalStr[0].toLowerCase().equals("txnRef".toLowerCase())) {
                            approvalRefNo = equalStr[1];
                        }
                    }
                    else {
                        paymentCancel = "Payment cancelled by user.";
                    }
                }
    
                if (status.equals("success")) {
                    //Code to handle successful transaction here.
                    Toast.makeText(upi.this, "Transaction successful.", Toast.LENGTH_SHORT).show();
                    // Log.d("UPI", "responseStr: "+approvalRefNo);
                    Toast.makeText(this, "YOUR ORDER HAS BEEN PLACED\n THANK YOU AND ORDER AGAIN", Toast.LENGTH_LONG).show();
                }
                else if("Payment cancelled by user.".equals(paymentCancel)) {
                    Toast.makeText(upi.this, "Payment cancelled by user.", Toast.LENGTH_SHORT).show();
                }
                else {
                    Toast.makeText(upi.this, "Transaction failed.Please try again", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(upi.this, "Internet connection is not available. Please check and try again", Toast.LENGTH_SHORT).show();
            }
        }
    
        public static boolean isConnectionAvailable(Context context) {
            ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivityManager != null) {
                NetworkInfo netInfo = connectivityManager.getActiveNetworkInfo();
                if (netInfo != null && netInfo.isConnected()
                        && netInfo.isConnectedOrConnecting()
                        && netInfo.isAvailable()) {
                    return true;
                }
            }
            return false;
        }
    }
    
    
    

    YOU CAN ADD YOUR LOGIC HERE WHAT TO DO IF THE PAYMENT IS SUCCESSFUL

    
    if (status.equals("success")) {
                    //Code to handle successful transaction here.
                    Toast.makeText(upi.this, "Transaction successful.", Toast.LENGTH_SHORT).show(); //TOAST THAT PAYMENT IS SUCCESSFUL
                    // Log.d("UPI", "responseStr: "+approvalRefNo);
                    Toast.makeText(this, "YOUR ORDER HAS BEEN PLACED\n THANK YOU AND ORDER AGAIN", Toast.LENGTH_LONG).show();
                }
    

    HURRAY DONE WITH THE PAYMENT

    NOTE: ONLY FOR GOOGLE PAY IT IS WORKING

    FOR PHONEPE AND OTHER EVEN IF THE PAYMENT IS SUCCESSFUL IT IS TELLING PAYMENT FAILED.