06-05-2020, 05:11 PM
One Page Checkout Script Free with Example Template in PHP
<div style="margin: 5px 5% 10px 5%;"><img src="https://www.sickgaming.net/blog/wp-content/uploads/2020/01/one-page-checkout-script-free-with-example-template-in-php.png" width="940" height="788" title="" alt="" /></div><div><p>Last modified on December 13th, 2019 by Vincy.</p>
<p>One page checkout reduces friction in the buying process, increases conversion and improves the sales. Do you know the cart abandonment rate of the customers during their purchase? Unnecessary, lengthy checkout process is one of the main reason which increases this rate.</p>
<p>Just by fine-tuning your checkout process, you can increase the sales by a staggering 23%. This could be a game changer for many eCommerce websites. I have cited the Baymard Institute research statistics below. Just check it out.</p>
<p>The right ecommerce software and a shopping cart script will definitely have an option for one page checkout. By increasing steps in the checkout flow, you do not have anything to gain. Then why not one page checkout? Not only Baymard Institute’s research, check any parties research statistics in this area and everything points towards a seamless checkout process.</p>
<p><img class="alignnone size-full wp-image-10886" src="https://phppot.com/wp-content/uploads/2019/12/one-page-checkout-script-free-with-example-template-in-php.png" alt="One Page Checkout Script Free with Example Template in PHP" width="940" height="788" srcset="https://phppot.com/wp-content/uploads/2019/12/one-page-checkout-script-free-with-example-template-in-php.png 940w, https://phppot.com/wp-content/uploads/20...00x251.png 300w, https://phppot.com/wp-content/uploads/20...68x644.png 768w, https://phppot.com/wp-content/uploads/20...50x461.png 550w" sizes="(max-width: 940px) 100vw, 940px"></p>
<p>Before going to provide one page checkout for your shopping cart application, we have to know what it is and the significance behind its usage. This article will help you to know about it and its advantages.</p>
<p>Also, I have created an example script in PHP for the implementation of this one page checkout. In a previous article, we have seen a <a href="https://phppot.com/php/simple-php-shopping-cart/">simple PHP shopping cart</a> code and this is its enhanced version.</p>
<h2>What is inside?</h2>
<ol>
<li><a href="https://phppot.com/php/one-page-checkout-script-free-with-example-template-in-php/#what-is-one-page-checkout">What is one page checkout?</a></li>
<li><a href="https://phppot.com/php/one-page-checkout-script-free-with-example-template-in-php/#about-this-example">About this example</a></li>
<li><a href="https://phppot.com/php/one-page-checkout-script-free-with-example-template-in-php/#one-page-checkout-example-demo">One page checkout example demo</a></li>
<li><a href="https://phppot.com/php/one-page-checkout-script-free-with-example-template-in-php/#php-checkout-example-files">PHP checkout example files</a></li>
<li><a href="https://phppot.com/php/one-page-checkout-script-free-with-example-template-in-php/#creating-one-page-checkout-template">Creating one page checkout template</a></li>
<li><a href="https://phppot.com/php/one-page-checkout-script-free-with-example-template-in-php/#jquery-script-to-handle-cart-events-and-prepare-ajax-request">jQuery script to handle cart events and prepare AJAX request</a></li>
<li><a href="https://phppot.com/php/one-page-checkout-script-free-with-example-template-in-php/#process-checkout-in-php">Process checkout in PHP</a></li>
<li><a href="https://phppot.com/php/one-page-checkout-script-free-with-example-template-in-php/#enhancements">Enhancements</a></li>
<li><a href="https://phppot.com/php/one-page-checkout-script-free-with-example-template-in-php/#one-page-template-example-template-output">One page template example output</a></li>
</ol>
<h2 id="what-is-one-page-checkout">What is one page checkout?</h2>
<p>One page checkout is a way to make the eCommerce checkout process easier. It reduces the navigation effort, page redirects. It gets the job done by retaining the buyer in a single page.</p>
<p>This makes the checkout experience easier with a single checkout click. We will not compromise any feature to implement one page checkout. It may include add-to-cart control, customer’s cart, payment and shipping and more.</p>
<p><img class="alignnone size-large wp-image-10896" src="https://phppot.com/wp-content/uploads/2019/12/checkout-cart-abandonment-stats-550x390.jpg" alt="Checkout Cart Abandonment Stats" width="550" height="390" srcset="https://phppot.com/wp-content/uploads/2019/12/checkout-cart-abandonment-stats-550x390.jpg 550w, https://phppot.com/wp-content/uploads/20...00x213.jpg 300w, https://phppot.com/wp-content/uploads/20...68x544.jpg 768w" sizes="(max-width: 550px) 100vw, 550px"></p>
<p>Source: <a href="https://baymard.com/lists/cart-abandonment-rate">Baymard Institute</a></p>
<h2 id="about-this-example">About this example</h2>
<p>This example is for creating a <strong>one page checkout in PHP</strong>. On a single page, I have covered the product gallery and the entire cart flow. It is a <strong>lightweight script</strong>.</p>
<p>The gallery will show the product tiles with an add-to-cart option. Then the added cart items will have options to edit and delete.</p>
<p>I used jQuery AJAX for requesting the server-side code to perform the cart actions. We have already seen <a href="https://phppot.com/php/ajax-cart-edit-in-php-shopping-cart/">how to perform cart edit with AJAX</a>.</p>
<p>The cart detail table will also a preview for confirmation before checkout. The checkout will need the mandatory billing details customer name and email.</p>
<p>A simple JavaScript validates the billing and payment form. Once the validation step got passed then it will allow the continuing process to checkout in PHP.</p>
<h2 id="one-page-checkout-example-demo">One page checkout example demo</h2>
<p>I have deployed a demo for this one-page checkout example.</p>
<p>The below button link will redirect you to see this demo. It has the following functionality.</p>
<ul>
<li>Add-to-cart</li>
<li>Edit cart item quantity</li>
<li>Remove a single item</li>
<li>Empty cart</li>
<li>Checkout</li>
</ul>
<p>You can try all the above with this demo.</p>
<p><a class="demo" href="https://phppot.com/demo/one-page-checkout-script-free-with-example-template-in-php/">View Demo</a></p>
<h2 id="php-checkout-example-files">PHP checkout example files</h2>
<p>This is the complete file structure on this PHP one-page checkout example.</p>
<p>The figure shows the PHP endpoints, CSS and JS assets, images, data and vendor directories. It also shows the home and other HTML views and PHP classes.</p>
<p>In the following sections, we will see the file’s code and its purpose.</p>
<p><img class="alignnone size-full wp-image-10861" src="https://phppot.com/wp-content/uploads/2019/12/one-page-checkout-example-files-.jpg" alt="One Page Checkout Example Files" width="400" height="458" srcset="https://phppot.com/wp-content/uploads/2019/12/one-page-checkout-example-files-.jpg 400w, https://phppot.com/wp-content/uploads/20...62x300.jpg 262w" sizes="(max-width: 400px) 100vw, 400px"></p>
<h2 id="creating-one-page-checkout-template">Creating one page checkout template</h2>
<p>The one-page checkout template includes three major parts. Those are the gallery, cart and the billing & payment form.</p>
<p>I have created separate files for these three display components. Then, I included all into a landing page that is index.php.</p>
<p>index.php</p>
<pre class="prettyprint lang-php"><?php session_start(); if (isset($_POST["checkout-btn"])) { $order_number = rand(100, 999); } ?> <HTML> <HEAD> <TITLE>One Page Checkout Script Free Template</TITLE> <link href="./assets/css/phppot-style.css" type="text/css" rel="stylesheet" /> <link href="./assets/css/one-page-checkout.css" type="text/css" rel="stylesheet" /> <script src="./vendor/jquery/jquery.min.js" type="text/javascript"></script> <script src="./vendor/jquery/jquery-ui.js"></script> </HEAD> <BODY> <div class="phppot-container"> <div class="page-heading">One Page Checkout Script Free Template</div> <form name="one-page-checkout-form" id="one-page-checkout-form" action="" method="post" onsubmit="return checkout()"> <?php if(!empty($order_number)){?> <div class="order-message order-success"> You order number is <?php echo $order_number;?>. <span class="btn-message-close" onclick="this.parentElement.style.display='none';" title="Close">×</span> </div> <?php }?> <div class="section product-gallery"> <?php require_once './view/product-gallery.php'; ?> </div> <div class="billing-details"> <?php require_once './view/billing-details.php'; ?> </div> <div class="cart-error-message" id="cart-error-message">Cart must not be emty to checkout</div> <div id="shopping-cart" tabindex="1"> <div id="tbl-cart"> <div id="txt-heading"> <div id="cart-heading">Your Shopping Cart</div> <div id="close"></div> </div> <div id="cart-item"> <?php require_once './view/shopping-cart.php'; ?> </div> </div> </div> <div class="payment-details"> <div class="payment-details-heading">Payment details</div> <div class="row"> <div class="inline-block"> <div> <input class="bank-transfer" type="radio" checked="checked" value="Direct bank transfer" name="direct-bank-transfer">Direct bank transfer </div> <div class="info-label">Specify your order number when you make the bank transfer. Your order will be shippied after the amount is credited to us.</div> </div> </div> </div> <div class="row"> <div id="inline-block"> <input type="submit" class="checkout" name="checkout-btn" id="checkout-btn" value="Checkout"> </div> </div> </form> </div> <script src="./assets/js/cart.js"></script> <script> function checkout() { var valid = true; $("#first-name").removeClass("error-field"); $("#email").removeClass("error-field"); $("#shopping-cart").removeClass("error-field"); $("#cart-error-message").hide(); var firstName = $("#first-name").val(); var cartItem = $("#cart-item-count").val(); var email = $("#email").val(); var emailRegex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; $("#first-name-info").html("").hide(); $("#email-info").html("").hide(); if (firstName.trim() == "") { $("#first-name-info").html("required.").css("color", "#ee0000").show(); $("#first-name").addClass("error-field"); valid = false; } if (email == "") { $("#email-info").html("required").css("color", "#ee0000").show(); $("#email").addClass("error-field"); valid = false; } else if (email.trim() == "") { $("#email-info").html("Invalid email address.").css("color", "#ee0000").show(); $("#email").addClass("error-field"); valid = false; } else if (!emailRegex.test(email)) { $("#email-info").html("Invalid email address.").css("color", "#ee0000") .show(); $("#email").addClass("error-field"); valid = false; } if(cartItem == 0){ $("#cart-error-message").show(); $("#shopping-cart").addClass("error-field"); valid = false; } if (valid == false) { $('.error-field').first().focus(); valid = false; } return valid; } </script> </BODY> </HTML> </pre>
<h3>Product gallery with Add-to-Cart button</h3>
<p>This file will show a catalog to display available products in a gallery. I have shown three products in this example gallery.</p>
<p>These products are static from a PHP array. You can also include your database component to make it dynamic.</p>
<p>Each tile contains an <strong>add-to-cart</strong> button. It calls <em>cartAction() </em>jQuery function on its click event.</p>
<p>product-gallery.php</p>
<pre class="prettyprint lang-php"><div id="product-grid"> <div class="txt-heading">Choose your products</div> <div class="product-item"> <div class="product-image"> <img src="data/camera.jpg" id="<?php echo "3DcAM01";?>" class="product-img"> </div> <div> <strong><?php echo "FinePix Pro2 3D Camera";?></strong> </div> <div class="product-price"><?php echo "1500.00";?></div> <input type="button" id="add_<?php echo "3DcAM01";?>" value="Add to cart" class="btnAddAction" onClick="cartAction('add', '<?php echo "3DcAM01";?>','<?php echo "FinePix Pro2 3D Camera";?>','<?php echo "1500.00";?>')" /> </div> <div class="product-item"> <div class="product-image"> <img src="data/watch.jpg" id="<?php echo "wristWear03";?>" class="product-img"> </div> <div> <strong><?php echo "Luxury Ultra thin Wrist Watch";?></strong> </div> <div class="product-price"><?php echo "300.00";?></div> <input type="button" id="add_<?php echo "wristWear03";?>" value="Add to cart" class="btnAddAction" onClick="cartAction('add', '<?php echo "wristWear03";?>','<?php echo "Luxury Ultra thin Wrist Watch";?>','<?php echo "300.00";?>')" /> </div> <div class="product-item"> <div class="product-image"> <img src="data/laptop.jpg" id="<?php echo "LPN45";?>" class="product-img"> </div> <div> <strong><?php echo "XP 1155 Intel Core Laptop";?></strong> </div> <div class="product-price"><?php echo "800.00";?></div> <input type="button" id="add_<?php echo "LPN45";?>" value="Add to cart" class="btnAddAction" onClick="cartAction('add', '<?php echo "LPN45";?>','<?php echo "XP 1155 Intel Core Laptop";?>','<?php echo "800.00";?>')" /> </div> </div> </pre>
<h3>Shopping cart items with edit delete</h3>
<p>I used the PHP session for managing the cart items. The below code shows an HTML code by embedding the cart details into it from the session array.</p>
<p>The cart must have at least one item to proceed with checkout. So I stored the total cart item count in a hidden field. I update this field after every successful cart action.</p>
<p>When you submit with an empty cart, then this example will prevent checkout. It will display validation error by focusing on the empty cart section.</p>
<p>shopping-cart.php</p>
<pre class="prettyprint lang-php"><?php use Phppot\Cart; require_once __DIR__ . './../Model/Cart.php'; $cartModel = new Cart(); ?> <input type="hidden" id="cart-item-count" value="<?php echo $cartModel->cartSessionItemCount; ?>"> <?php if ($cartModel->cartSessionItemCount > 0) { ?> <table width="100%" id="cart-table" cellpadding="10" cellspacing="1" border="0"> <tbody> <tr> <th>Name</th> <th>Quantity</th> <th class="text-right">Price</th> <th class="text-right">Action</th> </tr> <?php $item_total = 0; $i = 1; foreach ($_SESSION["cart_item"] as $item) { ?> <tr> <td><?php echo $item["name"]; ?></td> <td><input type="number" name="quantity" class="quantity" value="<?php echo $item['quantity']; ?>" data-code='<?php echo $item["code"]; ?>' size=2 onChange="updatePrice(this)" /> <input type="hidden" class='total' name="total" value="<?php echo $item["price"]; ?>" /></td> <td class="prc text-right" id="price" <?php echo $i;?>><?php echo $item["price"]; ?></td> <?php $i++; ?> <td class="text-right"><a onClick="cartAction('remove','<?php echo $item["code"]; ?>')" class="btnRemoveAction"><img src="./view/images/icon-delete.png" alt="Remove Item" /></a></td> </tr> <?php $item_total += ($item["price"] * $item['quantity']); } ?> <tr id="tot"> <td class="text-right" colspan="3"><strong>Total (USD): </strong> <span id="total"><?php echo $item_total;?></span></td> <td class="text-right"><a id="btnEmpty" onClick="cartAction('empty', '');">Empty Cart</a></td> </tr> </tbody> </table> <?php } else { ?> <div id="empty-cart">Your cart is empty</div> <?php } </pre>
<p>This HTML code is for displaying the billing and payment form to the user. The user has to enter the billing details and select the payment method before checkout.</p>
<p>In this example, I have provided only one payment option, Bank Transfer. At the time of processing payment via direct bank transfer, the users refer to the order number.</p>
<p>billing-details.php</p>
<pre class="prettyprint lang-php"><div class="billing-detail-heading">Billing details</div> <div class="row"> <div class="form-label inline-block"> Name <span class="required error"></span> </div> <div class="inline-block"> <div id="first-name-info"></div> <input class="input-box-330" type="text" name="first-name" id="first-name"> </div> </div> <div class="row"> <div class="form-label">Address</div> <div class="inline-block"> <input class="input-box-330" class="input-box-330" type="text" name="address"> </div> </div> <div class="row"> <div class="form-label">City</div> <div class="inline-block"> <input class="input-box-330" type="text" name="city"> </div> </div> <div class="row"> <div class="form-label">State</div> <div class="inline-block"> <input class="input-box-330" type="text" name="state"> </div> </div> <div class="row"> <div class="form-label">Zipcode</div> <div class="inline-block"> <input class="input-box-330" type="text" name="zipcode"> </div> </div> <div class="row"> <div class="form-label"> Email Address<span class="required error"></span> </div> <div class="inline-block"> <div id="email-info"></div> <input class="input-box-330" type="text" name="email" id="email"> </div> </div> </pre>
<h2 id="jquery-script-to-handle-cart-events-and-prepare-ajax-request">jQuery script to handle cart events and prepare AJAX request</h2>
<p>The <em>cartAction()</em> method is for handling the add, edit, remove and empty-cart actions. It has a switch case to perform these actions.</p>
<p>It receives the action parameter and sends the control flow to the appropriate case. It also gets the product title, code and price.</p>
<p>I prepare a query string by using the product details and request PHP via AJAX. After performing the cart action, the PHP code will return the response.</p>
<p>In the success block, we can receive this response for updating the cart.</p>
<p>cart.js</p>
<pre class="prettyprint lang-php">function cartAction(action, product_code, productTitle, productPrice) { var queryString = ""; if (action != "") { switch (action) { case "add": queryString = 'action=' + action + '&code=' + product_code + '&quantity=' + 1 + '&productTitle=' + productTitle + '&productPrice=' + productPrice; break; case "remove": queryString = 'action=' + action + '&code=' + product_code; break; case "empty": queryString = 'action=' + action; break; } } jQuery.ajax({ url : "ajax/handle-cart-ep.php", data : queryString, type : "POST", success : function(data) { $("#cart-item").html(data); $("#count").text($("#cart-item-count").val()); }, error : function() { } }); } function updatePrice(obj) { var quantity = $(obj).val(); var code = $(obj).data('code'); queryString = 'action=edit&code=' + code + '&quantity=' + quantity; $.ajax({ type : 'post', url : "ajax/handle-cart-ep.php", data : queryString, success : function(data) { $("#total").text(data); } }); } </pre>
<h2 id="process-checkout-in-php">Process checkout in PHP</h2>
<p>This is the PHP endpoint called via AJAX. As like as the JavaScript method, this PHP file also contains a switch case to control the cart action.</p>
<p>The Cart.php included in this file is a Model class that executes all the cart operations. </p>
<p>In this endpoint, I instantiate this model and invoke its methods based on the request.</p>
<p>On each cart action, it iterates the latest cart session to prepare the response.</p>
<p>ajax/handle-cart-ep.php</p>
<pre class="prettyprint lang-php"><?php namespace Phppot; use \Phppot\Cart; require_once __DIR__ . './../Model/Cart.php'; $cartModel = new Cart(); session_start(); if (! empty($_POST["action"])) { switch ($_POST["action"]) { case "add": $cartModel->addToCart(); break; case "edit": $totalPrice = $cartModel->editCart(); print $totalPrice; exit; break; case "remove": $cartModel->removeFromCart(); break; case "empty": $cartModel->emptyCart(); break; } } require_once '../view/shopping-cart.php'; </pre>
<p>The below code shows the Cart class. It handles and updates the cart session on each cart action.</p>
<p>The <em>emptyCart() </em>method wipes out the cart by clearing the current session.</p>
<p>Model/Cart.php</p>
<pre class="prettyprint lang-php"><?php namespace Phppot; class Cart { public $cartSessionItemCount = 0; function __construct() { if (! empty($_SESSION["cart_item"]) && is_array($_SESSION["cart_item"])) { $this->cartSessionItemCount = count($_SESSION["cart_item"]); } } function addToCart() { if (isset($_POST)) { $productCode = $_POST["code"]; $productTitle = $_POST["productTitle"]; $poductQuantity = $_POST["quantity"]; $productPrice = $_POST["productPrice"]; } $cartItem = array( 'code' => $productCode, 'name' => $productTitle, 'quantity' => $poductQuantity, 'price' => $productPrice ); $_SESSION["cart_item"][$productCode] = $cartItem; if (! empty($_SESSION["cart_item"]) && is_array($_SESSION["cart_item"])) { $this->cartSessionItemCount = count($_SESSION["cart_item"]); } } function editCart() { if (! empty($_SESSION["cart_item"])) { $total_price = 0; foreach ($_SESSION["cart_item"] as $k => $v) { if ($_POST["code"] == $k) { $_SESSION["cart_item"][$k]["quantity"] = $_POST["quantity"]; } $total_price = $total_price + ($_SESSION["cart_item"][$k]["quantity"] * $_SESSION["cart_item"][$k]["price"]); } return $total_price; } if (! empty($_SESSION["cart_item"]) && is_array($_SESSION["cart_item"])) { $this->cartSessionItemCount = count($_SESSION["cart_item"]); } } function removeFromCart() { if (! empty($_SESSION["cart_item"])) { foreach ($_SESSION["cart_item"] as $k => $v) { if ($_POST["code"] == $k) unset($_SESSION["cart_item"][$k]); if (empty($_SESSION["cart_item"])) unset($_SESSION["cart_item"]); } } if (! empty($_SESSION["cart_item"]) && is_array($_SESSION["cart_item"])) { $this->cartSessionItemCount = count($_SESSION["cart_item"]); } } function emptyCart() { unset($_SESSION["cart_item"]); $this->cartSessionItemCount = 0; } }</pre>
<h2 id="enhancements">Enhancements</h2>
<p>In this example code, there are places to bring the database into the picture. For example, the product gallery and the cart.</p>
<p>I have managed the gallery with a PHP array. And, I handled the cart session with PHP $_SESSION.</p>
<p>If you manage the shopping cart with a database, then it will help you to have a persistent cart. I have already given an example of <a href="https://phppot.com/php/how-to-build-a-persistent-shopping-cart-in-php/">building a persistent shopping cart in PHP</a>.</p>
<p>You can plugin your database module into this example code to store products. If you want to show your <a href="https://phppot.com/php/responsive-product-gallery-for-shopping-cart/">shopping cart products gallery from a database</a>, this link has an example.</p>
<h2 id="one-page-template-example-template-output">One page template example output</h2>
<p>See the screenshot shows the product gallery, cart and checkout on one page. The gallery shows three product tiles.</p>
<p>By clicking the <em>Add to cart </em>button, the cart will have a new entry as shown below.</p>
<p>The Checkout button click will place the order for the added cart items.</p>
<p><img class="alignnone size-full wp-image-10867" src="https://phppot.com/wp-content/uploads/2019/12/one-page-checkout-example-output.jpg" alt="One Page Checkout Example Output" width="649" height="957" srcset="https://phppot.com/wp-content/uploads/2019/12/one-page-checkout-example-output.jpg 649w, https://phppot.com/wp-content/uploads/20...03x300.jpg 203w, https://phppot.com/wp-content/uploads/20...50x811.jpg 550w" sizes="(max-width: 649px) 100vw, 649px"></p>
<p><a class="demo" href="https://phppot.com/demo/one-page-checkout-script-free-with-example-template-in-php">View Demo</a><a class="download" href="https://phppot.com/downloads/one-page-checkout-script-free-with-example-template-in-php.zip">Download</a></p>
<p> <!-- #comments --> </p>
<div class="related-articles">
<h2>Popular Articles</h2>
</p></div>
<p> <a href="https://phppot.com/php/one-page-checkout-script-free-with-example-template-in-php/#top" class="top">↑ Back to Top</a> </p>
</div>
https://www.sickgaming.net/blog/2019/12/...te-in-php/
<div style="margin: 5px 5% 10px 5%;"><img src="https://www.sickgaming.net/blog/wp-content/uploads/2020/01/one-page-checkout-script-free-with-example-template-in-php.png" width="940" height="788" title="" alt="" /></div><div><p>Last modified on December 13th, 2019 by Vincy.</p>
<p>One page checkout reduces friction in the buying process, increases conversion and improves the sales. Do you know the cart abandonment rate of the customers during their purchase? Unnecessary, lengthy checkout process is one of the main reason which increases this rate.</p>
<p>Just by fine-tuning your checkout process, you can increase the sales by a staggering 23%. This could be a game changer for many eCommerce websites. I have cited the Baymard Institute research statistics below. Just check it out.</p>
<p>The right ecommerce software and a shopping cart script will definitely have an option for one page checkout. By increasing steps in the checkout flow, you do not have anything to gain. Then why not one page checkout? Not only Baymard Institute’s research, check any parties research statistics in this area and everything points towards a seamless checkout process.</p>
<p><img class="alignnone size-full wp-image-10886" src="https://phppot.com/wp-content/uploads/2019/12/one-page-checkout-script-free-with-example-template-in-php.png" alt="One Page Checkout Script Free with Example Template in PHP" width="940" height="788" srcset="https://phppot.com/wp-content/uploads/2019/12/one-page-checkout-script-free-with-example-template-in-php.png 940w, https://phppot.com/wp-content/uploads/20...00x251.png 300w, https://phppot.com/wp-content/uploads/20...68x644.png 768w, https://phppot.com/wp-content/uploads/20...50x461.png 550w" sizes="(max-width: 940px) 100vw, 940px"></p>
<p>Before going to provide one page checkout for your shopping cart application, we have to know what it is and the significance behind its usage. This article will help you to know about it and its advantages.</p>
<p>Also, I have created an example script in PHP for the implementation of this one page checkout. In a previous article, we have seen a <a href="https://phppot.com/php/simple-php-shopping-cart/">simple PHP shopping cart</a> code and this is its enhanced version.</p>
<h2>What is inside?</h2>
<ol>
<li><a href="https://phppot.com/php/one-page-checkout-script-free-with-example-template-in-php/#what-is-one-page-checkout">What is one page checkout?</a></li>
<li><a href="https://phppot.com/php/one-page-checkout-script-free-with-example-template-in-php/#about-this-example">About this example</a></li>
<li><a href="https://phppot.com/php/one-page-checkout-script-free-with-example-template-in-php/#one-page-checkout-example-demo">One page checkout example demo</a></li>
<li><a href="https://phppot.com/php/one-page-checkout-script-free-with-example-template-in-php/#php-checkout-example-files">PHP checkout example files</a></li>
<li><a href="https://phppot.com/php/one-page-checkout-script-free-with-example-template-in-php/#creating-one-page-checkout-template">Creating one page checkout template</a></li>
<li><a href="https://phppot.com/php/one-page-checkout-script-free-with-example-template-in-php/#jquery-script-to-handle-cart-events-and-prepare-ajax-request">jQuery script to handle cart events and prepare AJAX request</a></li>
<li><a href="https://phppot.com/php/one-page-checkout-script-free-with-example-template-in-php/#process-checkout-in-php">Process checkout in PHP</a></li>
<li><a href="https://phppot.com/php/one-page-checkout-script-free-with-example-template-in-php/#enhancements">Enhancements</a></li>
<li><a href="https://phppot.com/php/one-page-checkout-script-free-with-example-template-in-php/#one-page-template-example-template-output">One page template example output</a></li>
</ol>
<h2 id="what-is-one-page-checkout">What is one page checkout?</h2>
<p>One page checkout is a way to make the eCommerce checkout process easier. It reduces the navigation effort, page redirects. It gets the job done by retaining the buyer in a single page.</p>
<p>This makes the checkout experience easier with a single checkout click. We will not compromise any feature to implement one page checkout. It may include add-to-cart control, customer’s cart, payment and shipping and more.</p>
<p><img class="alignnone size-large wp-image-10896" src="https://phppot.com/wp-content/uploads/2019/12/checkout-cart-abandonment-stats-550x390.jpg" alt="Checkout Cart Abandonment Stats" width="550" height="390" srcset="https://phppot.com/wp-content/uploads/2019/12/checkout-cart-abandonment-stats-550x390.jpg 550w, https://phppot.com/wp-content/uploads/20...00x213.jpg 300w, https://phppot.com/wp-content/uploads/20...68x544.jpg 768w" sizes="(max-width: 550px) 100vw, 550px"></p>
<p>Source: <a href="https://baymard.com/lists/cart-abandonment-rate">Baymard Institute</a></p>
<h2 id="about-this-example">About this example</h2>
<p>This example is for creating a <strong>one page checkout in PHP</strong>. On a single page, I have covered the product gallery and the entire cart flow. It is a <strong>lightweight script</strong>.</p>
<p>The gallery will show the product tiles with an add-to-cart option. Then the added cart items will have options to edit and delete.</p>
<p>I used jQuery AJAX for requesting the server-side code to perform the cart actions. We have already seen <a href="https://phppot.com/php/ajax-cart-edit-in-php-shopping-cart/">how to perform cart edit with AJAX</a>.</p>
<p>The cart detail table will also a preview for confirmation before checkout. The checkout will need the mandatory billing details customer name and email.</p>
<p>A simple JavaScript validates the billing and payment form. Once the validation step got passed then it will allow the continuing process to checkout in PHP.</p>
<h2 id="one-page-checkout-example-demo">One page checkout example demo</h2>
<p>I have deployed a demo for this one-page checkout example.</p>
<p>The below button link will redirect you to see this demo. It has the following functionality.</p>
<ul>
<li>Add-to-cart</li>
<li>Edit cart item quantity</li>
<li>Remove a single item</li>
<li>Empty cart</li>
<li>Checkout</li>
</ul>
<p>You can try all the above with this demo.</p>
<p><a class="demo" href="https://phppot.com/demo/one-page-checkout-script-free-with-example-template-in-php/">View Demo</a></p>
<h2 id="php-checkout-example-files">PHP checkout example files</h2>
<p>This is the complete file structure on this PHP one-page checkout example.</p>
<p>The figure shows the PHP endpoints, CSS and JS assets, images, data and vendor directories. It also shows the home and other HTML views and PHP classes.</p>
<p>In the following sections, we will see the file’s code and its purpose.</p>
<p><img class="alignnone size-full wp-image-10861" src="https://phppot.com/wp-content/uploads/2019/12/one-page-checkout-example-files-.jpg" alt="One Page Checkout Example Files" width="400" height="458" srcset="https://phppot.com/wp-content/uploads/2019/12/one-page-checkout-example-files-.jpg 400w, https://phppot.com/wp-content/uploads/20...62x300.jpg 262w" sizes="(max-width: 400px) 100vw, 400px"></p>
<h2 id="creating-one-page-checkout-template">Creating one page checkout template</h2>
<p>The one-page checkout template includes three major parts. Those are the gallery, cart and the billing & payment form.</p>
<p>I have created separate files for these three display components. Then, I included all into a landing page that is index.php.</p>
<p>index.php</p>
<pre class="prettyprint lang-php"><?php session_start(); if (isset($_POST["checkout-btn"])) { $order_number = rand(100, 999); } ?> <HTML> <HEAD> <TITLE>One Page Checkout Script Free Template</TITLE> <link href="./assets/css/phppot-style.css" type="text/css" rel="stylesheet" /> <link href="./assets/css/one-page-checkout.css" type="text/css" rel="stylesheet" /> <script src="./vendor/jquery/jquery.min.js" type="text/javascript"></script> <script src="./vendor/jquery/jquery-ui.js"></script> </HEAD> <BODY> <div class="phppot-container"> <div class="page-heading">One Page Checkout Script Free Template</div> <form name="one-page-checkout-form" id="one-page-checkout-form" action="" method="post" onsubmit="return checkout()"> <?php if(!empty($order_number)){?> <div class="order-message order-success"> You order number is <?php echo $order_number;?>. <span class="btn-message-close" onclick="this.parentElement.style.display='none';" title="Close">×</span> </div> <?php }?> <div class="section product-gallery"> <?php require_once './view/product-gallery.php'; ?> </div> <div class="billing-details"> <?php require_once './view/billing-details.php'; ?> </div> <div class="cart-error-message" id="cart-error-message">Cart must not be emty to checkout</div> <div id="shopping-cart" tabindex="1"> <div id="tbl-cart"> <div id="txt-heading"> <div id="cart-heading">Your Shopping Cart</div> <div id="close"></div> </div> <div id="cart-item"> <?php require_once './view/shopping-cart.php'; ?> </div> </div> </div> <div class="payment-details"> <div class="payment-details-heading">Payment details</div> <div class="row"> <div class="inline-block"> <div> <input class="bank-transfer" type="radio" checked="checked" value="Direct bank transfer" name="direct-bank-transfer">Direct bank transfer </div> <div class="info-label">Specify your order number when you make the bank transfer. Your order will be shippied after the amount is credited to us.</div> </div> </div> </div> <div class="row"> <div id="inline-block"> <input type="submit" class="checkout" name="checkout-btn" id="checkout-btn" value="Checkout"> </div> </div> </form> </div> <script src="./assets/js/cart.js"></script> <script> function checkout() { var valid = true; $("#first-name").removeClass("error-field"); $("#email").removeClass("error-field"); $("#shopping-cart").removeClass("error-field"); $("#cart-error-message").hide(); var firstName = $("#first-name").val(); var cartItem = $("#cart-item-count").val(); var email = $("#email").val(); var emailRegex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; $("#first-name-info").html("").hide(); $("#email-info").html("").hide(); if (firstName.trim() == "") { $("#first-name-info").html("required.").css("color", "#ee0000").show(); $("#first-name").addClass("error-field"); valid = false; } if (email == "") { $("#email-info").html("required").css("color", "#ee0000").show(); $("#email").addClass("error-field"); valid = false; } else if (email.trim() == "") { $("#email-info").html("Invalid email address.").css("color", "#ee0000").show(); $("#email").addClass("error-field"); valid = false; } else if (!emailRegex.test(email)) { $("#email-info").html("Invalid email address.").css("color", "#ee0000") .show(); $("#email").addClass("error-field"); valid = false; } if(cartItem == 0){ $("#cart-error-message").show(); $("#shopping-cart").addClass("error-field"); valid = false; } if (valid == false) { $('.error-field').first().focus(); valid = false; } return valid; } </script> </BODY> </HTML> </pre>
<h3>Product gallery with Add-to-Cart button</h3>
<p>This file will show a catalog to display available products in a gallery. I have shown three products in this example gallery.</p>
<p>These products are static from a PHP array. You can also include your database component to make it dynamic.</p>
<p>Each tile contains an <strong>add-to-cart</strong> button. It calls <em>cartAction() </em>jQuery function on its click event.</p>
<p>product-gallery.php</p>
<pre class="prettyprint lang-php"><div id="product-grid"> <div class="txt-heading">Choose your products</div> <div class="product-item"> <div class="product-image"> <img src="data/camera.jpg" id="<?php echo "3DcAM01";?>" class="product-img"> </div> <div> <strong><?php echo "FinePix Pro2 3D Camera";?></strong> </div> <div class="product-price"><?php echo "1500.00";?></div> <input type="button" id="add_<?php echo "3DcAM01";?>" value="Add to cart" class="btnAddAction" onClick="cartAction('add', '<?php echo "3DcAM01";?>','<?php echo "FinePix Pro2 3D Camera";?>','<?php echo "1500.00";?>')" /> </div> <div class="product-item"> <div class="product-image"> <img src="data/watch.jpg" id="<?php echo "wristWear03";?>" class="product-img"> </div> <div> <strong><?php echo "Luxury Ultra thin Wrist Watch";?></strong> </div> <div class="product-price"><?php echo "300.00";?></div> <input type="button" id="add_<?php echo "wristWear03";?>" value="Add to cart" class="btnAddAction" onClick="cartAction('add', '<?php echo "wristWear03";?>','<?php echo "Luxury Ultra thin Wrist Watch";?>','<?php echo "300.00";?>')" /> </div> <div class="product-item"> <div class="product-image"> <img src="data/laptop.jpg" id="<?php echo "LPN45";?>" class="product-img"> </div> <div> <strong><?php echo "XP 1155 Intel Core Laptop";?></strong> </div> <div class="product-price"><?php echo "800.00";?></div> <input type="button" id="add_<?php echo "LPN45";?>" value="Add to cart" class="btnAddAction" onClick="cartAction('add', '<?php echo "LPN45";?>','<?php echo "XP 1155 Intel Core Laptop";?>','<?php echo "800.00";?>')" /> </div> </div> </pre>
<h3>Shopping cart items with edit delete</h3>
<p>I used the PHP session for managing the cart items. The below code shows an HTML code by embedding the cart details into it from the session array.</p>
<p>The cart must have at least one item to proceed with checkout. So I stored the total cart item count in a hidden field. I update this field after every successful cart action.</p>
<p>When you submit with an empty cart, then this example will prevent checkout. It will display validation error by focusing on the empty cart section.</p>
<p>shopping-cart.php</p>
<pre class="prettyprint lang-php"><?php use Phppot\Cart; require_once __DIR__ . './../Model/Cart.php'; $cartModel = new Cart(); ?> <input type="hidden" id="cart-item-count" value="<?php echo $cartModel->cartSessionItemCount; ?>"> <?php if ($cartModel->cartSessionItemCount > 0) { ?> <table width="100%" id="cart-table" cellpadding="10" cellspacing="1" border="0"> <tbody> <tr> <th>Name</th> <th>Quantity</th> <th class="text-right">Price</th> <th class="text-right">Action</th> </tr> <?php $item_total = 0; $i = 1; foreach ($_SESSION["cart_item"] as $item) { ?> <tr> <td><?php echo $item["name"]; ?></td> <td><input type="number" name="quantity" class="quantity" value="<?php echo $item['quantity']; ?>" data-code='<?php echo $item["code"]; ?>' size=2 onChange="updatePrice(this)" /> <input type="hidden" class='total' name="total" value="<?php echo $item["price"]; ?>" /></td> <td class="prc text-right" id="price" <?php echo $i;?>><?php echo $item["price"]; ?></td> <?php $i++; ?> <td class="text-right"><a onClick="cartAction('remove','<?php echo $item["code"]; ?>')" class="btnRemoveAction"><img src="./view/images/icon-delete.png" alt="Remove Item" /></a></td> </tr> <?php $item_total += ($item["price"] * $item['quantity']); } ?> <tr id="tot"> <td class="text-right" colspan="3"><strong>Total (USD): </strong> <span id="total"><?php echo $item_total;?></span></td> <td class="text-right"><a id="btnEmpty" onClick="cartAction('empty', '');">Empty Cart</a></td> </tr> </tbody> </table> <?php } else { ?> <div id="empty-cart">Your cart is empty</div> <?php } </pre>
<p>This HTML code is for displaying the billing and payment form to the user. The user has to enter the billing details and select the payment method before checkout.</p>
<p>In this example, I have provided only one payment option, Bank Transfer. At the time of processing payment via direct bank transfer, the users refer to the order number.</p>
<p>billing-details.php</p>
<pre class="prettyprint lang-php"><div class="billing-detail-heading">Billing details</div> <div class="row"> <div class="form-label inline-block"> Name <span class="required error"></span> </div> <div class="inline-block"> <div id="first-name-info"></div> <input class="input-box-330" type="text" name="first-name" id="first-name"> </div> </div> <div class="row"> <div class="form-label">Address</div> <div class="inline-block"> <input class="input-box-330" class="input-box-330" type="text" name="address"> </div> </div> <div class="row"> <div class="form-label">City</div> <div class="inline-block"> <input class="input-box-330" type="text" name="city"> </div> </div> <div class="row"> <div class="form-label">State</div> <div class="inline-block"> <input class="input-box-330" type="text" name="state"> </div> </div> <div class="row"> <div class="form-label">Zipcode</div> <div class="inline-block"> <input class="input-box-330" type="text" name="zipcode"> </div> </div> <div class="row"> <div class="form-label"> Email Address<span class="required error"></span> </div> <div class="inline-block"> <div id="email-info"></div> <input class="input-box-330" type="text" name="email" id="email"> </div> </div> </pre>
<h2 id="jquery-script-to-handle-cart-events-and-prepare-ajax-request">jQuery script to handle cart events and prepare AJAX request</h2>
<p>The <em>cartAction()</em> method is for handling the add, edit, remove and empty-cart actions. It has a switch case to perform these actions.</p>
<p>It receives the action parameter and sends the control flow to the appropriate case. It also gets the product title, code and price.</p>
<p>I prepare a query string by using the product details and request PHP via AJAX. After performing the cart action, the PHP code will return the response.</p>
<p>In the success block, we can receive this response for updating the cart.</p>
<p>cart.js</p>
<pre class="prettyprint lang-php">function cartAction(action, product_code, productTitle, productPrice) { var queryString = ""; if (action != "") { switch (action) { case "add": queryString = 'action=' + action + '&code=' + product_code + '&quantity=' + 1 + '&productTitle=' + productTitle + '&productPrice=' + productPrice; break; case "remove": queryString = 'action=' + action + '&code=' + product_code; break; case "empty": queryString = 'action=' + action; break; } } jQuery.ajax({ url : "ajax/handle-cart-ep.php", data : queryString, type : "POST", success : function(data) { $("#cart-item").html(data); $("#count").text($("#cart-item-count").val()); }, error : function() { } }); } function updatePrice(obj) { var quantity = $(obj).val(); var code = $(obj).data('code'); queryString = 'action=edit&code=' + code + '&quantity=' + quantity; $.ajax({ type : 'post', url : "ajax/handle-cart-ep.php", data : queryString, success : function(data) { $("#total").text(data); } }); } </pre>
<h2 id="process-checkout-in-php">Process checkout in PHP</h2>
<p>This is the PHP endpoint called via AJAX. As like as the JavaScript method, this PHP file also contains a switch case to control the cart action.</p>
<p>The Cart.php included in this file is a Model class that executes all the cart operations. </p>
<p>In this endpoint, I instantiate this model and invoke its methods based on the request.</p>
<p>On each cart action, it iterates the latest cart session to prepare the response.</p>
<p>ajax/handle-cart-ep.php</p>
<pre class="prettyprint lang-php"><?php namespace Phppot; use \Phppot\Cart; require_once __DIR__ . './../Model/Cart.php'; $cartModel = new Cart(); session_start(); if (! empty($_POST["action"])) { switch ($_POST["action"]) { case "add": $cartModel->addToCart(); break; case "edit": $totalPrice = $cartModel->editCart(); print $totalPrice; exit; break; case "remove": $cartModel->removeFromCart(); break; case "empty": $cartModel->emptyCart(); break; } } require_once '../view/shopping-cart.php'; </pre>
<p>The below code shows the Cart class. It handles and updates the cart session on each cart action.</p>
<p>The <em>emptyCart() </em>method wipes out the cart by clearing the current session.</p>
<p>Model/Cart.php</p>
<pre class="prettyprint lang-php"><?php namespace Phppot; class Cart { public $cartSessionItemCount = 0; function __construct() { if (! empty($_SESSION["cart_item"]) && is_array($_SESSION["cart_item"])) { $this->cartSessionItemCount = count($_SESSION["cart_item"]); } } function addToCart() { if (isset($_POST)) { $productCode = $_POST["code"]; $productTitle = $_POST["productTitle"]; $poductQuantity = $_POST["quantity"]; $productPrice = $_POST["productPrice"]; } $cartItem = array( 'code' => $productCode, 'name' => $productTitle, 'quantity' => $poductQuantity, 'price' => $productPrice ); $_SESSION["cart_item"][$productCode] = $cartItem; if (! empty($_SESSION["cart_item"]) && is_array($_SESSION["cart_item"])) { $this->cartSessionItemCount = count($_SESSION["cart_item"]); } } function editCart() { if (! empty($_SESSION["cart_item"])) { $total_price = 0; foreach ($_SESSION["cart_item"] as $k => $v) { if ($_POST["code"] == $k) { $_SESSION["cart_item"][$k]["quantity"] = $_POST["quantity"]; } $total_price = $total_price + ($_SESSION["cart_item"][$k]["quantity"] * $_SESSION["cart_item"][$k]["price"]); } return $total_price; } if (! empty($_SESSION["cart_item"]) && is_array($_SESSION["cart_item"])) { $this->cartSessionItemCount = count($_SESSION["cart_item"]); } } function removeFromCart() { if (! empty($_SESSION["cart_item"])) { foreach ($_SESSION["cart_item"] as $k => $v) { if ($_POST["code"] == $k) unset($_SESSION["cart_item"][$k]); if (empty($_SESSION["cart_item"])) unset($_SESSION["cart_item"]); } } if (! empty($_SESSION["cart_item"]) && is_array($_SESSION["cart_item"])) { $this->cartSessionItemCount = count($_SESSION["cart_item"]); } } function emptyCart() { unset($_SESSION["cart_item"]); $this->cartSessionItemCount = 0; } }</pre>
<h2 id="enhancements">Enhancements</h2>
<p>In this example code, there are places to bring the database into the picture. For example, the product gallery and the cart.</p>
<p>I have managed the gallery with a PHP array. And, I handled the cart session with PHP $_SESSION.</p>
<p>If you manage the shopping cart with a database, then it will help you to have a persistent cart. I have already given an example of <a href="https://phppot.com/php/how-to-build-a-persistent-shopping-cart-in-php/">building a persistent shopping cart in PHP</a>.</p>
<p>You can plugin your database module into this example code to store products. If you want to show your <a href="https://phppot.com/php/responsive-product-gallery-for-shopping-cart/">shopping cart products gallery from a database</a>, this link has an example.</p>
<h2 id="one-page-template-example-template-output">One page template example output</h2>
<p>See the screenshot shows the product gallery, cart and checkout on one page. The gallery shows three product tiles.</p>
<p>By clicking the <em>Add to cart </em>button, the cart will have a new entry as shown below.</p>
<p>The Checkout button click will place the order for the added cart items.</p>
<p><img class="alignnone size-full wp-image-10867" src="https://phppot.com/wp-content/uploads/2019/12/one-page-checkout-example-output.jpg" alt="One Page Checkout Example Output" width="649" height="957" srcset="https://phppot.com/wp-content/uploads/2019/12/one-page-checkout-example-output.jpg 649w, https://phppot.com/wp-content/uploads/20...03x300.jpg 203w, https://phppot.com/wp-content/uploads/20...50x811.jpg 550w" sizes="(max-width: 649px) 100vw, 649px"></p>
<p><a class="demo" href="https://phppot.com/demo/one-page-checkout-script-free-with-example-template-in-php">View Demo</a><a class="download" href="https://phppot.com/downloads/one-page-checkout-script-free-with-example-template-in-php.zip">Download</a></p>
<p> <!-- #comments --> </p>
<div class="related-articles">
<h2>Popular Articles</h2>
</p></div>
<p> <a href="https://phppot.com/php/one-page-checkout-script-free-with-example-template-in-php/#top" class="top">↑ Back to Top</a> </p>
</div>
https://www.sickgaming.net/blog/2019/12/...te-in-php/