In this post we will learn how to integrate paypal payment in your android application. In this Android Paypal Integration Tutorial we will be using the official SDK provided by paypal.
Now days a payment option is very much essential for many apps if you are selling something through your apps. And PayPal is one of the major payment method used worldwide.
Thats why I thought about posting this Android PayPal Integration Tutorial. So lets begin.
Table of Contents
Android Paypal Integration Tutorial Video Demo
You can checkout this video before moving on to the tutorial to know what actually we will be creating.
Android Paypal Integration Tutorial
Creating Paypal Sandbox Account
Now it is very obvious that you will not be testing your payment with actual money. And that is why paypal has given a sandbox feature. You can create sandbox accounts to test payments. So in the first phase of this Android Paypal Integration Tutorial we will create two sandbox accounts. One personal account from where you pay, and one Business Account where you will receive the paid amount. So lets begin.
- Go to this link and login with your paypal account.
- Fill the form to create account. Remember you need to create two accounts. For first account select Account Type to Personal and for Other select Account Type to Business.
Creating Paypal REST API App
- Now go to this link to create a paypal app.
- Put your app name and click on Create App.
- Now you will see your Client ID. Copy it some where. Thats all for the Paypal Side. Now we will move to Android Project.
Creating Android Project
Adding PayPal Client ID
- Create a new Android Project. I created PayPalIntegration.
- In your package create a class named PayPalConfig.java and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 |
package net.simplifiedcoding.paypalintegration; /** * Created by Belal on 5/1/2016. */ public class PayPalConfig { public static final String PAYPAL_CLIENT_ID = "YOUR PAYPAL CLIENT ID"; } |
- In the above code you have to put your paypal client id. Now we need to add PayPal SDK to our project.
Adding PayPal SDK
- We are using Android Studio so go inside your app level build.gradle file. (Someone said that he doesn’t understand app level build.gradle) So I am posting the screenshot. The highlighted one is app level build.gradle file and above that you have the project level build.gradle file. You need to open the app level build.gradle file.
- Inside the app level build.gradle file you will see dependencies block. Inside that you need to add your paypal sdk. So add the following code.
1 2 3 4 5 6 7 8 9 10 |
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' } |
- Now sync your project and your done.
Integrating Paypal Payment
- As this is a sample demonstrating only paypal payment. I will not give a real world demo. Instead I am creating a simple EditText where you can put the payment amount to pay. So come inside your acitivity_main.xml and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
<?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 will get the following UI with the above given code.
- Now come inside MainActivity.java and declare objects for your views and add listener to the button.
1 2 3 4 5 6 7 8 9 10 11 |
//Implementing click listener to our class public class MainActivity extends AppCompatActivity implements View.OnClickListener { //The views private Button buttonPay; private EditText editTextAmount; //Payment Amount private String paymentAmount; |
- Inside onCreate() initialize the views and add listener to the buttons.
1 2 3 4 5 6 7 8 9 10 11 12 |
@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); } |
- Now create a method named getPayment() and call it on button click.
1 2 3 4 5 6 |
@Override public void onClick(View v) { getPayment(); } |
- Now to get Payment from PayPal we need a PayPal Configuration Object and a Request Code.
1 2 3 4 5 6 7 8 9 10 11 12 |
//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) |
- Inside onCreate() method we need to start PayPalService.
1 2 3 4 5 6 7 |
Intent intent = new Intent(this, PayPalService.class); intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config); startService(intent); |
- We should destroy the service when app closes.
1 2 3 4 5 6 7 |
@Override public void onDestroy() { stopService(new Intent(this, PayPalService.class)); super.onDestroy(); } |
- Now complete the method getPayment() with the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
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); } |
- The above method will invoke the onActivityResult() method after completion. So override onActivityResult() and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
@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."); } } } |
- In the above code you can see the string paymentDetails. It is in json format as follows. It contains the payment detail with a unique payment id.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
{ "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" } |
- In this post I am not covering the verification process. As you need to verify the payment at your server with the payment id you are seeing in the above json.
You need to store the unique id at your server after the verification. In the next part we will cover the verification process at the server.
In this tutorial we will show these details to another activity. - Now we will create another activity where we will show the payment details. So create a new empty activity I created ConfirmationActivity.java. And inside layout file for this activity write the following xml code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
<?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> |
- Now in the java file which is ConfirmationActivity.java write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
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"); } } |
- Thats it now just run your application and you will get the following output.
- If you are seeing the status as approved you can verity the payment at your sandbox paypal account.
- Bingo! it is working absolutely fine. You can download my source code from GitHub. Just go to the link given below.
[sociallocker id=1372]Android Paypal Integration Tutorial Source Code[/sociallocker]
So thats all for this Android Paypal Integration Tutorial friends. Feel free to leave your comments if having any troubles regarding this Android PayPal Integration Tutorial. Thank You 🙂