📜  如何在 Android 中集成 PayPal SDK?

📅  最后修改于: 2022-05-13 01:54:49.220000             🧑  作者: Mango

如何在 Android 中集成 PayPal SDK?

PayPal 是著名的支付网关集成之一,它是全球众多应用程序和网站中使用的著名支付网关之一。在本文中,我们将看看在我们的应用程序中实现这个 PayPal SDK。

我们将在本文中构建什么?

我们将构建一个简单的应用程序,我们将在其中显示一个简单的 EditText 和一个 Button。从该 EditText 我们将获得用户输入的金额,然后在单击按钮后我们将调用 PayPal 进行付款。在 PayPal UI 的帮助下,我们将能够从卡以及 PayPal 帐户进行付款。下面给出了一个示例视频,以了解我们将在本文中做什么。请注意,我们将使用Java语言来实现这个项目。

生成客户端 ID 的分步实施

第 1 步:导航到以下 URL 以创建您的沙盒帐户

导航到此 URL 并使用您的 PayPal 用户名和密码登录。之后,您将看到以下页面。在该页面上,我们必须使用以下表格中显示的一些基本详细信息创建我们的 SandBox 帐户。



填写完所有信息后。单击“创建帐户”选项以创建您的 SandBox 帐户。

第 2 步:创建一个新应用程序以生成客户端 ID

导航到此 URL 并在其中添加您的应用程序名称

在此屏幕中,我们必须添加我们的应用程序名称并将其选择为商家,然后单击创建应用程序选项以创建新应用程序。之后,您将看到我们必须在应用程序中使用的客户端 ID。现在我们将转向 Android 部分。

Android中的分步实现

第 1 步:创建一个新项目

要在 Android Studio 中创建新项目,请参阅如何在 Android Studio 中创建/启动新项目。请注意,选择Java作为编程语言。

第 2 步:在 build.gradle 中添加依赖项



导航到app > Gradle Scripts > build.gradle并在依赖项部分添加以下依赖项。

implementation 'com.paypal.sdk:paypal-android-sdk:2.14.2'

添加此依赖项后,现在同步您的项目,我们将继续使用 XML 文件。

步骤 3:使用 activity_main.xml 文件

导航到app > res > layout > activity_main.xml并将以下代码添加到该文件中。下面是activity_main.xml文件的代码。

XML


 
    
    
 
    
    


Java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
 
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
 
import com.paypal.android.sdk.payments.PayPalConfiguration;
import com.paypal.android.sdk.payments.PayPalPayment;
import com.paypal.android.sdk.payments.PayPalService;
import com.paypal.android.sdk.payments.PaymentActivity;
import com.paypal.android.sdk.payments.PaymentConfirmation;
 
import org.json.JSONException;
import org.json.JSONObject;
 
import java.math.BigDecimal;
 
public class MainActivity extends AppCompatActivity {
 
    public static final String clientKey = "Enter your client id here";
    public static final int PAYPAL_REQUEST_CODE = 123;
     
      // Paypal Configuration Object
    private static PayPalConfiguration config = new PayPalConfiguration()
            // Start with mock environment.  When ready,
              // switch to sandbox (ENVIRONMENT_SANDBOX)
            // or live (ENVIRONMENT_PRODUCTION)
            .environment(PayPalConfiguration.ENVIRONMENT_SANDBOX)
            // on below line we are passing a client id.
            .clientId(clientKey);
    private EditText amountEdt;
    private TextView paymentTV;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        // on below line we are initializing our variables.
        amountEdt = findViewById(R.id.idEdtAmount);
         
          // creating a variable for button, edit text and status tv.
        Button makePaymentBtn = findViewById(R.id.idBtnPay);
        paymentTV = findViewById(R.id.idTVStatus);
         
          // on below line adding click listener to our make payment button.
        makePaymentBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // calling a method to get payment.
                getPayment();
            }
        });
    }
 
    private void getPayment() {
         
          // Getting the amount from editText
        String amount = amountEdt.getText().toString();
         
          // Creating a paypal payment on below line.
        PayPalPayment payment = new PayPalPayment(new BigDecimal(String.valueOf(amount)), "USD", "Course Fees",
                PayPalPayment.PAYMENT_INTENT_SALE);
 
        // Creating Paypal Payment activity intent
        Intent intent = new Intent(this, PaymentActivity.class);
 
        //putting the paypal configuration to the intent
        intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
 
        // Putting paypal payment to the intent
        intent.putExtra(PaymentActivity.EXTRA_PAYMENT, payment);
 
        // Starting the intent activity for result
        // the request code will be used on the method onActivityResult
        startActivityForResult(intent, PAYPAL_REQUEST_CODE);
    }
 
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
         
          // If the result is from paypal
        if (requestCode == PAYPAL_REQUEST_CODE) {
 
            // If the result is OK i.e. user has not canceled the payment
            if (resultCode == Activity.RESULT_OK) {
                 
                  // Getting the payment confirmation
                PaymentConfirmation confirm = data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
 
                // if confirmation is not null
                if (confirm != null) {
                    try {
                        // Getting the payment details
                        String paymentDetails = confirm.toJSONObject().toString(4);
                        // on below line we are extracting json response and displaying it in a text view.
                        JSONObject payObj = new JSONObject(paymentDetails);
                        String payID = payObj.getJSONObject("response").getString("id");
                        String state = payObj.getJSONObject("response").getString("state");
                        paymentTV.setText("Payment " + state + "\n with payment id is " + payID);
                    } catch (JSONException e) {
                        // handling json exception on below line
                        Log.e("Error", "an extremely unlikely failure occurred: ", e);
                    }
                }
            } else if (resultCode == Activity.RESULT_CANCELED) {
                // on below line we are checking the payment status.
                Log.i("paymentExample", "The user canceled.");
            } else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID) {
                // on below line when the invalid paypal config is submitted.
                Log.i("paymentExample", "An invalid Payment or PayPalConfiguration was submitted. Please see the docs.");
            }
        }
    }
}



第 4 步:使用MainActivity。 Java文件

转到主活动。 Java文件,参考如下代码。下面是MainActivity的代码。 Java文件。代码中添加了注释以更详细地理解代码。



Java

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
 
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
 
import com.paypal.android.sdk.payments.PayPalConfiguration;
import com.paypal.android.sdk.payments.PayPalPayment;
import com.paypal.android.sdk.payments.PayPalService;
import com.paypal.android.sdk.payments.PaymentActivity;
import com.paypal.android.sdk.payments.PaymentConfirmation;
 
import org.json.JSONException;
import org.json.JSONObject;
 
import java.math.BigDecimal;
 
public class MainActivity extends AppCompatActivity {
 
    public static final String clientKey = "Enter your client id here";
    public static final int PAYPAL_REQUEST_CODE = 123;
     
      // Paypal Configuration Object
    private static PayPalConfiguration config = new PayPalConfiguration()
            // Start with mock environment.  When ready,
              // switch to sandbox (ENVIRONMENT_SANDBOX)
            // or live (ENVIRONMENT_PRODUCTION)
            .environment(PayPalConfiguration.ENVIRONMENT_SANDBOX)
            // on below line we are passing a client id.
            .clientId(clientKey);
    private EditText amountEdt;
    private TextView paymentTV;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        // on below line we are initializing our variables.
        amountEdt = findViewById(R.id.idEdtAmount);
         
          // creating a variable for button, edit text and status tv.
        Button makePaymentBtn = findViewById(R.id.idBtnPay);
        paymentTV = findViewById(R.id.idTVStatus);
         
          // on below line adding click listener to our make payment button.
        makePaymentBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // calling a method to get payment.
                getPayment();
            }
        });
    }
 
    private void getPayment() {
         
          // Getting the amount from editText
        String amount = amountEdt.getText().toString();
         
          // Creating a paypal payment on below line.
        PayPalPayment payment = new PayPalPayment(new BigDecimal(String.valueOf(amount)), "USD", "Course Fees",
                PayPalPayment.PAYMENT_INTENT_SALE);
 
        // Creating Paypal Payment activity intent
        Intent intent = new Intent(this, PaymentActivity.class);
 
        //putting the paypal configuration to the intent
        intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
 
        // Putting paypal payment to the intent
        intent.putExtra(PaymentActivity.EXTRA_PAYMENT, payment);
 
        // Starting the intent activity for result
        // the request code will be used on the method onActivityResult
        startActivityForResult(intent, PAYPAL_REQUEST_CODE);
    }
 
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
         
          // If the result is from paypal
        if (requestCode == PAYPAL_REQUEST_CODE) {
 
            // If the result is OK i.e. user has not canceled the payment
            if (resultCode == Activity.RESULT_OK) {
                 
                  // Getting the payment confirmation
                PaymentConfirmation confirm = data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
 
                // if confirmation is not null
                if (confirm != null) {
                    try {
                        // Getting the payment details
                        String paymentDetails = confirm.toJSONObject().toString(4);
                        // on below line we are extracting json response and displaying it in a text view.
                        JSONObject payObj = new JSONObject(paymentDetails);
                        String payID = payObj.getJSONObject("response").getString("id");
                        String state = payObj.getJSONObject("response").getString("state");
                        paymentTV.setText("Payment " + state + "\n with payment id is " + payID);
                    } catch (JSONException e) {
                        // handling json exception on below line
                        Log.e("Error", "an extremely unlikely failure occurred: ", e);
                    }
                }
            } else if (resultCode == Activity.RESULT_CANCELED) {
                // on below line we are checking the payment status.
                Log.i("paymentExample", "The user canceled.");
            } else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID) {
                // on below line when the invalid paypal config is submitted.
                Log.i("paymentExample", "An invalid Payment or PayPalConfiguration was submitted. Please see the docs.");
            }
        }
    }
}


现在运行您的应用程序并查看应用程序的输出。

输出: