PayPal Express Checkout with PHP and MySQL
Wall Script
Wall Script
Monday, September 25, 2017

PayPal Express Checkout with PHP and MySQL

Most of the people prefer to shop online which made eCommerce to grow rapidly. But, what makes an excellent eCommerce site for the customers? The answer is - an excellent checkout process. There are several different payment options available in the market today. Out of all, Paypal is the most popular and convenient way to get paid. Making it as easy as possible for your customers to pay is essential for increasing conversions and sales. This is why your checkout page is critical. I have already discussed 2 checkout options in my previous articles BrainTree PayPal using PHP and Payment System which were in most trend till day. Now, a new checkout option has been introduced by Paypal which is Paypal Express Checkout option.

PayPal Express Checkout with PHP and MySQL


Live Demo


Database Design
To build the user order system, you have to create three tables such as Users, Products, and Orders.

PayPal Express Checkout with PHP Design

Users
User table contains all the users registration details.
CREATE TABLE users(
uid int AUTO_INCREMENT PRIMARY KEY,
username varchar(50),
password varchar(300),
name varchar(200),
email varchar(300));

Products
This table contains product details.
CREATE TABLE products(
pid int PRIMARY KEY AUTO_INCREMENT,
product varchar(300),
product_img varchar(300),
price int,
currency varchar(10)
);

Orders
This table contains user order details.
CREATE TABLE orders(
oid int PRIMARY KEY AUTO_INCREMENT,
uid_fk int,
pid_fk int,
payerID varchar(300),
paymentID varchar(300),
token varchar(300),
created int
);

Video Tutorial
PayPal Express Checkout with PHP and MySQL


Getting started with PayPal Express Checkout

Create Sandbox Account
Go to PayPal Developer and create a sandbox account for development.
Getting started with PayPal Express Checkout

Make sure choose account type as bussiness and give some PayPal balanace number.
Getting started with PayPal Express Checkout

Create REST API Application
Now go to PayPal dashboard and scroll down, you will find a REST API apps and click on create app button.
Getting started with PayPal Express Checkout

Give your application name and choose your sandbox account. This only works with PayPal business accounts.
Getting started with PayPal Express Checkout

Application Credentials
Here you will find both Sandbox and Live Client ID and Secret values.
Getting started with PayPal Express Checkout

PHP Development
Project structure.
Getting started with PayPal Express Checkout

config.php
Database and PayPal checkout API configuration file. Here you have to modify PayPal credentials for Sandbox and Live. Function getDB() help you to create a PDO connection with MySQL database.
<?php
//ob_start();
error_reporting(0);
session_start();

/* DATABASE CONFIGURATION */
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'username');
define('DB_DATABASE', 'database_name');
define('DB_PASSWORD', 'password');
define("BASE_URL", "http://localhost/PHP-PayPal-ExpressCheckout/");
define('PRO_PayPal', 0); // PayPal live change 0 to 1


if(PRO_PayPal){
    define("PayPal_CLIENT_ID", "##Your Production/Live Client ID##");
    define("PayPal_SECRET", "##Your Production/Live Secret ID##");
    define("PayPal_BASE_URL", "https://api.paypal.com/v1/");
}
else{
    define("PayPal_CLIENT_ID", "##Your Sandbox Client ID##");
    define("PayPal_SECRET", "##Your Sandbox Secret ID##");
    define("PayPal_BASE_URL", "https://api.sandbox.paypal.com/v1/");
}

function getDB()
{
    $dbhost=DB_SERVER;
    $dbuser=DB_USERNAME;
    $dbpass=DB_PASSWORD;
    $dbname=DB_DATABASE;
    $dbConnection = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
    $dbConnection->exec("set names utf8");
    $dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    return $dbConnection;
}
?>


paypalExpress.php
PHP class for all the project operations like user login, getting product details, PayPal backend check etc.
<?php
class paypalExpress
{
    public function userLogin($username,$password)
    {

        $db = getDB();
        $hash_password= hash('sha256', $password);
        $stmt = $db->prepare("SELECT uid FROM users WHERE  username=:username and password=:hash_password");
        $stmt->bindParam("username", $username, PDO::PARAM_STR) ;
        $stmt->bindParam("hash_password", $hash_password, PDO::PARAM_STR) ;
        $stmt->execute();
        $db = null;

        if($stmt->rowCount()==1)
        {
            $data = $stmt->fetch(PDO::FETCH_OBJ);
            $_SESSION['session_uid'] = $data->uid;
            return $data->uid;
        }
        else
        {
            return false;
        }
    }


    // Other functions
}
?>

index.php
Here index is a user login page. Using $paypalExpress->userLogin() function, verifing the user login details.
<?php
require 'config.php';
require 'class/paypalExpress.php';

$errorMsgLogin ='';
if (!empty($_POST['loginSubmit']))
{
    $usernameEmail=$_POST['username'];
    $password=$_POST['password'];
    if(strlen(trim($usernameEmail))>1 && strlen(trim($password))>1 )
    {
        $paypalExpress = new paypalExpress();
        $uid=$paypalExpress->userLogin($usernameEmail,$password);
        if($uid)
        {
            header("Location:home.php"); // Page redirecting to home.php
        }
        else
        {
            $errorMsgLogin="Please check login details.";
        }
    }
}
?>
<form action="" method="post">
    <label>Username</label>
    <input type="text" value="" name="username" class="input" />
    <label>Password</label>
    <input type="password" value="" name="password"  class="input" />
    <div>
    <input type="submit" value=" Log In" name="loginSubmit" />
    </div>
    <div> <?php echo $errorMsgLogin ?></div>
</form>

home.php
Displaying all of the product details. Clicking on order button this will redirect to checkout page for actual payment process.
<?php
require 'config.php';
require 'session.php';
require 'class/paypalExpress.php';
$paypalExpress = new paypalExpress();
$getAllProducts = $paypalExpress->getAllProducts();
?>
//Logout link
<a href="logout.php" class="logout">Logout</a>
<table>
<?php foreach($getAllProducts as $product){ ?>
<tr>
      <td >
      <img src="img/<?php echo $product->product_img; ?>" />
      </td>
      <td>$<?php echo $product->price; ?></td>
       <td >
      <a href="<?php echo BASE_URL.'checkout.php?pid='.$product->pid; ?>" class="wallButton">Order</a></td>
        </tr>
      <?php } ?>
</table>

getProducts
Getting all of the products.
public function getAllProducts()
    {
        $db = getDB();
        $stmt = $db->prepare("SELECT * FROM products");
        $stmt->bindParam("pid", $pid, PDO::PARAM_INT) ;
        $stmt->execute();
        $data = $stmt->