integrate Paypal in Android Application
integrate Paypal in Android Application

If you wish to sell something through your app, then you need to integrate a payment method in your app.One of the worldwide used payment method is Paypal.

This article shall guide you on integrating payment method in your app, using the SDK provided by Paypal.

Sandbox Feature:

Paypal allows a sandbox feature to test payments since testing with actual money wouldn’t have been possible. Start by creating two sandbox accounts. The first one being the ‘Personal Account’ from where you shall pay. And the second one being the ‘business Account’ from where you shall receive the payment.

  • Open up this link and login with your paypal account.
  • Fill up the form to create accounts. Two accounts should be created, for the first one select ‘Personal’ in the Account Type. And for the second one select ‘Business’.

Creating Paypal App:

  • Now open up this link to create a Paypal app.

  • Next you will see your client ID which you should copy somewhere.

Creating Android Project:

  • First create a new Android Project. We created PayPalIntegration.
  • Now create a class named PayPalConfig.java in your package and write the following code:
    PayPalConfig.java:
    package net.simplifiedcoding.paypalintegration;
     
    
    public class PayPalConfig {
     
        public static final String PAYPAL_CLIENT_ID = "YOUR PAYPAL CLIENT ID";
     
    }
    
    

     

  • Now we shall add a Paypal SDK to our project.
  • Go inside the app level build.gradle file under the Gradle Scripts.
  • You’ll see the dependencies block inside the app level build.gradle file. Add your Paypal SDK here, by adding the following code:

build.gradle:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.3.0'
 
    //You have to add this line
    compile 'com.paypal.sdk:paypal-android-sdk:2.14.2'
}

 

  • Next sync your project.
  • As a demo, we shall be creating a simple EditText where you can put the payment amount to pay.
  • Go inside the acitivity_main.xml and write the following code:

acitivity_main.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="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="net.simplifiedcoding.paypalintegration.MainActivity">
 
 
    <LinearLayout
        android:id="@+id/linearLayout"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_centerVertical="true">
 
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Enter Amount"
            android:textAlignment="center" />
 
        <EditText
            android:id="@+id/editTextAmount"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textAlignment="center" />
 
        <Button
            android:id="@+id/buttonPay"
            android:text="Pay Now"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
 
    </LinearLayout>
 
 
</RelativeLayout>

 

  • You shall see the following UI with the above given code:

  • Come inside MainActivity.java and declare objects for views and add listener to the button:

MainActivity.java:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
 
    //The views
    private Button buttonPay;
    private EditText editTextAmount;
    
    //Payment Amount 
    private String paymentAmount;

 

  • Initialize the views and add listener to the buttons inside the onCreate() function:

MainActivity.java:

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        buttonPay = (Button) findViewById(R.id.buttonPay);
        editTextAmount = (EditText) findViewById(R.id.editTextAmount);
 
        buttonPay.setOnClickListener(this);
    }

 

  • Next create a method named getPayment() and call it on button click:

MainActivity.java:

@Override
    public void onClick(View v) {
        getPayment();
    }

 

  • Now we need a PayPal Configuration Object and a Request Code to get Payment from PayPal:
 //Paypal intent request code to track onActivityResult method
    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)
            .clientId(PayPalConfig.PAYPAL_CLIENT_ID)

 

  • Start PayPalService inside onCreate() method:
       Intent intent = new Intent(this, PayPalService.class);
     
            intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
     
            startService(intent);
    

     

  • When the app closes, the service should be destroyed:
   @Override
    public void onDestroy() {
        stopService(new Intent(this, PayPalService.class));
        super.onDestroy();
    }

 

  • Now complete the method getPayment() with the following code:
 private void getPayment() {
        //Getting the amount from editText
        paymentAmount = editTextAmount.getText().toString();
 
        //Creating a paypalpayment 
        PayPalPayment payment = new PayPalPayment(new BigDecimal(String.valueOf(paymentAmount)), "USD", "Simplified Coding Fee",
                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);
 
        //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);
    }

 

  • This  method invokes the onActivityResult() method after completion. So override onActivityResult() and write the following code instead:
  @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent 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);
                        Log.i("paymentExample", paymentDetails);
 
                        //Starting a new activity for the payment details and also putting the payment details with intent 
                        startActivity(new Intent(this, ConfirmationActivity.class)
                                .putExtra("PaymentDetails", paymentDetails)
                                .putExtra("PaymentAmount", paymentAmount));
 
                    } 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.");
            }
        }
    }

 

  • We can see the string paymentDetails  in the above code. It is in json format as follows. It contains the payment detail with a unique payment id:
{
    "client": {
        "environment": "sandbox",
        "paypal_sdk_version": "2.0.0",
        "platform": "iOS",
        "product_name": "PayPal iOS SDK;"
    },
    "response": {
        "create_time": "2014-02-12T22:29:49Z",
        "id": "PAY-564191241M8701234KL57LXI",
        "intent": "sale",
        "state": "approved"
    },
    "response_type": "payment"
}

 

  • Next we shall another activity to show the payment details. So create a new empty activity, we created ConfirmationActivity.java.
  • Inside layout file for this activity write the following xml code:
<?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="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="net.simplifiedcoding.paypalintegration.ConfirmationActivity">
 
    <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="Payment Amount : " />
 
            <TextView
                android:id="@+id/paymentAmount"
                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="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>
 
</RelativeLayout>

 

  • In the ConfirmationActivity.java write the following code:

ConfirmationActivity.java:

package net.simplifiedcoding.paypalintegration;
 
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
 
import org.json.JSONException;
import org.json.JSONObject;
 
public class ConfirmationActivity extends AppCompatActivity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_confirmation);
 
        //Getting Intent
        Intent intent = getIntent();
        
 
        try {
            JSONObject jsonDetails = new JSONObject(intent.getStringExtra("PaymentDetails"));
            
            //Displaying payment details 
            showDetails(jsonDetails.getJSONObject("response"), intent.getStringExtra("PaymentAmount"));
        } catch (JSONException e) {
            Toast.makeText(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);
        TextView textViewAmount = (TextView) findViewById(R.id.paymentAmount);
        
        //Showing the details from json object 
        textViewId.setText(jsonDetails.getString("id"));
        textViewStatus.setText(jsonDetails.getString("state"));
        textViewAmount.setText(paymentAmount+" USD");
    }
}

 

Now run the application and if you see the status as approved, means it is working and you can verity the payment at your sandbox paypal account.

Your app with an integrated payment method is now good to go!

Leave a Reply