Open In App

How to Integrate PayPal SDK in Android?

Last Updated : 26 Jul, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

PayPal is one of the famous payment gateway integration which is one of the famous payment gateways across the world used in so many applications and websites. In this article, we will take a look at implementing this PayPal SDK in our app.

What we are going to build in this article?

We will be building a simple application in which we will be displaying a simple EditText and a Button. From that EditText we will be getting the amount entered by the user and then after clicking on the button we will call PayPal to make payment. With the help of the PayPal UI, we will be able to make payments from the card as well as the PayPal account. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. 

Step by Step Implementation for Generating a Client ID 

Step 1: Navigate to the URL below to create your sandbox account 

Navigate to this URL and log in with your PayPal username and password. After that, you will get to see the below page. On that page, we have to create our SandBox account with some basic details which are shown in the below form. 

After filling in all the details. Click on Create Account option to create your SandBox account. 

Step 2: Creating a new app to generate Client ID

Navigate to this URL and inside this add your app name

Inside this screen, we have to add our App Name and select it as Merchant and then click on Create app option to create a new app. After that, you will get to see the Client ID which we have to use in our application. Now we will move towards Android Part.  

Step by Step Implementation in Android

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.

Step 2: Adding dependency in build.gradle

Navigate to the app > Gradle Scripts > build.gradle and add the below dependency in the dependencies section.

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

After adding this dependency now sync your project and we will move towards working with the XML file.

Step 3: Working with the activity_main.xml file

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. 

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
 
    <!--Edit text for entering the amount-->
    <EditText
        android:id="@+id/idEdtAmount"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="20dp"
        android:layout_marginTop="50dp"
        android:layout_marginEnd="20dp"
        android:hint="Enter Amount to be Paid"
        android:inputType="numberDecimal" />
 
    <!--button for making a payment-->
    <Button
        android:id="@+id/idBtnPay"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/idEdtAmount"
        android:layout_centerInParent="true"
        android:layout_marginTop="10dp"
        android:text="Make Payment" />
 
    <!--text view for displaying payment status-->
    <TextView
        android:id="@+id/idTVStatus"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/idBtnPay"
        android:layout_marginStart="20dp"
        android:layout_marginTop="20dp"
        android:layout_marginEnd="20dp"
        android:padding="5dp"
        android:textAlignment="center"
        android:textColor="@color/purple_200"
        android:textSize="20sp" />
 
</RelativeLayout>


 
 

Step 4: Working with the MainActivity.java file

 

Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.

 

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.");
            }
        }
    }
}


 
 

Now run your app and see the output of the app.

 

Output:

 

Note: As my PayPal account is not verified so the payments will not be done on my side.

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads