使用Android Studio将UPI支付添加到Android应用程序,UPI(统一支付接口)集成Android。

3

我正在尝试为咖啡点单应用程序(数字支付)添加Upi支付以自动支付账单。我在谷歌上搜索了一下,但是没有成功。所以有人可以详细解释一下步骤吗?


如果您觉得这个问题有用,请给它点赞。 - undefined
2个回答

3
创建一个按钮,它将触发打开名为upi的新活动的意图。 请仔细按照以下步骤操作: 1. 创建一个名为bill.xml和bill.java的活动以打开upi活动。
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

    }


}

现在创建UPI活动

文件-->新建-->活动-->空活动-->活动名称:upi --> 点击确定

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

对于PhonePe和其他应用,即使支付成功,也会提示付款失败。


1
对我来说不起作用,它显示响应中超过了最大交易次数,支付无法完成。 - undefined
我也是一样的。:( @RohitSharma - undefined
@RohitSharma 我认为如果接收者的 UPI 是商家 UPIID,这将起作用。 - undefined
Google已经更新了政策,因此我们只能通过商家ID即Google Pay商业ID来执行此操作。 - undefined

0

要进行一键支付,只需使用 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);

并且为了响应检查onActivityResult

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



        }
    }
}
            

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接