In our previous blogs, we have discussed, how we can use PayPal express checkout for selling a Single Product and Digital Goods.

Now we are going to explain how we can use PayPal express checkout for making shopping cart based website using PHP session and selling multiple products.

Adding cart on the website lets users to buy multiple products using PayPal. Where PHP session based shopping cart collects the product which buyer wants to buy, and they will be able to pay for multiple products using a PayPal account.

Here we demonstrate a furniture selling site with cart option. Where buyer can select quantity for product and add products to cart then checkout for making payments to PayPal.

 


Watch the live demo or download code from the link given below

Paypal express checkout shopping cart in php


Note : PayPal offers sandbox account for development and testing purpose. Here we are using Sandbox for demo. so if you would like to test our demo you can use your PayPal sandbox credentials.

 

Concept behind the script

In our last post we have used Paypal Add to Cart button for creating a online shopping website, this post have the same functionality, but it differs somehow.

The difference is, there we have used Paypal Add to Cart button for making cart, whereas in this post we have achieved the same functionality using Paypal Express Checkout and PHP session, which makes the script an effective one as compare to the last one.


 

Tutorial Scripts in detail

Below are the details of the code used in this tutorial with proper explanation.

index.php

Index.php showing product details. Here the buyer can select the quantity of product and add a product to the cart. After collecting products they will checkout with PayPal by clicking on the place order button.



<?php session_start(); ?>
<html>
<head>
<title>PayPal Express Checkout : Shopping Cart in PHP</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="css/loadding.css">
<link rel="stylesheet" type="text/css" href="css/popup-style.css">
</head>
<body>
<div id="main">
<center><h1>PayPal Express Checkout : Shopping Cart in PHP</h1></center>
<div id="container">
<h2>Modern Furniture Store</h2>
<hr/>

<table id="results" >
<?php
if (isset($_POST['submit']) || !empty($_SESSION['item_list'])) {
?>
<thead>
<tr class="head">
<th>Serial</th>
<th>Name</th>
<th>Price</th>
<th>Qty</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<?php
if (isset($_POST['submit'])) {
$new_ssn_value = "";
if (!empty($_SESSION['item_list'])) {
$all_row = explode("@@##", $_SESSION['item_list']);
$flag = 0;
foreach ($all_row as $value) {
$row = explode("@#@#", $value);
if (!empty($row[0])) {
if ($row[4] == $_POST['P_id']) {
$new_ssn_value .= $_POST['p_name'] . "@#@#" . $_POST['amount'] . "@#@#" . $_POST['qty'] . "@#@#" . $_POST['amount'] * $_POST['qty'] . "@#@#" . $_POST['P_id'] . "@@##";
$flag = 1;
} else {
$new_ssn_value .= $row[0] . "@#@#" . $row[1] . "@#@#" . $row[2] . "@#@#" . $row[3] . "@#@#" . $row[4] . "@@##";
}
}
}
if ($flag == 0) {
$new_ssn_value .= $_POST['p_name'] . "@#@#" . $_POST['amount'] . "@#@#" . $_POST['qty'] . "@#@#" . $_POST['amount'] * $_POST['qty'] . "@#@#" . $_POST['P_id'] . "@@##";
}
session_unset();
$_SESSION['item_list'] = $new_ssn_value;
} else {
$_SESSION['item_list'] = $_POST['p_name'] . "@#@#" . $_POST['amount'] . "@#@#" . $_POST['qty'] . "@#@#" . $_POST['amount'] * $_POST['qty'] . "@#@#" . $_POST['P_id'] . "@@##";
}
}
$all_row = explode("@@##", $_SESSION['item_list']);
$num = 0;
$total = 0;
foreach ($all_row as $value) {
$row = explode("@#@#", $value);
if (!empty($row[0])) {
$total +=$row[3];
?>
<tr>
<td><?php echo ++$num; ?></td>
<td><?php echo $row[0]; ?></td>
<td><?php echo $row[1]; ?></td>
<td><?php echo $row[2]; ?></td>
<td>$<?php echo $row[3]; ?></td>
</tr>
<?php
}
}
?>
<tr>
<td colspan="5"><h3 style="float: left">Total Amout = $<?php echo $total; ?></h3>
<form style="float: right;" action="SetExpressCheckout.php" method="POST">
<input style="margin-top: 0px;" type="submit" name="empty_cart" id="paynow" value="Empty Cart">
<input style="margin-top: 0px; margin-right: 10px;" type="submit" name="palce_order" id="paynow" onclick="popup();"value="Place Order">
</form>
</td>
</tr>
</tbody>
<?php
} else {
?><thead>
<tr class="head">
<th colspan="5" style="text-align: center;">
To add products to your shopping cart click on "Add to Cart" Button
</th>
</tr>
</thead> <?php
}
?>
</table>
<ul class="products-grid row">
<li class="item col-xs-4 last">
<div class="grid_wrapper">
<a href="#" title="Algarva Outdoor Sofa in Chocolate" class="product-image"><img src="images/4.png" alt="Algarva Outdoor Sofa in Chocolate"></a>
<div class="product-shop">
<h3 class="product-name"><a href="#" title="Algarva Outdoor Sofa in Chocolate">Algarva Outdoor Sofa in Chocolate</a></h3>
<div class="desc_grid">
From ancient times people always wanted to find a harmony. Greek philosophers stated that harmony is the basic element of a nature, and everything that surrounds us is in harmony.</div>
<div class="price-box">
<span class="regular-price" id="product-price-53-new">
<span class="price">$12.30</span>
</span>
<form method="POST" action="index.php">
<input type="hidden" value="1" name="P_id">
<input type="hidden" value="12.30" name="amount">
<input type="hidden" name='p_name' value='Algarva Outdoor Sofa in Chocolate'>
<label>Quantity :</label>
<select name='qty'>
<?php for ($i = 1; $i <= 100; $i++) { ?>
<option value='<?php echo $i; ?>'><?php echo $i; ?></option>
<?php } ?>
</select>
<input id="paynow" type="submit" name="submit" value="Add to cart">
</form>
</div>

</div>

</div>
</li>
<li class="item col-xs-4">
<div class="grid_wrapper">
<a href="#" title="Turtle Bach Table Set in Chocolate" class="product-image"><img src="images/2.png" alt="Turtle Bach Table Set in Chocolate"></a>
<div class="product-shop">
<h3 class="product-name"><a href="#" title="Turtle Bach Table Set in Chocolate">Turtle Bach Table Set in Chocolate</a></h3>
<div class="desc_grid">
We are offering you our tremendous choice of different kinds of furniture. It is totally safe for your health. It has passed many various tests without a single failure.</div>
<div class="price-box">
<span class="regular-price" id="product-price-18-new">
<span class="price">$32.50</span>
</span>
<form method="POST" action="index.php">
<input type="hidden" value="2" name="P_id">
<input type="hidden" value="32.50" name="amount">
<input type="hidden" name='p_name' value='Turtle Bach Table Set in Chocolate'>
<label>Quantity :</label>
<select name='qty'>
<?php for ($i = 1; $i <= 100; $i++) { ?>
<option value='<?php echo $i; ?>'><?php echo $i; ?></option>
<?php } ?>
</select>
<input id="paynow" type="submit" name="submit" value="Add to cart">
</form>
</div>

</div>
</div>
</li>
<li class="item col-xs-4 first">
<div class="grid_wrapper">
<a href="#" title="Attractive round chair on low revolving base" class="product-image"><img src="images/8.png" alt="Attractive round chair on low revolving base"></a>
<div class="product-shop">
<h3 class="product-name"><a href="#" title="Attractive round chair on low revolving base">Attractive round chair on low revolving base</a></h3>
<div class="desc_grid">
You know, nowadays we have also faced the problem of choice. All these new technologies that surround us, they became so much more available and many stores use them to represent us numerous goods.</div>
<div class="price-box">
<span class="regular-price" id="product-price-26-new">
<span class="price">$15.30</span>
</span>
<form method="POST" action="index.php">
<input type="hidden" value="3" name="P_id">
<input type="hidden" value="15.30" name="amount">
<input type="hidden" name='p_name' value='Attractive round chair on low revolving base'>
<label>Quantity :</label>
<select name='qty'>
<?php for ($i = 1; $i <= 100; $i++) { ?>
<option value='<?php echo $i; ?>'><?php echo $i; ?></option>
<?php } ?>
</select>
<input id="paynow" type="submit" name="submit" value="Add to cart">
</form>
</div>

</div>
</div>
</li>
</ul>
</div>
<center><img id="paypal_logo" style="margin-top: -30;"src="images/secure-paypal-logo.jpg"></center>
</div>
<div style="clear: both;"></div>
<div id="pop2" class="simplePopup">
<div id="loader">
<div id="circularG">
<div id="circularG_1" class="circularG">
</div>
<div id="circularG_2" class="circularG">
</div>
<div id="circularG_3" class="circularG">
</div>
<div id="circularG_4" class="circularG">
</div>
<div id="circularG_5" class="circularG">
</div>
<div id="circularG_6" class="circularG">
</div>
<div id="circularG_7" class="circularG">
</div>
<div id="circularG_8" class="circularG">
</div>
</div>
</div>
</div>
<script src="js/jquery.min.js"></script>
<script src="js/jquery.simplePopup.js" type="text/javascript"></script>
<script type="text/javascript">
function popup() {
$('#pop2').simplePopup();
}
</script>
</body>
</html>

 

SetExpressCheckout.php

This file contains code to set express checkout and process payment to PayPal.



<?php

session_start();
if (isset($_POST['empty_cart'])) {

session_unset();
session_destroy();
header('Location: index.php');
} else if (isset($_POST['palce_order'])) {

require_once('../PPBootStrap.php');
$url = dirname('http://' . $_SERVER['SERVER_NAME'] . ':' . $_SERVER['SERVER_PORT'] . $_SERVER['REQUEST_URI']);
$returnUrl = "$url/GetExpressCheckout.php";
$cancelUrl = "$url/index.php";

$currencyCode = 'USD';
// total shipping amount
$shippingTotal = new BasicAmountType($currencyCode, 0.50);
//total handling amount if any
$handlingTotal = new BasicAmountType($currencyCode, 0);
//total insurance amount if any
$insuranceTotal = new BasicAmountType($currencyCode, 0);

// shipping address
$address = new AddressType();
$address->CityName = '';
$address->Name = '';
$address->Street1 = '';
$address->StateOrProvince = '';
$address->PostalCode = '';
$address->Country = '';
$address->Phone = '';

// details about payment
$paymentDetails = new PaymentDetailsType();
$itemTotalValue = 0;
$taxTotalValue = 0;

$all_row = explode("@@##", $_SESSION['item_list']);
$num = 0;
$total = 0;
/*
* iterate trhough each item and add to $itemDetails
*/
foreach ($all_row as $value) {
$row = explode("@#@#", $value);
if (!empty($row[0])) {
$total +=$row[3];
$itemAmount = new BasicAmountType($currencyCode, $row[1]);
$itemTotalValue += $row[1] * $row[2];
$taxTotalValue += 1.5 * $row[2];
$itemDetails = new PaymentDetailsItemType();
$itemDetails->Name = $row[0];
$itemDetails->Amount = $itemAmount;
$itemDetails->Quantity = $row[2];
$itemDetails->ItemCategory = 'Physical';
$itemDetails->Tax = new BasicAmountType($currencyCode, 1.5);
$paymentDetails->PaymentDetailsItem[$num++] = $itemDetails;
}
}
/*
* The total cost of the transaction to the buyer. If shipping cost and tax charges are known, include them in this value. If not, this value should be the current subtotal of the order. If the transaction includes one or more one-time purchases, this field must be equal to the sum of the purchases. If the transaction does not include a one-time purchase such as when you set up a billing agreement for a recurring payment, set this field to 0.
*/
$orderTotalValue = $shippingTotal->value + $handlingTotal->value +
$insuranceTotal->value +
$itemTotalValue + $taxTotalValue;

//Payment details
$paymentDetails->ShipToAddress = $address;
$paymentDetails->ItemTotal = new BasicAmountType($currencyCode, $itemTotalValue);
$paymentDetails->TaxTotal = new BasicAmountType($currencyCode, $taxTotalValue);
$paymentDetails->OrderTotal = new BasicAmountType($currencyCode, $orderTotalValue);

/*
* How you want to obtain payment. When implementing parallel payments, this field is required and must be set to Order. When implementing digital goods, this field is required and must be set to Sale. If the transaction does not include a one-time purchase, this field is ignored. It is one of the following values:

Sale - This is a final sale for which you are requesting payment (default).

Authorization - This payment is a basic authorization subject to settlement with PayPal Authorization and Capture.

Order - This payment is an order authorization subject to settlement with PayPal Authorization and Capture.

*/
$paymentDetails->PaymentAction = 'Sale';

$paymentDetails->HandlingTotal = $handlingTotal;
$paymentDetails->InsuranceTotal = $insuranceTotal;
$paymentDetails->ShippingTotal = $shippingTotal;

/*
* Your URL for receiving Instant Payment Notification (IPN) about this transaction. If you do not specify this value in the request, the notification URL from your Merchant Profile is used, if one exists.
*/
if (isset($_REQUEST['notifyURL'])) {
$paymentDetails->NotifyURL = '';
}

$setECReqDetails = new SetExpressCheckoutRequestDetailsType();
$setECReqDetails->PaymentDetails[0] = $paymentDetails;
/*
* (Required) URL to which the buyer is returned if the buyer does not approve the use of PayPal to pay you. For digital goods, you must add JavaScript to this page to close the in-context experience.
*/
$setECReqDetails->CancelURL = $cancelUrl;
/*
* (Required) URL to which the buyer's browser is returned after choosing to pay with PayPal. For digital goods, you must add JavaScript to this page to close the in-context experience.
*/
$setECReqDetails->ReturnURL = $returnUrl;

/*
* Determines where or not PayPal displays shipping address fields on the PayPal pages. For digital goods, this field is required, and you must set it to 1. It is one of the following values:

0 - PayPal displays the shipping address on the PayPal pages.

1 - PayPal does not display shipping address fields whatsoever.

2 - If you do not pass the shipping address, PayPal obtains it from the buyer's account profile.

*/
$setECReqDetails->NoShipping = 0;
/*
* (Optional) Determines whether or not the PayPal pages should display the shipping address set by you in this SetExpressCheckout request, not the shipping address on file with PayPal for this buyer. Displaying the PayPal street address on file does not allow the buyer to edit that address. It is one of the following values:

0 - The PayPal pages should not display the shipping address.

1 - The PayPal pages should display the shipping address.

*/
$setECReqDetails->AddressOverride = '';

/*
* Indicates whether or not you require the buyer's shipping address on file with PayPal be a confirmed address. For digital goods, this field is required, and you must set it to 0. It is one of the following values:

0 - You do not require the buyer's shipping address be a confirmed address.

1 - You require the buyer's shipping address be a confirmed address.

*/
$setECReqDetails->ReqConfirmShipping = 0;

// Billing agreement details
$billingAgreementDetails = new BillingAgreementDetailsType('None');
$billingAgreementDetails->BillingAgreementDescription = '';
$setECReqDetails->BillingAgreementDetails = array($billingAgreementDetails);

// Display options
$setECReqDetails->cppheaderimage = '';
$setECReqDetails->cppheaderbordercolor = '';
$setECReqDetails->cppheaderbackcolor = '';
$setECReqDetails->cpppayflowcolor = '';
$setECReqDetails->cppcartbordercolor = '';
$setECReqDetails->cpplogoimage = '';
$setECReqDetails->PageStyle = '';
$setECReqDetails->BrandName = '';

// Advanced options
$setECReqDetails->AllowNote = 0;

$setECReqType = new SetExpressCheckoutRequestType();
$setECReqType->SetExpressCheckoutRequestDetails = $setECReqDetails;
$setECReq = new SetExpressCheckoutReq();
$setECReq->SetExpressCheckoutRequest = $setECReqType;

/*
* ## Creating service wrapper object
Creating service wrapper object to make API call and loading
Configuration::getAcctAndConfig() returns array that contains credential and config parameters
*/
$paypalService = new PayPalAPIInterfaceServiceService(Configuration::getAcctAndConfig());
try {
/* wrap API method calls on the service object with a try catch */
$setECResponse = $paypalService->SetExpressCheckout($setECReq);
} catch (Exception $ex) {
include_once("../Error.php");
exit;
}
if (isset($setECResponse)) {
/* echo "<table>";
* echo "<tr><td>Ack :</td><td><div id='Ack'>$setECResponse->Ack</div> </td></tr>";
* echo "<tr><td>Token :</td><td><div id='Token'>$setECResponse->Token</div> </td></tr>";
* echo "</table>";
* echo '<pre>';
* print_r($setECResponse);
* echo '</pre>';
*/
if ($setECResponse->Ack == 'Success') {
$token = $setECResponse->Token;
$payPalURL = 'https://www.sandbox.paypal.com/webscr?cmd=_express-checkout&token=' . $token;
header('Location:' . $payPalURL);
}
}
}

GetExpressCheckout.php

GetExpressCheckout will call when  buyer’s browser is returned after choosing to pay with PayPal. and this page shows the transaction status as long as purchased items detail like product name ,Quantity,Product price ,Taxes and Total amount .



<?php
require_once('../PPBootStrap.php');
session_start();

/*
* # GetExpressCheckout API
The GetExpressCheckoutDetails API operation obtains information about
an Express Checkout transaction.

#A timestamped token, the value of which was returned by
`SetExpressCheckout` response.
*/
$token = $_REQUEST['token'];

$getExpressCheckoutDetailsRequest = new GetExpressCheckoutDetailsRequestType($token);

$getExpressCheckoutReq = new GetExpressCheckoutDetailsReq();
$getExpressCheckoutReq->GetExpressCheckoutDetailsRequest = $getExpressCheckoutDetailsRequest;

/*
* ## Creating service wrapper object
Creating service wrapper object to make API call and loading
Configuration::getAcctAndConfig() returns array that contains credential and config parameters
*/
$paypalService = new PayPalAPIInterfaceServiceService(Configuration::getAcctAndConfig());
try {
/* wrap API method calls on the service object with a try catch */
$getECResponse = $paypalService->GetExpressCheckoutDetails($getExpressCheckoutReq);
} catch (Exception $ex) {
include_once("../Error.php");
exit;
}
if (isset($getECResponse)) {
?>
<html>
<head>
<title>PayPal Express Checkout : Shopping Cart in PHP</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<div id="main">
<div class="success_main_heading">
<center><h1>PayPal Express Checkout : Shopping Cart in PHP</h1></center>
</div>
<div id="return">
<h2>Payment Status</h2>
<hr/>
<?php
//Rechecking the product price and currency details
if ($getECResponse->Ack == 'Success') {
echo "<h3 id='success'>Payment Successful</h3>";
session_unset();
session_destroy();
?>
<table id="results" >
<thead>
<tr class="head">
<th>Description</th>
<th>Amount</th>
</tr>

</thead>
<tbody>
<?php for ($i = 0; $i < count($getECResponse->GetExpressCheckoutDetailsResponseDetails->PaymentDetails[0]->PaymentDetailsItem); $i++) { ?>
<tr>
<td>
<b><p style="color: rgb(77, 125, 179);"><?php echo $getECResponse->GetExpressCheckoutDetailsResponseDetails->PaymentDetails[0]->PaymentDetailsItem[$i]->Name; ?></p></b>
<p>Item Price: $<?php echo $getECResponse->GetExpressCheckoutDetailsResponseDetails->PaymentDetails[0]->PaymentDetailsItem[$i]->Amount->value; ?></p>
<p>Quantity: <?php echo $getECResponse->GetExpressCheckoutDetailsResponseDetails->PaymentDetails[0]->PaymentDetailsItem[$i]->Quantity; ?></p>
</td>
<td>
<b><p style="color: rgb(77, 125, 179);">$<?php echo $getECResponse->GetExpressCheckoutDetailsResponseDetails->PaymentDetails[0]->PaymentDetailsItem[$i]->Amount->value * $getECResponse->GetExpressCheckoutDetailsResponseDetails->PaymentDetails[0]->PaymentDetailsItem[$i]->Quantity; ?></p></b>
</td>
</tr>
<?php } ?>
<tr>
<td>
<p style="color: rgb(77, 125, 179);"><b>Item Total</b></p>
<p>Tax</p>
<p>Shipping and handling</p>
</td>
<td><p style="color: rgb(77, 125, 179);"><b>$<?php echo $getECResponse->GetExpressCheckoutDetailsResponseDetails->PaymentDetails[0]->ItemTotal->value; ?></b></p>
<p>$<?php echo $getECResponse->GetExpressCheckoutDetailsResponseDetails->PaymentDetails[0]->TaxTotal->value; ?></p>
<p>$<?php echo $getECResponse->GetExpressCheckoutDetailsResponseDetails->PaymentDetails[0]->ShippingTotal->value; ?></p>
</td>
</tr>
<tr>
<td><b>Total Amount</b></td>
<td><b>$<?php echo $getECResponse->GetExpressCheckoutDetailsResponseDetails->PaymentDetails[0]->OrderTotal->value; ?> USD</b></td>
</tr>
</tbody>
</table>
<div class='back_btn'><a href='index.php' id= 'btn'><< Back to Products </a></div>
<?php
} else {
echo "<h3 id='fail'>Payment - Failed</h3>";
echo '<p><center>Error msg :- This transaction cannot be processed.</center></p>';
echo "<div class='back_btn'><a href='index.php' id= 'btn'><< Back to Products </a></div>";
}
?>
</div>
<!-- Right side div -->
<div class="fr"id="formget">
<a href=https://www.formget.com/app><img style="margin-left: 12%;" src="images/formget.jpg" alt="Online Form Builder"/></a>
</div>
</div>
</body>
</html><?php
}

Conclusion :

After reading the above post, I am sure you will give a try to the script provided and implement it in your own projects as well. Feel free to visit our website again in the future to get in touch with new coding tricks. You can let us know about your feedback in the space provided below :)