How to Integrate PayPal SDK in Android?


Developers can easily integrate the PayPal SDK into their Android applications to enable secure and convenient payment processing. With the PayPal SDK, users gain the flexibility to make payments using PayPal accounts, credit cards, or other supported methods. The integration involves initializing the SDK with required configurations, creating payment objects, and managing payment outcomes. By leveraging the extensive documentation and powerful features of the PayPal SDK, developers can enhance their Android apps with seamless and reliable payment functionality for smooth user transactions.

PayPal SDK

The PayPal SDK, also known as the Software Development Kit, offers a range of tools, libraries, and resources designed to simplify the integration of PayPal's payment services into various applications. This comprehensive package provides developers with APIs and pre-built UI components that seamlessly incorporate PayPal's secure payment processing capabilities into their software. Notably, it includes provisions for Android applications.

The PayPal SDK is a versatile tool that handles various payment methods. It empowers deve-lopers to effortlessly create, process, and manage payments. With its robust capabilities, it enables the retrieval of detailed payment information and facilitates seamless handling of transaction outcomes.

The developers can greatly enhance their applications by integrating the PayPal SDK. This integration provides reliable, trusted, and widely accepted payment functionality. As a result, it improves the user experience and facilitates seamless transactions.

Approaches

To integrate PayPal SDK in an Android application, you can follow these two different methods:

  • Using Gradle dependency

  • Manual integration

Using Gradle dependency

This method involves adding the PayPal SDK dependency to your app-level build.gradle file. By including the dependency and syncing the project, the necessary PayPal SDK files are fetched. You then initialize the PayPal SDK in your application class or activity by providing the PayPal configuration, which includes the client ID and environment. Once initialized, you can use the PayPal SDK to implement payment flows in your Android app.

Algorithm

  • Add the PayPal SDK dependency in your app-level build.gradle file.

  • Sync the project to fetch the PayPal SDK files.

  • Initialize the PayPal SDK by providing the PayPal configuration, including the client ID and environment.

  • Start the PayPal service to enable payment processing in your application.

Example

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.paypal.android.sdk.payments.PaymentActivity;
import com.paypal.android.sdk.payments.PaymentConfirmation;
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.PaymentIntent;

import java.math.BigDecimal;

public class MainActivity extends AppCompatActivity {

   private static final int PAYPAL_REQUEST_CODE = 123;
   private static final String TAG = "MainActivity";

   // PayPal configuration
   private static PayPalConfiguration paypalConfig = new PayPalConfiguration()
         .environment(PayPalConfiguration.ENVIRONMENT_SANDBOX) // Use sandbox for testing
         .clientId("YOUR_CLIENT_ID"); // Replace with your own PayPal client ID

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      // Start PayPal service
      Intent intent = new Intent(this, PayPalService.class);
      intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, paypalConfig);
      startService(intent);

      // Perform payment
      makePayment();
   }

   private void makePayment() {
      PayPalPayment payment = new PayPalPayment(new BigDecimal("10.0"), "USD", "Test payment",
            PayPalPayment.PAYMENT_INTENT_SALE);

      Intent intent = new Intent(this, PaymentActivity.class);
      intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, paypalConfig);
      intent.putExtra(PaymentActivity.EXTRA_PAYMENT, payment);
      startActivityForResult(intent, PAYPAL_REQUEST_CODE);
   }

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

      if (requestCode == PAYPAL_REQUEST_CODE) {
         if (resultCode == RESULT_OK) {
            PaymentConfirmation confirmation = data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
            if (confirmation != null) {
               String paymentId = confirmation.getProofOfPayment().getPaymentId();
               String state = confirmation.getProofOfPayment().getState();
               
               // Handle successful payment
               Toast.makeText(this, "Payment successful. Payment ID: " + paymentId, Toast.LENGTH_SHORT).show();
            }
         } else if (resultCode == RESULT_CANCELED) {
            // Handle canceled payment
            Toast.makeText(this, "Payment canceled.", Toast.LENGTH_SHORT).show();
         } else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID) {
            // Invalid payment or configuration
            Toast.makeText(this, "Invalid payment or configuration.", Toast.LENGTH_SHORT).show();
         }
      }
   }

   @Override
   public void onDestroy() {
      super.onDestroy();

      // Stop PayPal service
      stopService(new Intent(this, PayPalService.class));
   }
}

Output

Manual integration

In this method, you can manually download the PayPal Android SDK from the PayPal Developer website. Once downloaded, extract the SDK files and copy the relevant JAR file into your project's libs folder. Adding the JAR file as a dependency in your app-level build.gradle file and syncing the project will ensure that the PayPal SDK is included in your project. Afterward, proceed to initialize the SDK and implement payment functionality following Method 1. This approach allows for more control over the integration process but does require manual handling of the SDK files.

Algorithm

  • Download the PayPal Android SDK from the PayPal Developer website.

  • Extract the SDK files and locate the necessary JAR file.

  • Copy the JAR file into your project's libs folder.

  • Add the JAR file as a dependency in your app-level build.gradle file.

  • Sync the project to include the PayPal SDK.

  • Initialize the PayPal SDK by providing the PayPal configuration, including the client ID and environment.

  • Start the PayPal service to enable payment processing in your application.

Example

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.paypal.android.sdk.payments.PayPalConfiguration;
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 java.math.BigDecimal;

public class PayPalActivity extends Activity {

   private static final String TAG = "PayPalActivity";
   private static final int REQUEST_CODE_PAYMENT = 1;

   private static PayPalConfiguration config = new PayPalConfiguration()
         .environment(PayPalConfiguration.ENVIRONMENT_SANDBOX) // Use sandbox for testing
         .clientId("YOUR_CLIENT_ID"); // Replace with your own PayPal client ID

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_paypal);

      Intent intent = new Intent(this, PayPalService.class);
      intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
      startService(intent);

      makePayment();
   }

   private void makePayment() {
      PayPalPayment payment = new PayPalPayment(new BigDecimal("10.0"), "USD", "Test payment",
            PayPalPayment.PAYMENT_INTENT_SALE);

      Intent intent = new Intent(this, PaymentActivity.class);
      intent.putExtra(PaymentActivity.EXTRA_PAYMENT, payment);
      startActivityForResult(intent, REQUEST_CODE_PAYMENT);
   }

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

      if (requestCode == REQUEST_CODE_PAYMENT) {
         if (resultCode == Activity.RESULT_OK) {
            PaymentConfirmation confirm = data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
            if (confirm != null) {
               try {
                  Log.i(TAG, confirm.toJSONObject().toString(4));
                  Log.i(TAG, confirm.getPayment().toJSONObject().toString(4));

                  // Handle successful payment
                  String paymentId = confirm.getPayment().toJSONObject().getString("id");
                  String state = confirm.getPayment().toJSONObject().getString("state");
               } catch (JSONException e) {
                  Log.e(TAG, "Error parsing PayPal payment response.", e);
               }
            }
         } else if (resultCode == Activity.RESULT_CANCELED) {
            // Handle canceled payment
            Log.i(TAG, "Payment canceled.");
         } else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID) {
            // Invalid payment or configuration
            Log.i(TAG, "Invalid payment or configuration.");
         }
      }
   }

   @Override
   public void onDestroy() {
      stopService(new Intent(this, PayPalService.class));
      super.onDestroy();
   }
}

Output

Conclusion

In this tutorial, developers can easily integrate the PayPal SDK into Android applications. This empowers them to incorporate secure and versatile payment processing capabilities effortlessly. By leveraging the comprehensive tools and resources of the SDK, developers can enhance their applications with a trusted and widely accepted payment solution.

Updated on: 27-Jul-2023

252 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements