Android Integrating PayPal using PHP, MySQL – Part 1

When you are building an eCommerce app, integrating the payment gateway is one of the most important building blocks of an app. Today we are going to learn how to integrate most popular payment gateway PayPal in our android app.

For an eCommerce app, building android app is not enough. We need to have a server side component too to maintain the inventory, customers, transactions and other important things. So this tutorial covers both the topics by diving the article into two parts. In this part, we are going to learn how to build the PHP, MySQL server and integrating the PayPal REST API. In the next part Android Integrating PayPal using PHP, MySQL – Part 2 we’ll learn how to build the android app and integrate the PayPal gateway.

1. Overview

PayPal provides multiple payment options such as Single Payment (Receives the payment immediately), Future Payments (Can be used for recurring payments) and Profile Sharing (Obtains information about customer). For our use case Single payment is best suited options as we need to get the payment immediately once user purchases some products.

Below diagram explains the complete app flow from listing the products to completing the checkout.

1. First the android app connects with server and fetches the products json. Products json will be parsed and all the products will be displayed on the android app.

2. User selects the products and make the payment using PayPal payment option.

3. After successful payment, PayPal issues the json that contains the payment id.

4. Android app sends the payment id to our server for verification.

5. Server make a REST API call to PayPal along with payment id to verify the payment.

6. PayPal responds a json in which we have to check for “state”: “approved” (and few other flags) for a successful payment.>

2. Creating PayPal App (Client ID & Secret)

In order to make the calls to PayPal API we need to create an app in developer.paypal.com and obtain Client ID & Secret.

1. Log into PayPal’s Developer account. If you are visiting for the first time, register and create a new account.

2. Once logged in, you will be redirected to my apps page where you can create a new app.

3. Give your app name, select developer account and click on create app. Once the app is created, you can notice the Client id & Secret. We’re gonna need these keys in our both server and client apps.

3. PayPal Sandbox Test Account

Paypal provides a test environment called sandbox to test the app before going live. These test accounts comes with paypal balance credited into it using which you can make test purchases. To get your sandbox account credentials, follow below steps.

1. Go to PayPal’s Developer account and click on Accounts under Sandbox on the left panel.

2. On the right you can see the sandbox test accounts. Select the buyer email and click on Profile.

3. In the popup window, click on Change Password to change the password in case if you are not sure about the password.

4. In the popup window, goto Funding tab to see the test balance.

You have to use these credentials to test the app in sandbox environment.

4. Downloading PayPal PHP Rest API SDK

It’s always a good practise to use the SDKs provided by the vendors rather than building ourselves. Paypal provides REST API SDK for multiple platforms. As we choose to write the server side code in PHP, download the latest release of PayPal-PHP-SDK.

5. Downloading Slim Framework

PHP Slim library allows you to write simple and efficient REST APIs. This framework we use here to generate json responses. To know more about Slim, read my previous article Building REST API for Android app using PHP, Slim and MySQL about building a perfect REST API when your app needs to talk to a php, mysql server.

6. Downloading & Installing WAMP

Download and Install WAMP from http://www.wampserver.com/en/ and start the program from Start => All Programs. Once started, you should be able to access via http://localhost/ in the browser.

Watch the below video to know how to download and install WAMP.

7. Creating MySQL Database

Overall we are going to create four tables. users (to store the customer information), products (to store the product information like name, price, description), payments (to store the paypal transactions) and sales (to keep the product sales done by customers). This is very simple database design. In real world scenario, the database will be more complex than this.

Open phpmyadmin by going to http://localhost/phpmyadmin and execute below SQL query to create required database and tables. Also I am inserting a user and few sample products for testing.

8. Creating PHP Project

Once you are done creating the database, let’s create the PHP project. Below is the project structure that we are going to create now. Carefully place all the folders/files in appropriate location as shown in the diagram. I am using the Netbeans IDE to develop my PHP project.

In the project, the purpose of each file/folder is

include – All the config & helper classes goes into this directorylibs – All the third party libraries (Slim & PayPal) will be placed herev1 – It is the version directory of our API

index.php – All the API calls will be handled in this file.htaccess – Contains Apache web server configuration

1. Goto the directory where wamp is installed (generally wamp will be installed at c:\wamp) and open www directory. This is where all the php projects will be placed.

2. Inside www folder, create a folder named PayPalServer. This is the root directory for our project.

3. Now inside PayPalServer, create three folders named include, libs and v1.

4. Paste the Slim Framework and PayPal SDK in libs folder.

5. Create a file named Config.php in the include directory and add the below code. This file contains configuration values like database credentials, paypal client id & secret and default currency. Change the username and password with your mysql credentials.

9. Finally create index.php inside v1 and paste below code. This is most important file where we handle all the REST requests using Slim Framework.

In the below code

echoResponse() – Prints final json response when API call is made

$app->get(‘/products’.. – Fetches all the products from products table and prints in json format

$app->post(‘/verifyPayment’.. – Verifies the paypal payment on the server side that was done on mobile app. This server side verification is very important for every paypal transaction to avoid fraudulent payments.

Hi there! I am Founder at androidhive and programming enthusiast. My skills includes Android, iOS, PHP, Ruby on Rails and lot more. If you have any idea that you would want me to develop? Let’s talk: ravi@androidhive.info

Thats not an emulator. I record the video on a real device and while editing the video, I’ll place it on nexus 5 png image.

Manoj Behera

awesome!

Pornpoj Pojjanapatee

Awesome!!! Thank you very much!

Cristopher

Excelente aporte

Trong Hieu

good thread !

Gunner

Thanks Bro, Fantastic thread can’t wait to try it out

pushpa

If i want my user to select bank and make the payment from those banks. the amount will be credited to apps admin account. how can i do that using above tutorial?

pushpa

we can use paypal for online baking in India right? which is the best payment gateway? 1stly i want to test my app so i would need free testing initially.

pushpa

What is the difference between google wallet and paypal? does google wallet allows free trial of app?

Romeo

Hi Ravi, thank you for your tutorials, I have implement your code, but when fetching the products it shows error org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject. I put the database online, and I cannot find what the caused of it, can you help me, thank you

Hi Ravi, my app just crushes when i load. java.lang.noclassdefFoundError thats the error

Ejeu Emmanuel

Figured how to make it work by creating a new project and copying file by file. It no longer crashes. I am now working on posting data from the android to php and its proving to be challenging

Sonam Singh

sir m following your project but m not getting access to v1 folder. whenever i browse for “http://localhost:90/PayPalServer/v1/products” i m getting error “500 Internal Server Error”. Please do help me to come out of it.

tamil

im gettting the same error ,if u find a solution to this please do help me

Siddharth Khetan

Sonam Singh Go to your wamp Server where u get Apache Folder Open it(C:wampbinapacheapache2.4.9)
Find the httpd.conf file.
Inside the httpd.conf file uncomment the line LoadModule rewrite_module modules/mod_rewrite.so (remove the pound ‘#’ sign from in front of the line)

Your Problem is solved..

Siddharth Khetan

Sonam Singh Go to your wamp Server where u get Apache Folder Open it(C:wampbinapacheapache2.4.9)
Find the httpd.conf file.
Inside the httpd.conf file uncomment the line LoadModule rewrite_module modules/mod_rewrite.so (remove the pound ‘#’ sign from in front of the line)

Hi Ravi, i searched and searched through my code and i found the problem, it was simply, i just miss placed the theme, so now instead of using activity, i want to use it in a fragment, can you help me how am i going to put products model into fragment?

Hi Ravi, I used the other tutorial on google cloud messaging, now I am facing problem connecting to the database, I am using a real server as my local host is not working due to mbstring missing on php. can you help on how to connect the google cloud messaging to a server?

Ravi Sir, Thank you very much for this wonderful tutorial ,It was very helpful,
I want to send a unique user Id every time the payment gets verified succefully but I am new one in PHP so not getting any idea how to do this , please let me know if you can help

Hi I want some help with Paypal, I want to update the individual user Id with the payament details so I can organise it according to particular user , the user id should be sent from the app with the payament details. Please give me some idea about how to do this.

Itai Martsiano

Hi!
I build my server side app in java, is there away to make all the requests from PayPal server using java and not in PHP?
thanks,
Itai.

Sachin Tandel

in second url what value of paymentId and paymentClientJso?

Sachin Tandel

when i click on checkout button then i got dialog which display there was a problem communicationg with paypal serever.plz try again.

Michał Pankowski

Hello,

I have a big problem with verify transaction.

I add to cart product, checkout, pay and waiting for verify…and nothing there is a error with

// Paypal transactions

$transaction = $payment->getTransaction()[0];

Geraldo K Fillipus

Hi, when you run app what problem did you faced perhaps you can help, to its crashing

Michał Pankowski

I have faced with this problem when I clicked on the button to Accept payment. There were no response.

mercy

I have a problem with my index,php it throws this error
Fatal error: Call to a member function fetch() on null line 55.kindly help me out

Sega Nightshade

i dont know why we have table users while we dont use anything information from it.i think it better if you can save pay method to an account we will create and store table like google play.

whatismyusername

@ravi8x:disqus can I just have the paypalpaymentID in the userid table ? I thought I only need user email for paypal payment ? is the paypalpaymentID the user email too??

Arbaaz

@ravi8x:disqus Hi Ravi would you please tell me how i can add more payment options like via credit or debit card.

Prashant Vidja

hello..
i have used your code with paypal android and php-mysql server.
but issue is not insert any value in mysql server.
so please help to fix it.