Shopping Cart with PayPal Payment Gateway in PHP

Shopping cart with payment gateway is a must-have functionality for an e-commerce website. The payment gateway allows the buyers to make payment online at the time of checkout. PayPal standard checkout is one of the easiest option to integrate payment gateway in the web application. A shopping cart helps users to select multiple products and PayPal allows users to checkout with credit/debit card payment.

PHP shopping cart with PayPal makes e-commerce web applications more user-friendly and feature reach. In this tutorial, we will show you how to build shopping cart with payment gateway in PHP. This example shopping cart system uses PHP SESSION to integrate cart functionality and PayPal for online credit/debit card payment.

The following functionality will be implemented in the PHP Shopping Cart system.

  • List the products on the webpage.
  • Custom shopping cart library with PHP.
  • Add multiple products to the cart.
  • Checkout cart items with online payment.
  • Payment with PayPal standard checkout and order submission.

PayPal REST API Credentials

To get started with the PayPal REST API, you need to create a developer account on the PayPal Developer Dashboard.

PayPal provides two environments, Sandbox and Live. Sandbox environment allows developers to test the PayPal checkout process before making it Live for production usage. You can create sandbox Business and Personal accounts from the Sandbox Accounts section.

In the PayPal Developer Dashboard, you can switch between the Sandbox and Live environment from the toggle button placed at the top-right corner.

Create Sandbox Accounts:

  • Sandbox Merchant Account: Create a sandbox business account with Account type: Business. This merchant account is required to attach at the time of the REST API app.
  • Sandbox Buyer Account: Create a sandbox buyer account with Account type: Personal. This buyer account will be used to test payment.
    • After the sandbox buyer account creation, an email ID and password will be generated. You can use these credentials to log in at the time of testing the PayPal checkout.

Create REST API App:
In the Apps & Credentials section, create a new REST API App with Type: Merchant.

  • Select a business account under the Sandbox Account dropdown.

After the App creation, the Client ID and Secret will be generated.

  • Copy these API credentials to later use in the script.

Live REST API Credentials:
At the top right corner, toggle the switch to Live. Then navigate to the Apps & Credentials section.

  • Create a new REST API App, you will get the credentials (Client ID and Secret) for the Live environment.

Getting Started

We suggest you follow the steps mentioned in our PHP Shopping Cart and PayPal Standard Checkout integration tutorials to initial setup.

Before getting started, take a look at the file structure of the PHP shopping cart with PayPal script.

php_shopping_cart_with_paypal/
├── index.php
├── view-cart.php
├── checkout.php
├── order-status.php
├── config.php
├── dbConnect.php
├── cartAction.php
├── Cart.class.php
├── paypal_checkout_validate.php
├── PaypalCheckout.class.php
├── js/
|   └── jquery.min.js
├── css/
|   ├── bootstrap.min.css
|   └── style.css
└── images/

Create Database Tables

Some tables (products, customers, orders, order_items, and transactions) are required in the database to store product, order, and payment details.

The following SQL creates a products table to store the product information in the MySQL database.

CREATE TABLE `products` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `image` varchar(255) NOT NULL,
  `name` varchar(200) NOT NULL,
  `description` text NOT NULL,
  `price` float(10,2) NOT NULL,
  `created` datetime NOT NULL,
  `modified` datetime NOT NULL,
  `status` tinyint(1) NOT NULL DEFAULT 1 COMMENT '1=Active | 0=Inactive',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

The following SQL creates a customers table to store the user contact information in the MySQL database.

CREATE TABLE `customers` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `first_name` varchar(25) NOT NULL,
  `last_name` varchar(25) NOT NULL,
  `email` varchar(50) NOT NULL,
  `phone` varchar(15) NOT NULL,
  `address` text NOT NULL,
  `created` datetime NOT NULL,
  `modified` datetime NOT NULL,
  `status` tinyint(1) NOT NULL DEFAULT 1 COMMENT '1=Active | 0=Inactive',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

The following SQL creates an orders table in the MySQL database to store the order info that submitted by the customer. The customer_id will be a FOREIGN KEY which is associated with the customers table.

CREATE TABLE `orders` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `customer_id` int(11) NOT NULL,
  `grand_total` float(10,2) NOT NULL,
  `payment_status` tinyint(1) NOT NULL DEFAULT 0 COMMENT '1=Paid | 0=Pending',
  `created` datetime NOT NULL,
  `status` enum('Pending','Completed','Cancelled') NOT NULL DEFAULT 'Pending',
  PRIMARY KEY (`id`),
  KEY `customer_id` (`customer_id`),
  CONSTRAINT `orders_ibfk_1` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

The following SQL creates an order_items table to store the items of each order in the MySQL database. The order_id will be a FOREIGN KEY which is associated with the orders table.

CREATE TABLE `order_items` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `order_id` int(11) NOT NULL,
  `product_id` int(11) NOT NULL,
  `quantity` int(5) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `order_id` (`order_id`),
  CONSTRAINT `order_items_ibfk_1` FOREIGN KEY (`order_id`) REFERENCES `orders` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

The following SQL creates a transactions table to store the payment details in the MySQL database. The order_id will be a FOREIGN KEY which is associated with the orders table.

CREATE TABLE `transactions` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `order_id` int(11) DEFAULT NULL,
  `item_name` varchar(255) DEFAULT NULL,
  `payer_id` varchar(50) DEFAULT NULL,
  `payer_name` varchar(50) DEFAULT NULL,
  `payer_email` varchar(50) DEFAULT NULL,
  `payer_country` varchar(20) DEFAULT NULL,
  `merchant_id` varchar(255) DEFAULT NULL,
  `merchant_email` varchar(50) DEFAULT NULL,
  `paypal_order_id` varchar(50) NOT NULL,
  `transaction_id` varchar(50) NOT NULL,
  `paid_amount` float(10,2) NOT NULL,
  `paid_amount_currency` varchar(10) NOT NULL,
  `payment_source` varchar(50) DEFAULT NULL,
  `payment_status` varchar(25) NOT NULL,
  `created` datetime NOT NULL,
  `modified` datetime NOT NULL,
  PRIMARY KEY (`id`),
  KEY `order_id` (`order_id`),
  CONSTRAINT `transactions_ibfk_1` FOREIGN KEY (`order_id`) REFERENCES `orders` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

PayPal API, Currency and Database Configuration (config.php)

In the config.php file, constant variables of the Currency, PayPal Checkout API, and database settings are defined.

Product Information:

  • CURRENCY – Currency code.
  • CURRENCY_SYMBOL – Graphic symbol of currency.

Database Constants:

  • DB_HOST – Specify the database host.
  • DB_USERNAME – Specify the database username.
  • DB_PASSWORD – Specify the database password.
  • DB_NAME – Specify the database name.

PayPal REST API Constants:

  • PAYPAL_SANDBOX – (TRUE/FALSE) Set PayPal environment, Sandbox or Live.
  • PAYPAL_SANDBOX_CLIENT_ID – Client ID of PayPal Sandbox REST API App.
  • PAYPAL_SANDBOX_CLIENT_SECRET – Secret key of PayPal Sandbox REST API App.
  • PAYPAL_PROD_CLIENT_ID – Client ID of PayPal Live REST API App.
  • PAYPAL_PROD_CLIENT_SECRET – Secret key of PayPal Live REST API App.
<?php 
// Common settings
define('CURRENCY''USD');
define('CURRENCY_SYMBOL''$');
 
// Database configuration 
define('DB_HOST''MySQL_Database_Host');
define('DB_USERNAME''MySQL_Database_Username');
define('DB_PASSWORD''MySQL_Database_Password'); 
define('DB_NAME''MySQL_Database_Name');

/* PayPal REST API configuration
 * You can generate API credentials from the PayPal developer panel.
 * See your keys here: https://developer.paypal.com/dashboard/
 */
define('PAYPAL_SANDBOX'TRUE); //TRUE=Sandbox | FALSE=Production
// PayPal API keys for Sandbox
define('PAYPAL_SANDBOX_CLIENT_ID''Insert_PayPal_Client_ID_For_Sandbox_Here');
define('PAYPAL_SANDBOX_CLIENT_SECRET''Insert_PayPal_Secret_Key_For_Sandbox_Here');
// PayPal API keys for Production
define('PAYPAL_PROD_CLIENT_ID''Insert_Live_PayPal_Client_ID_Here');
define('PAYPAL_PROD_CLIENT_SECRET''Insert_Live_PayPal_Secret_Key_Here');

// Start session
if(!session_id()){
    
session_start();
}
?>

Note that: PayPal API Client ID and Secret will be found in the REST API App section of your PayPal Developer Dashboard.

Database Connection (dbConnect.php)

The dbConnect.php file is used to connect and select the MySQL database using PHP.

<?php 
// Include the configuration file
require_once 'config.php';

// Connect with the database 
$db = new mysqli(DB_HOSTDB_USERNAMEDB_PASSWORDDB_NAME); 
 
// Display error if failed to connect 
if ($db->connect_errno) { 
    
printf("Connect failed: %s\n"$db->connect_error); 
    exit(); 
}
?>

PayPal Checkout & Cart Handler Library

We will use two custom PHP libraries, named PaypalCheckout.class.php and Cart.class.php to handle PayPal check and shopping cart related operations.

  • The PaypalCheckout library (PaypalCheckout.class.php) helps to validate transactions and retrieve order details with PayPal Orders REST API using PHP.
  • The Cart library (Cart.class.php) helps to process shopping cart operations with SESSION in PHP.

Bootstrap and jQuery Library

We will use the Bootstrap 5 library to design UI elements in HTML.

<link href="css/bootstrap.min.css" rel="stylesheet">

The jQuery library is used in the cart page to update cart items via AJAX.

<script src="js/jquery.min.js"></script>

Products list (index.php)

Initially, all the products are fetched from the database and listed in a grid view.

  • Add to Cart button is attached to each product box.
  • Add to Cart button redirects the user to the cartAction.php page with action type (action=addToCart) and respective product ID (id).
  • In the basket, the number of the cart items is shown which redirects the user to the shopping cart page.
<?php 
// Include the database connection file
require_once 'dbConnect.php';

// Initialize shopping cart class
include_once 'Cart.class.php';
$cart = new Cart;

// Fetch products from the database
$sqlQ "SELECT * FROM products";
$stmt $db->prepare($sqlQ);
$stmt->execute();
$result $stmt->get_result();
?> <div class="row g-5"> <!-- Cart basket --> <div class="col-12 mb-2"> <div class="text-end"> <a href="view-cart.php" class="btn btn-outline-secondary" title="View Cart"><i class="icart"></i> (<?php echo ($cart->total_items() > 0)?$cart->total_items().' Items':0?>)</a> </div> </div> <!-- Product list --> <div class="col-12"> <div class="row row-cols-1 row-cols-md-3 g-4">             <?php
            
if($result->num_rows 0){
                while(
$row $result->fetch_assoc()){
                    
$proImg = !empty($row["image"])?'images/products/'.$row["image"]:'images/demo-img.png';
            
?> <div class="col"> <div class="card h-100"> <img src="<?php echo $proImg?>" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title"><?php echo $row["name"]; ?></h5> <h6 class="card-subtitle mb-2 text-muted">Price: <?php echo CURRENCY_SYMBOL.$row["price"].' '.CURRENCY?></h6> <p class="card-text"><?php echo $row["description"]; ?></p> <a href="cartAction.php?action=addToCart&id=<?php echo $row["id"]; ?>" class="btn btn-primary">Add to Cart</a> </div> </div> </div> <?php } }else{ ?> <p>Product(s) not found.....</p> <?php ?> </div> </div> </div>

Shopping Cart (view-cart.php)

All the cart items are retrieved from the SESSION using the Cart library and listed in a tabular format.

  • The user can update the quantity and remove items from the cart.
<?php 
// Include the configuration file
require_once 'config.php';

// Initialize shopping cart class
include_once 'Cart.class.php';
$cart = new Cart;
?> <div class="row g-5"> <div class="cart"> <div class="col-12"> <div class="table-responsive"> <table class="table table-striped cart"> <thead> <tr> <th width="10%"></th> <th width="35%">Product</th> <th width="15%">Price</th> <th width="15%">Quantity</th> <th width="20%">Total</th> <th width="5%"> </th> </tr> </thead> <tbody>                     <?php
                    
if($cart->total_items() > 0){
                        
// Get cart items from session
                        
$cartItems $cart->contents();
                        foreach(
$cartItems as $item){
                            
$proImg = !empty($item["image"])?'images/products/'.$item["image"]:'images/demo-img.png';
                    
?> <tr> <td><img src="<?php echo $proImg?>" alt="..."></td> <td><?php echo $item["name"]; ?></td> <td><?php echo CURRENCY_SYMBOL.$item["price"].' '.CURRENCY?></td> <td><input class="form-control" type="number" value="<?php echo $item["qty"]; ?>" onchange="updateCartItem(this, '<?php echo $item["rowid"]; ?>')"/></td> <td><?php echo CURRENCY_SYMBOL.$item["subtotal"].' '.CURRENCY?></td> <td><button class="btn btn-sm btn-danger" onclick="return confirm('Are you sure to remove cart item?')?window.location.href='cartAction.php?action=removeCartItem&id=<?php echo $item["rowid"]; ?>':false;" title="Remove Item"><i class="itrash"></i> </button> </td> </tr> <?php } }else{ ?> <tr><td colspan="6"><p>Your cart is empty.....</p></td> <?php ?> <?php if($cart->total_items() > 0){ ?> <tr> <td></td> <td></td> <td></td> <td><strong>Cart Total</strong></td> <td><strong><?php echo CURRENCY_SYMBOL.$cart->total().' '.CURRENCY?></strong></td> <td></td> </tr> <?php ?> </tbody> </table> </div> </div> <div class="col mb-2"> <div class="row"> <div class="col-sm-12 col-md-6"> <a href="index.php" class="btn btn-block btn-secondary"><i class="ialeft"></i>Continue Shopping</a> </div> <div class="col-sm-12 col-md-6 text-end"> <?php if($cart->total_items() > 0){ ?> <a href="checkout.php" class="btn btn-block btn-primary">Proceed to Checkout<i class="iaright"></i></a> <?php ?> </div> </div> </div> </div> </div>
<script>
function updateCartItem(obj,id){
    $.get("cartAction.php", {action:"updateCartItem", id:id, qty:obj.value}, function(data){
        if(data == 'ok'){
            location.reload();
        }else{
            alert('Cart update failed, please try again.');
        }
    });
}
</script>

Checkout and Payment (checkout.php)

In the checkout page, the buyer can preview the cart items before order submission.

  • Once the billing details are submitted, the PayPal payment button will appear.
  • The buyer can select credit/debit card or PayPal to make payment online.
  • The payment process is handled by the REST API (paypal_checkout_validate.php) using PayPal standard checkout system.
  • On payment success, the buyer will be redirected to the order status page.
<?php 
// Include the configuration file
require_once 'config.php';

// Initialize shopping cart class
include_once 'Cart.class.php';
$cart = new Cart;

// If the cart is empty, redirect to the products page
if($cart->total_items() <= 0){
    
header("Location: index.php");
    exit();
}

$paypal_item_desc 'Cart Order ('.$cart->total_items().' items)';
$paypal_total_amount $cart->total()
?>
<!-- PayPal JS SDK -->
<script src="https://www.paypal.com/sdk/js?client-id=<?php echo PAYPAL_SANDBOX?PAYPAL_SANDBOX_CLIENT_ID:PAYPAL_PROD_CLIENT_ID?>&currency=<?php echo CURRENCY?>"></script>
<div class="row g-5">
    <div class="col-12">
        <div class="checkout">
            <div class="row">
                <div class="col-md-4 order-md-2 mb-4">
                    <h4 class="d-flex justify-content-between align-items-center mb-3">
                        <span class="text-primary">Your Cart</span>
                        <span class="badge bg-primary rounded-pill"><?php echo $cart->total_items(); ?></span>
                    </h4>
                    <ul class="list-group mb-3">
                    <?php 
                    
if($cart->total_items() > 0){
                        
// Get cart items from session
                        
$cartItems $cart->contents();
                        foreach(
$cartItems as $item){
                    
?> <li class="list-group-item d-flex justify-content-between lh-condensed"> <div> <h6 class="my-0"><?php echo $item["name"]; ?></h6> <small class="text-muted"><?php echo CURRENCY_SYMBOL.$item["price"]; ?>(<?php echo $item["qty"]; ?>)</small> </div> <span class="text-muted"><?php echo CURRENCY_SYMBOL.$item["subtotal"]; ?></span> </li> <?php } } ?> <li class="list-group-item d-flex justify-content-between"> <span>Total (<?php echo CURRENCY?>)</span> <strong><?php echo CURRENCY_SYMBOL.$cart->total(); ?></strong> </li> </ul> <a href="index.php" class="btn btn-sm btn-success">+ add items</a> </div> <div class="col-md-8 order-md-1"> <div class="overlay hidden"><div class="overlay-content"><img src="images/loading.gif" alt="Processing..."/></div></div> <div id="billingWrap"> <h4 class="mb-3">Billing Details</h4> <div class="status-msg"></div> <form id="billingFrm" action="#" method="post"> <div class="row"> <div class="col-md-6 mb-3"> <label for="first_name">First Name</label> <input type="text" class="form-control" name="first_name" value="<?php echo !empty($postData['first_name'])?$postData['first_name']:''?>" required> </div> <div class="col-md-6 mb-3"> <label for="last_name">Last Name</label> <input type="text" class="form-control" name="last_name" value="<?php echo !empty($postData['last_name'])?$postData['last_name']:''?>" required> </div> </div> <div class="mb-3"> <label for="email">Email</label> <input type="email" class="form-control" name="email" value="<?php echo !empty($postData['email'])?$postData['email']:''?>" required> </div> <div class="mb-3"> <label for="phone">Phone</label> <input type="text" class="form-control" name="phone" value="<?php echo !empty($postData['phone'])?$postData['phone']:''?>" required> </div> <div class="mb-3"> <label for="last_name">Address</label> <input type="text" class="form-control" name="address" value="<?php echo !empty($postData['address'])?$postData['address']:''?>" required> </div> <hr class="my-4"> <input type="hidden" name="action" value="placeOrder"/> <input class="btn btn-primary btn-block" type="submit" name="checkoutSubmit" value="Continue"> </form> </div> <div id="paymentWrap" class="hidden"> <h4 class="mb-3">Proceed with Payment</h4> <div class="status-msg-pay"></div> <!-- Set up a container element for the button --> <div id="paypal-button-container"></div> </div> </div> </div> </div> </div> </div>
<script>
const billingWrap = document.querySelector("#billingWrap");
const paymentWrap = document.querySelector("#paymentWrap");

// Show a loader on payment form processing
const setProcessing = (isProcessing) => {
    if (isProcessing) {
        document.querySelector(".overlay").classList.remove("hidden");
    } else {
        document.querySelector(".overlay").classList.add("hidden");
    }
}

document.querySelector("#billingFrm").addEventListener("submit", function(e){
    e.preventDefault();
    setProcessing(true);
    
    let form = document.querySelector('#billingFrm');
    let formData = new FormData(form);
    formData.append("action", 'billing_submit');

    fetch("cartAction.php", {
        method: "POST",
        body: formData,
    })
    .then(response => response.json())
    .then(data => {
        if(data.status == 1){
            billingWrap.classList.add("hidden");
            paymentWrap.classList.remove("hidden");

            document.querySelector('.status-msg-pay').innerHTML = '<div class="alert alert-success">'+data.msg+'</div>';
        }else{
            document.querySelector('.status-msg').innerHTML = '<div class="alert alert-danger">'+data.msg+'</div>';
        }

        setProcessing(false);
        
    })
    .catch(console.error);
});

paypal.Buttons({
    // Sets up the transaction when a payment button is clicked
    createOrder: (data, actions) => {
        return actions.order.create({
            "purchase_units": [{
                //"custom_id": "",
                "description": "<?php echo $paypal_item_desc?>",
                "amount": {
                    "currency_code": "<?php echo CURRENCY?>",
                    "value": <?php echo $paypal_total_amount?>,
                    "breakdown": {
                        "item_total": {  /* Required when including the items array */
                            "currency_code": "<?php echo CURRENCY?>",
                            "value": <?php echo $paypal_total_amount?>
                        }
                    }
                },
                "items": [
                    {
                        "name": "<?php echo $paypal_item_desc?>", /* Shows within upper-right dropdown during payment approval */
                        "description": "<?php echo $paypal_item_desc?>", /* Item details will also be in the completed paypal.com transaction view */
                        "unit_amount": {
                            "currency_code": "<?php echo CURRENCY?>",
                            "value": <?php echo $paypal_total_amount?>
                        },
                        "quantity": "1",
                        "category": "DIGITAL_GOODS"
                    },
                ]
            }]
        });
    },
    // Finalize the transaction after payer approval
    onApprove: (data, actions) => {
        return actions.order.capture().then(function(orderData) {
            setProcessing(true);

            var postData = {paypal_order_check: 1, order_id: orderData.id};
            fetch("paypal_checkout_validate.php", {
                method: 'POST',
                headers: {'Accept': 'application/json'},
                body: encodeFormData(postData)
            })
            .then((response) => response.json())
            .then((result) => {
                if(result.status == 1){
                    window.location.href = "order-status.php?ref_id="+result.ref_id;
                }else{
                    document.querySelector('.status-msg-pay').innerHTML = '<div class="alert alert-danger">'+result.msg+'</div>';
                }
                setProcessing(false);
            })
            .catch(error => console.log(error));
        });
    }
}).render('#paypal-button-container');

const encodeFormData = (data) => {
  var form_data = new FormData();

  for ( var key in data ) {
    form_data.append(key, data[key]);
  }
  return form_data;   
}
</script>

Order Status (order-status.php)

The order details are fetched from the database based on the order ID passed in the URL.

  • The associated transaction details are displayed.
<?php 
// Include the database connection file
require_once 'dbConnect.php';

if(!empty(
$_GET['ref_id'])){
    
$order_id base64_decode($_GET['ref_id']);

    
// Fetch order details from the database
    
$sqlQ "SELECT R.*, T.transaction_id, T.paid_amount, T.paid_amount_currency, T.payment_source, T.payment_status, C.first_name, C.last_name, C.email, C.phone, C.address FROM orders as R LEFT JOIN transactions as T ON T.order_id = R.id LEFT JOIN customers as C ON C.id = R.customer_id WHERE R.id=?";
    
$stmt $db->prepare($sqlQ);
    
$stmt->bind_param("i"$order_id);
    
$stmt->execute();
    
$result $stmt->get_result();

    if(
$result->num_rows 0){
        
$orderData $result->fetch_assoc();
    }
}

if(empty(
$orderData)){
    
header("Location: index.php");
    exit();
}
?> <div class="row g-5"> <div class="col-12"> <?php if(!empty($orderData)){ ?> <div class="col-md-12"> <div class="alert alert-success">Your order has been placed successfully.</div> </div> <!-- Order status & shipping info --> <div class="row col-lg-12 ord-addr-info"> <div class="col-md-4"> <div class="hdr">Order Details</div> <p><b>Reference ID:</b> #<?php echo $orderData['id']; ?></p> <p><b>Total:</b> <?php echo CURRENCY_SYMBOL.$orderData['grand_total'].' '.CURRENCY?></p> <p><b>Placed On:</b> <?php echo $orderData['created']; ?></p> </div> <div class="col-md-4"> <div class="hdr">Payment Information</div> <p><b>Transaction ID:</b> <?php echo $orderData['transaction_id']; ?></p> <p><b>Paid Amount:</b> <?php echo $orderData['paid_amount'].' '.$orderData['paid_amount_currency']; ?></p> <p><b>Payment Source:</b> <?php echo $orderData['payment_source']; ?></p> <p><b>Payment Status:</b> <?php echo $orderData['payment_status']; ?></p> </div> <div class="col-md-4"> <div class="hdr">Buyer Information</div> <p><b>Name:</b> <?php echo $orderData['first_name'].' '.$orderData['last_name']; ?></p> <p><b>Email:</b> <?php echo $orderData['email']; ?></p> <p><b>Phone:</b> <?php echo $orderData['phone']; ?></p> <p><b>Address:</b> <?php echo $orderData['address']; ?></p> </div> </div> <!-- Order items --> <div class="row col-lg-12"> <table class="table table-hover cart"> <thead> <tr> <th width="10%"></th> <th width="45%">Product</th> <th width="15%">Price</th> <th width="10%">QTY</th> <th width="20%">Sub Total</th> </tr> </thead> <tbody>                     <?php
                    
// Get order items from the database
                    
$sqlQ "SELECT i.*, p.name, p.image, p.price FROM order_items as i LEFT JOIN products as p ON p.id = i.product_id WHERE i.order_id=?";
                    
$stmt $db->prepare($sqlQ);
                    
$stmt->bind_param("i"$db_id);
                    
$db_id $order_id;
                    
$stmt->execute();
                    
$result $stmt->get_result();
                    
                    if(
$result->num_rows 0){ 
                        while(
$item $result->fetch_assoc()){
                            
$price $item["price"];
                            
$quantity $item["quantity"];
                            
$sub_total = ($price*$quantity);
                            
$proImg = !empty($item["image"])?'images/products/'.$item["image"]:'images/demo-img.png';
                    
?> <tr> <td><img src="<?php echo $proImg?>" alt="..."></td> <td><?php echo $item["name"]; ?></td> <td><?php echo CURRENCY_SYMBOL.$price.' '.CURRENCY?></td> <td><?php echo $quantity?></td> <td><?php echo CURRENCY_SYMBOL.$sub_total.' '.CURRENCY?></td> </tr>                     <?php
                        
}
                    }
                    
?> </tbody> </table> </div> <div class="col mb-2"> <div class="row"> <div class="col-sm-12 col-md-6"> <a href="index.php" class="btn btn-block btn-primary"><i class="ialeft"></i>Continue Shopping</a> </div> </div> </div> <?php }else{ ?> <div class="col-md-12"> <div class="alert alert-danger">Your order submission failed!</div> </div> <?php ?> </div> </div>

Make PayPal Standard Checkout Payment Gateway Live

Once the integration is completed and the payment process is working properly, follow the below steps to make PayPal checkout live.
1. Go to the PayPal Developer Dashboard Stripe account.

  • Switch to the Live environment using the toggle button at the top-right corner.
  • Navigate to the Apps & Credentials section and collect the REST API credentials (Client ID and Secret) for the Live environment.

2. In the config.php file,

  • Set the PAYPAL_SANDBOX to FALSE.
  • Specify the REST API keys (Client ID and Secret key) in PAYPAL_PROD_CLIENT_ID and PAYPAL_PROD_CLIENT_SECRET variables.
define('PAYPAL_SANDBOX'FALSE); 

define('PAYPAL_PROD_CLIENT_ID''Insert_Live_PayPal_Client_ID_Here');
define('PAYPAL_PROD_CLIENT_SECRET''Insert_Live_PayPal_Secret_Key_Here');

PayPal Advanced Checkout Card Payments Integration in PHP

Conclusion

That’s all! Now you are ready to accept payment on shopping cart checkout. You can use this PHP shopping cart script in your e-commerce website and allow the buyer to make payments online. All the required files are included in the source code package, download it to integrate shopping cart with payment gateway instantly.

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

Leave a reply

keyboard_double_arrow_up