How to Accept & Process Paypal Payment through Gateway in Android

In this tutorial, we are going to learn how to integrate Paypal payment gateway in our Android Application. Paypal provides a seamless online payment platform in Android application, ecommerce platform and many other vendors.

Don't Miss

Paypal provides the sdk for Android. It helps the developer to accept & process payment in the Google mobile phone.

To start integration of paypal gateway, we need to set up a development environment to get OAuth 2.0 client ID and secret credentials for the sandbox and live environments. We need to get these credentials for an access token that authorizes REST API Call.

Follow the Below Steps:

  • Create sandbox accounts

    – To integrate Paypal with web and mobile apps, we need to create an account on Paypal. We can create two type of account:
    • Personal Account – To represent a buyer.
    • Business Account – To represent a merchant. 

Click here to login on Paypal account. If you don’t have an account the click on the Signup and create an account.

  • Create Paypal App

    1. Login into the Developer Dashboard of Paypal account. On My Apps & Credentials, use the toggle to switch between live and sandbox testing apps.
    2. Navigate to the REST API apps section and click Create App.
    3. Type a name for your app and click Create App. The app details page opens and displays your credentials.
    4. Copy and save the client ID and secret for your app.
    5. Review your app details and save your app.
    6. After successfully creating an app, we will get the sandbox credentials. Like below:
  • Add Dependency

    – To integrate paypal SDK, we need to add below dependency in the our build.gradle file. The benefit of SDK, it direct integrate ans handle authentication for us by oAuth 2.0 access token and the SDK automatically reflects any payment API updates.
repositories {
    mavenCentral()
}

dependencies {
    compile 'com.paypal.sdk:paypal-android-sdk:2.16.0'
}

This SDK supports two types of Payment:

  • Single Payment – We will receive a one-time payment from a customer’s PayPal account or payment card (scanned with card.io). This can be either an immediate payment which your servers should subsequently verify, or an authorization for a payment which your servers must subsequently capture, or a payment for an order which your servers must subsequently authorize and capture.
  • Future Payment – Customer logs in to PayPal just one time and consents to future payments:
  1. Obtain Customer Consent to receive an authorization code.
  2. On your server, use this authorization code to Obtain OAuth2 Tokens.

Later, when that customer initiates a payment:

  1. Obtain a Client Metadata ID that you’ll pass to your server.
  2. On your server, Create a Payment using your OAuth2 tokens, the Client Metadata ID, and PayPal’s API.
  • Configure Your Environment

    – Now ,, we need to configure SDK environment. Configuration details include the mode, which is Sandbox for the testing and live for the production with client ID. Add PayPalConfiguration object like below:

For the testing using Sandbox:

PayPalConfiguration.ENVIRONMENT_SANDBOX

For the live using Production

PayPalConfiguration.ENVIRONMENT_PRODUCTION
import android.appcompat.app.AppCompatActivity;
import android.os.Bundle;

import com.paypal.android.sdk.payments.PayPalConfiguration;

public class MainActivity extends AppCompatActivity {
    private static final String clientId = "YOUR APPLICATION CLIENT ID";
    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(clientId);
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


    }
}
  • Start PayPalService –

    We need to start PayPalService when new activity created and also have to stop it upon destruction
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

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

        intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);

        startService(intent);
        
    }

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

    Creating payment and launch the payment intent when button clicked. We called the onBuyPressed() method. In this method, we set the transaction amount and start the Payment Activity.
public void onBuyPressed(View pressed) {

        // PAYMENT_INTENT_SALE will cause the payment to complete immediately.
        // Change PAYMENT_INTENT_SALE to
        //   - PAYMENT_INTENT_AUTHORIZE to only authorize payment and capture funds later.
        //   - PAYMENT_INTENT_ORDER to create a payment for authorization and capture
        //     later via calls from your server.
        
        PayPalPayment payment = new PayPalPayment(new BigDecimal("100"), "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);
    }
  • Implement onActivityResult() –

    To handle the response, we need to implement the onActivityResult() method.
@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));

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

Send Proof of Payment – Send the proof of payment to out servers for verification, as well as any other processing required for our business, such as fulfillment.

  • Full MainActivity Code –

    find the full activity code below
import androidx.appcompat.app.AppCompatActivity;
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 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 java.math.BigDecimal;

public class MainActivity extends AppCompatActivity {
    private static final String clientId = "YOUR_CLIENT_ID";
    Button online_payment;
    private static PayPalConfiguration config = new PayPalConfiguration()

            // Start with mock environment.  When ready, switch to sandbox (ENVIRONMENT_SANDBOX)
            // or live (ENVIRONMENT_PRODUCTION)
            .environment(PayPalConfiguration.ENVIRONMENT_PRODUCTION)

            .clientId(clientId);

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

        online_payment = (Button) findViewById(R.id.online_payment);

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

        intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);

        startService(intent);

        online_payment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBuyPressed(v);
            }
        });

    }

    public void onBuyPressed(View pressed) {

        // PAYMENT_INTENT_SALE will cause the payment to complete immediately.
        // Change PAYMENT_INTENT_SALE to
        //   - PAYMENT_INTENT_AUTHORIZE to only authorize payment and capture funds later.
        //   - PAYMENT_INTENT_ORDER to create a payment for authorization and capture
        //     later via calls from your server.

        PayPalPayment payment = new PayPalPayment(new BigDecimal("1.75"), "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);
    }

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

    @Override
    protected void onActivityResult (int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, 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));

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

I hope this blog help you while Integrating PayPal Account in Android Application. Let me know in comment if you have any question regarding PayPal Integration in Android.

Also check out following Android Integration:

LEAVE A REPLY

Please enter your comment!
Please enter your name here

564FansLike

Recent Posts

Concept of Session in Laravel Tutorial

Sessions are used to store details about the user throughout the requests. Laravel supplies various drivers like file, cookie, apc, array, Memcached, Redis, and database to handle session data. By default, file driver is used as a result of it's light-weight....

Laravel Url Generation Tutorial

Our web application revolves around routes and URLs. After all, they're what direct our users to our pages. At the end of the day, serving pages is what any web application should do. Our users may...

Concept of Laravel Views Tutorial

In MVC framework, the letter "V" stands for Views. It separates the application logic and presentation logic. Views are saved in resources/views listing. Generally, the view contains the HTML which might be served by the application.

Related Articles

Concept of Session in Laravel Tutorial

Sessions are used to store details about the user throughout the requests. Laravel supplies various drivers like file, cookie, apc, array, Memcached, Redis, and database to handle session data. By default, file driver is used as a result of it's light-weight....

Laravel Url Generation Tutorial

Our web application revolves around routes and URLs. After all, they're what direct our users to our pages. At the end of the day, serving pages is what any web application should do. Our users may...

Concept of Laravel Views Tutorial

In MVC framework, the letter "V" stands for Views. It separates the application logic and presentation logic. Views are saved in resources/views listing. Generally, the view contains the HTML which might be served by the application.
WP2Social Auto Publish Powered By : XYZScripts.com