Multiple Items PHP Shopping Cart to PayPal

In the previous post, we had created a simple PHP session based shopping cart, now in this article we will integrating this shopping cart with our PayPal express checkout system. Main idea is to let users buy multiple items using PayPal, shopping cart collects the items users want to buy and then they’ll be able to pay for multiple items using their PayPal account.

Before we start, I suggest you go through both articles Creating Shopping cart and PayPal express checkout, to understand how they work.

Shopping Cart to PayPal

View Cart Page

In viewcart.php I have added a “Pay with PayPal” button, once clicked it will redirect user to PayPal express checkout page. The express checkout page uses existing session variable from the shopping cart to determine the costs, taxes and additional fees. Then user will be redirected to PayPal’s item summery view, where user can pay using their PayPal account.

HTML
12

<a href="paypal-express-checkout" ><img src="images/btn_pay_with_paypal.png" width="179" height="36"></a>

Paypal Express Checkout

I’ve copied the Paypal Express Checkout folder into shopping cart and modified it to use shopping cart session variables, we just calculate the quantity and total amount and send it to PayPal. Have a look at the code below.

PHP
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768

if(isset($_SESSION["cart_products"])) //Post Data received from product list page.
{
	//Other important variables like tax, shipping cost
	//we need 4 variables from product page Item Name, Item Price, Item Number and Item Quantity.
	//Please Note : People can manipulate hidden field amounts in form,
	//In practical world you must fetch actual price from database using item id.
	//eg : $ItemPrice = $mysqli->query("SELECT item_price FROM products WHERE id = Product_Number");
	$paypal_data ='';
	$ItemTotalPrice = 0;
	$i = 0;
		foreach ($_SESSION["cart_products"] as $cart_itm)
        {
        $product_code 	= filter_var($cart_itm["product_code"], FILTER_SANITIZE_STRING); 
		$results = $mysqli->query("SELECT product_name, product_desc, price FROM products WHERE product_code='$product_code' LIMIT 1");
		$obj = $results->fetch_object();
        $paypal_data .= '&L_PAYMENTREQUEST_0_NAME'.$i.'='.urlencode($obj->product_name);
        $paypal_data .= '&L_PAYMENTREQUEST_0_NUMBER'.$i.'='.urlencode($cart_itm["product_code"]);
        $paypal_data .= '&L_PAYMENTREQUEST_0_AMT'.$i.'='.urlencode($obj->price);
		$paypal_data .= '&L_PAYMENTREQUEST_0_QTY'.$i.'='. urlencode($cart_itm["product_qty"]);
		// item price X quantity
        $subtotal = ($obj->price*$cart_itm["product_qty"]);
        //total price
        $ItemTotalPrice = $ItemTotalPrice + $subtotal;
		//create items for session
		$paypal_product['items'][] = array('itm_name'=>$obj->product_name,
											'itm_price'=>$obj->price,
											'itm_code'=>$cart_itm["product_code"],
											'itm_qty'=>$cart_itm["product_qty"]
											);
		$i++;
    }
	$total_tax = 0;
	foreach($taxes as $key => $value){ //list and calculate all taxes in array
			$tax_amount     = round($ItemTotalPrice * ($value / 100));
			$tax_item[$key] = $tax_amount;
			$total_tax = $total_tax + $tax_amount; //total tax amount
	}
	//Grand total including all tax, insurance, shipping cost and discount
	$GrandTotal = ($ItemTotalPrice + $total_tax + $HandalingCost + $InsuranceCost + $shipping_cost + $ShippinDiscount);
	$paypal_product['assets'] = array('tax_total'=>$total_tax,
								'handaling_cost'=>$HandalingCost,
								'insurance_cost'=>$InsuranceCost,
								'shippin_discount'=>$ShippinDiscount,
								'shippin_cost'=>$shipping_cost,
								'grand_total'=>$GrandTotal);
	//create session array for later use
	$_SESSION["paypal_products"] = $paypal_product;
	//Parameters for SetExpressCheckout, which will be sent to PayPal
	$padata = 	'&METHOD=SetExpressCheckout'.
				'&RETURNURL='.urlencode($PayPalReturnURL ).
				'&CANCELURL='.urlencode($PayPalCancelURL).
				'&PAYMENTREQUEST_0_PAYMENTACTION='.urlencode("SALE").
				$paypal_data.
				'&NOSHIPPING=0'. //set 1 to hide buyer's shipping address, in-case products that does not require shipping
				'&PAYMENTREQUEST_0_ITEMAMT='.urlencode($ItemTotalPrice).
				'&PAYMENTREQUEST_0_TAXAMT='.urlencode($total_tax).
				'&PAYMENTREQUEST_0_SHIPPINGAMT='.urlencode($shipping_cost).
				'&PAYMENTREQUEST_0_HANDLINGAMT='.urlencode($HandalingCost).
				'&PAYMENTREQUEST_0_SHIPDISCAMT='.urlencode($ShippinDiscount).
				'&PAYMENTREQUEST_0_INSURANCEAMT='.urlencode($InsuranceCost).
				'&PAYMENTREQUEST_0_AMT='.urlencode($GrandTotal).
				'&PAYMENTREQUEST_0_CURRENCYCODE='.urlencode($PayPalCurrencyCode).
				'&LOCALECODE=GB'. //PayPal pages to match the language on your website.
				'&LOGOIMG=https://www.sanwebe.com/wp-content/themes/sanwebe/img/logo.png'. //site logo
				'&CARTBORDERCOLOR=FFFFFF'. //border color of cart
				'&ALLOWNOTE=1';

That’s it, this is the main modification here, rest is explained in my previous post PayPal express checkout. Without making things further complicated, I want you to download and test the script yourself, but nothing is perfect, so if you want to leave some feedback or improvement suggestions please do so by commenting below. Good luck!

Download Demo
  • 166 Comments

    Add Comment
    • Rsf
      paypal truly f(*&*ng SUCKS
    • Raghuraj
      plz help me for resolve this SetExpressCheckout failed: error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure(35)
    • Raghuraj
      Plz check and help me to fix this Error : Security header is not valid Array ( [TIMESTAMP] => 20171129T160520Z [CORRELATIONID] => 5c48f5dcb679f [ACK] => Failure [VERSION] => 1090 [BUILD] => 40680762 [L_ERRORCODE0] => 10002 [L_SHORTMESSAGE0] => Securityerror [L_LONGMESSAGE0] => Securityheaderisnotvalid [L_SEVERITYCODE0] => Error )
    • Shabbir
      Dear Sir, Please help me to solve this problem? Fatal error: Call to undefined function curl_init() in C:\xampp\htdocs\shoppingcart\paypal-express-checkout\paypal.class.php on line 16 Thank you.
    • Shabbir
      Dear Sir, Please help me....! View cart page add item of product then " How to I will add paypal payment checkout option? " Please help me & give me the code. This code with helps me to develop my webpages. Thank you.
    • Gabriel
      I tried the demo and used my sandbox paypal account. my funds does not get deductions from the products that i ordered.
    • Joeson
      Why I get this error ? Error : Security header is not valid Array ( [TIMESTAMP] => 20170926T074907Z [CORRELATIONID] => 98f70237abfd6 [ACK] => Failure [VERSION] => 1090 [BUILD] => 39073839 [L_ERRORCODE0] => 10002 [L_SHORTMESSAGE0] => Securityerror [L_LONGMESSAGE0] => Securityheaderisnotvalid [L_SEVERITYCODE0] => Error ) Thanks.
    • Marco
      It would be very helpfull to have a PHP page that stores the entire content of the cart in the same database but in a "orders" table. Add an incremental order nr. Background: I'm using this excellent tut to make a small order food and drinks page. Customer orders 1 or more items, stored in cart, (sofar i have it working) Content cart to the waiter on another computer who starts serving it. (so he should be looking at the "orders" table.)
    • James Guina
      Hi your code works fine but I have a question and I can't figure it out, I already do the try and try but it seems it doesn't work. I want to add a parameter that will add item_color syntax because in your previous post about shopping cart it have a product_color how can i incorporate it here? thank you
    • Robert
      Hi there, SetExpressCheckout failed: error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure(35) i am trying to create it from Peru, thr BrainTree SDK is not supported for Peru, is that the problem? can i solve it? thanks in advance