使用 android studio 将 UPI 支付添加到 android 应用,UPI(统一支付接口)集成 android

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

我正在尝试将 Upi 支付添加到 android 应用程序以自动支付咖啡订购应用程序的账单(数字支付)。我在 google 中搜索过,但没找到。所以任何人都可以详细解释我的步骤。

创建一个按钮,该按钮将触发打开名为 upi 的新 activity 的意图。 仔细按照这些步骤 1. 要打开 upi activity 创建一个名为 bill.xml 和 bill.java

的 activity

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 Whosebug how to send data from one activity to other

    }


}

现在创建 upi activity FILE-->NEW-->ACTIVITY-->清空Activity-->Activityname:upi-->点击ok

现在将这些添加到 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>

将 1234@ybl 替换为接收者 upi id xxxxxx@ybl 或任何其他 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;
    }
}


你可以在这里添加你的逻辑如果支付成功了怎么办


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();
            }

万岁,付款完成

注意:仅对 GOOGLE 有效

对于 PHONEPE 和其他即使付款成功,它也会提示付款失败。

对于一键支付,只需打开 url using intent,这将显示您的设备上安装了支持 UPI 支付的应用程序,检查以下代码行

Uri uri = Uri.parse("upi://pay?pa=yourupiid&pn=Yadav%20Basant&tn=Testing%20by%20Yadav%20Basant&am=1&cu=INR&url=https://pay2all.in");
                
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivityForResult(intent, 1421);

并检查 ActivityResult 的响应

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

    if (requestCode==1421)
    {
        if (resultCode==RESULT_OK)
        {
             assert data != null;
            Log.e("data","response "+data.getStringExtra("response"));

            Toast.makeText(this, "response : "+data.getStringExtra("response"), Toast.LENGTH_LONG).show();



        }
    }
}