PayPal is used by most of the eCommerce website and mobile application to buy something online. In this post, I explain how to integrate PayPal in your android application. This post is very easy to understand and it takes 5 min to setup PayPal in your application and you can start getting payment through PayPal. I assume that you have your PayPal account or PayPal developer account if not then create one on this link, and once you create your account and get Client Id from the account. If you want to learn how to create an account in Paypal Sandbox check this official link.

 

Integrating PayPal in Android

Step 1: Create a new project or open existing one in Android Studio and open the gradle file and add PayPal dependencies in it. Note: your minimum SDK version is 16

    compile('com.paypal.sdk:paypal-android-sdk:2.15.3') {
        exclude group: 'io.card'
    }

If you want to include PayPal Card API you need to remove exclude group: ‘io.card’

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"
    defaultConfig {
        applicationId "com.example.myapplication"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.1'
    compile('com.paypal.sdk:paypal-android-sdk:2.15.3') {
        exclude group: 'io.card'
    }
    testCompile 'junit:junit:4.12'
}

Step 2. Now Open AndroidManifest.xml and add required permissions in it

<user-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />

Step 3. Now open activity_main.xml or layout where you want to add Paypal pay button and add click listener on it or you can directly call the function in it.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    tools:context="com.example.myapplication.MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="pay"
        android:text="Pay 1.00 USD"
        android:textColor="#000" />

</LinearLayout>

Step 4. Now open Mainactivity.java and initialize your Paypal in it.

  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)
            .clientId("AaOumiENp56mSWkNbk_IdWXxVKFrpCz1ZYSX4GqdMlvFzszZX9j1W03jZtlSUBDZafcYBfwTDSWqQgl-");

Step 5. Now create pay method when user click on it send a request to PayPal to allow you to make payment.

 public void pay(View view) {
        PayPalPayment payment = new PayPalPayment(new BigDecimal("1.00"), "USD", "sample item",
                PayPalPayment.PAYMENT_INTENT_SALE);

        Intent intent = new Intent(this, PaymentActivity.class);

        // send the same configuration for restart resiliency
        intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);

        intent.putExtra(PaymentActivity.EXTRA_PAYMENT, payment);

        startActivityForResult(intent, 0);

    }

Step 6. Now, onActivityResult when user completes the payment you can get payment status and also extract PayPal transaction Id.

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            PaymentConfirmation confirm = data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
            if (confirm != null) {
                try {
                    Log.i("paymentExample", confirm.toJSONObject().toString(4));

                    if (confirm != null) {
                        try {

                            JSONObject jsonObject = new JSONObject(confirm.toJSONObject().toString(4));
                            JSONObject response = new JSONObject(jsonObject.getString("response"));

                            Toast.makeText(this, "Payment Successful transction Id:-" + response.getString("id"), Toast.LENGTH_SHORT).show();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    // TODO: send 'confirm' to your server for verification.
                    // see https://developer.paypal.com/webapps/developer/docs/integration/mobile/verify-mobile-payment/
                    // for more details.

                } catch (JSONException e) {
                    Log.e("paymentExample", "an extremely unlikely failure occurred: ", e);
                }
            }
        } else if (resultCode == Activity.RESULT_CANCELED) {
            Log.i("paymentExample", "The user canceled.");
        } else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID) {
            Log.i("paymentExample", "An invalid Payment or PayPalConfiguration was submitted. Please see the docs.");
        }
    }

Now once you get PayPal id and transaction Id you can pass that data to the server and perform other operation.