In this tutorial I am going to discuss about Paypal Payment Integration in android application.
The PayPal Android SDK makes it easy to add PayPal Payments Integration in mobile apps.
At first we create a Paypal bussiness account

As we are just testing Paypal Payment, So we have to create a Paypal Sandbox Account to test payments. So in the first phase of this Android Paypal Integration we will just test with sandbox account

After that fill other account details :

To create a paypal Sandbox Account you can go through this link .
After creating a paypal sandbox account we create paypal Rest api app

To create a Paypal Rest api app you can go through this link .
Now you will get your Client ID, Copy it some where.
Lets we start with a new project in Android Studio from File ⇒ New Project select Empty Activity and go through it.
1.Import the Mobile Ads SDK :
At first here we have to Import paypal android sdk in our app’s project-level build.gradle file .
implementation 'com.paypal.sdk:paypal-android-sdk:2.16.0'
Try to add the latest version of the Mobile Ads SDK. Once that’s done, save the file and perform a Gradle sync.
2. Add Internet Permission to AndroidManifest.xml :
Add the Internet Paermission to access your mobile’s Internet to your app’s AndroidManifest.xml .
<uses-permission android:name="android.permission.INTERNET"/>
AndroidManifest.xml :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.technxtcodelabs.paypal">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.VIBRATE"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SuccessActivity" />
</application>
</manifest>
3. Create a constant java class name as PaypalConfig.java and store your sandbox PAYPAL_CLIENT_ID :
package com.technxtcodelabs.paypal;
public class PaypalConfig {
public static final String PAYPAL_CLIENT_ID = "AbCoUEWWWbaZ_BkuygA9puGqIEYlO_6ZemMVOWF22UJMBm2GL5xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
}
4. Implement Button to the XML Layout :
Create a Button to your XML Layout file i.e. activity_main.xml to display it for better user experience .
<Button
android:id="@+id/subscribe"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Subscribe"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
activity_main.xml :
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/subscribe"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Subscribe"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
5. Create a Layout Resource file :
Now create a Dialog Layout view to show a subscribe popup on click of subscribe button and named the file as subscribe_popup.xml inside Layout Resource.
subscribe_popup.xml :
<?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="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioGroup
android:id="@+id/radioGroup"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_margin="15dp"
tools:ignore="MissingConstraints">
<RadioButton
android:id="@+id/radioButton1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Subscribe for 3 month"
android:textSize="18sp"/>
<RadioButton
android:id="@+id/radioButton2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Subscribe for 6 month"
android:textSize="18sp"/>
<RadioButton
android:id="@+id/radioButton3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Subscribe for 1 year"
android:textSize="18sp"/>
</RadioGroup>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:orientation="horizontal">
<Button
android:id="@+id/cancel"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_marginLeft="15dp"
android:layout_alignParentLeft="true"
android:background="@android:color/holo_red_light"
android:text="Cancel"/>
<Button
android:id="@+id/conti"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_gravity="right"
android:layout_marginRight="15dp"
android:layout_alignParentRight="true"
android:background="@android:color/holo_red_light"
android:text="Continue" />
</RelativeLayout>
</LinearLayout>
6. Implement Paypal payment service to your Main_Activty.java :
Now Add the following code to implement subscribe button click Listener to open the Dialog and Paypal payment service to your project in Main_Activty.java file.
Main_Activity.java :
package com.technxtcodelabs.paypal;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import com.paypal.android.sdk.payments.PayPalConfiguration;
import com.paypal.android.sdk.payments.PayPalPayment;
import com.paypal.android.sdk.payments.PayPalPaymentDetails;
import com.paypal.android.sdk.payments.PayPalService;
import com.paypal.android.sdk.payments.PaymentActivity;
import com.paypal.android.sdk.payments.PaymentConfirmation;
import com.paypal.api.payments.Invoice;
import com.paypal.api.payments.InvoiceNumber;
import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.PayPalRESTException;
import org.json.JSONException;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigDecimal;
public class MainActivity extends AppCompatActivity {
//Paypal request code
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)
.environment(PayPalConfiguration.ENVIRONMENT_SANDBOX)
.clientId(PaypalConfig.PAYPAL_CLIENT_ID)
.merchantName("TechNxt Code Labs")
.merchantPrivacyPolicyUri(
Uri.parse("https://www.paypal.com/webapps/mpp/ua/privacy-full"))
.merchantUserAgreementUri(
Uri.parse("https://www.paypal.com/webapps/mpp/ua/useragreement-full"))
; // or live (ENVIRONMENT_PRODUCTION)
Button subscribe;
private String paymentAmount;
@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);
subscribe = (Button)findViewById(R.id.subscribe);
subscribe.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
subscribe();
}
});
}
private void subscribe() {
final Dialog dialog = new Dialog(this);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
View layout= null;
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
layout = inflater.inflate(R.layout.subscribe_popup, null);
RadioGroup radioGroup = (RadioGroup)layout.findViewById(R.id.radioGroup);
RadioButton radioButton1 = (RadioButton) layout.findViewById(R.id.radioButton1);
RadioButton radioButton2 = (RadioButton)layout.findViewById(R.id.radioButton2);
RadioButton radioButton3 = (RadioButton)layout.findViewById(R.id.radioButton3);
Button conti = (Button)layout.findViewById(R.id.conti);
Button cancel = (Button)layout.findViewById(R.id.cancel);
cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view)
{
dialog.dismiss();
}
});
//Getting the amount from Radio Button
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch(checkedId){
case R.id.radioButton1:
// do operations specific to this selection
paymentAmount = "1";
break;
case R.id.radioButton2:
// do operations specific to this selection
paymentAmount = "2";
break;
case R.id.radioButton3:
// do operations specific to this selection
paymentAmount = "3";
break;
}
}
});
conti.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view)
{
dialog.dismiss();
getPayment();
}
});
dialog.setTitle("Subscribe with Us");
dialog.setCanceledOnTouchOutside(false);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(layout);
dialog.show();
}
private void getPayment() {
//Creating a paypalpayment
PayPalPayment payment = new PayPalPayment(new
BigDecimal(paymentAmount),"USD","Test",PayPalPayment.PAYMENT_INTENT_SALE);
//Creating Paypal Payment activity intent
Intent intent = new Intent(MainActivity.this, PaymentActivity.class);
//putting the paypal configuration to the intent
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
//invoice number
payment.invoiceNumber("321");
//Puting 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, Intent data) {
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);
Log.d("CONFIRM", String.valueOf(confirm));
//if confirmation is not null
if (confirm != null) {
try {
//Getting the payment details
String paymentDetails = confirm.toJSONObject().toString(4);
Log.d("paymentExample",paymentDetails);
Log.i("paymentExample", paymentDetails);
Log.d("Pay Confirm : ", String.valueOf(confirm.getPayment().toJSONObject()));
// Starting a new activity for the payment details and status to show
startActivity(new Intent(MainActivity.this, SuccessActivity.class)
.putExtra("PaymentDetails", paymentDetails);
} 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.");
}
}
}
@Override
public void onDestroy() {
stopService(new Intent(this, PayPalService.class));
super.onDestroy();
}
}
7. Create an another Activity Empty Activity :
Now we create an another activity named as SuccessActivity to get the final result.
8. Implement TextView to your layout resource of second activity :
Now we implement few TextView to show the payment status and details in your activity_success.xml file.
activity_success.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:paddingBottom="5dp"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:paddingTop="5dp"
tools:context=".SuccessActivity">
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Status : " />
<TextView
android:id="@+id/paymentStatus"
android:layout_width="wrap_content"
android:textStyle="bold"
android:layout_height="wrap_content" />
</TableRow>
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Payment Id : " />
<TextView
android:id="@+id/paymentId"
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TableRow>
</TableLayout>
<ProgressBar
android:id="@+id/materialprogressbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minHeight="50dp"
android:minWidth="50dp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
9. Show Paypal Payment Status to Second Activity :
Now we finally get the final Paypal payment status in your SuccessActivity.java file . Add the following code to show the Paypal payment status to your project in SuccessActivity.java file .
SuccessActivity.java :
package com.technxtcodelabs.paypal;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.provider.SyncStateContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.paypal.base.rest.OAuthTokenCredential;
import com.paypal.base.rest.PayPalRESTException;
import org.json.JSONException;
import org.json.JSONObject;
public class ConfirmationActivity extends AppCompatActivity {
private ProgressBar materialProgressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_confirmation);
materialProgressBar = (ProgressBar)findViewById(R.id.materialprogressbar);
//Getting Intent
Intent intent = getIntent();
try {
JSONObject jsonDetails = new JSONObject(intent.getStringExtra("PaymentDetails"));
//Displaying payment details
showDetails(jsonDetails.getJSONObject("response"));
} catch (JSONException e) {
Toast.makeText(ConfirmationActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
private void showDetails(JSONObject jsonDetails, String paymentAmount) throws JSONException {
//Views
TextView textViewId = (TextView) findViewById(R.id.paymentId);
TextView textViewStatus= (TextView) findViewById(R.id.paymentStatus);
//Showing the paypal payment details and status from json object
textViewId.setText(jsonDetails.getString("id"));
textViewStatus.setText(jsonDetails.getString("state"));
}
}
Now run the project/app in android device or any Emulator .