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.

<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.

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,
    $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,
    //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 ).
                '&NOSHIPPING=0'. //set 1 to hide buyer's shipping address, in-case products that does not require shipping
                '&LOCALECODE=GB'. //PayPal pages to match the language on your website.
                '&LOGOIMG='. //site logo
                '&CARTBORDERCOLOR=FFFFFF'. //border color of cart

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

  1. Thanks so much :)

  2. Hello Team,
    can erverybody help me to modify this example paypal code, so that i can use it for mobile web app. Now i have the problem that after clicking paypal link, safari browser will open. it is not so nice.

    i can pay for your help.

    Thanks in advance,

  3. Excellent work, Thank you very much for help paypal sandbox code ..

  4. Hey Saran,
    great article. I have folowing problem and hope you can help me.
    I integrate paypal payment into my jquery mobile app and if anybody click “buy” ,safari browser will opens. This ist not so nice. I would like to execute paypal in an iframe into my webapp.

    Is any posibility to execute the paypal express ceheckout into a iframe(mobile app)?
    Can you help me an how it cost your solution.

    Thanks in advance,
    Best regards, Ben

  5. i am not getting any descriptions in payapal..when it redirects me to paypal i am not notified that how much i am going to pay? help me to get rid out of this..i used codeigniter cart in foreach loop.

  6. SetExpressCheckout failed: error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure(35)

    im getting above mentioned error. I given correct API username and password and signature.but i don’t know what happen.please some one help me……..

  7. Hello i ned some help…i need the life modus
    $paypalmode = ($PayPalMode==’live’) ? ‘.live’ : ”;

    $API_Endpoint = “https://api-3t”.$paypalmode.””;
    (this line must config for but what is to reed here )
    $version = urlencode(‘109.0’);
    The result fatal is:::
    Invalid HTTP Response for POST request(METHOD=SetExpressCheckout&VERSION=109.0&PWD=2MSJXZ9BQE9JDQBJ&USER=(cames the api information….)

  8. Fatal error: Call to undefined function curl_init() in C:\wamp\www\paypal-shopping-cart-example\paypal-express-checkout\paypal.class.php on line 16
    Call Stack

    error found.. could someone help me on that?

  9. SetExpressCheckout failed: (0)
    I am getting this error again and again. This demo is working properly but same code doesn’t work with me, Plz i need a quick solution, coz i have used same code for some live sites as well

  10. Hi Saran,
    I’ve used this script and it works like a charm. I’ve managed to make some little modification (adding new variables and eliminating others) and I’ve added the “insert in database” part you have written in a previous post, but my problem is the following: when the items are more than one how can I have them added to my table? Multiple mysqli insert? And if yes, can you give me an hint as I’m new to php programming and sometimes I feel a little bit lost…
    Thanks in advance for your help.

  11. Great tutorial but what if I will going to add Size using in shopping cart?

  12. Thanks for the great tutorial but I think you left out a step. Where do I get $GrandTotal?

  13. i got curl_init() error while running downloaded code .plz give me the solution

  14. Hi, I need to be able to send multiple items from the cart to the database, right now i can only send the first one from the ipn. Really appreciate the help. Thank you

  15. Great tut!!!
    I want to make 2 different things in the shopping cart. Can you please help me?
    How can I view cart in a new page and not in the same page of the products?
    I dont wanna send de order to paypall. I want to send an email instead. Is it possible?
    Thank you very much for sharing!

  16. I have the same error:

    Fatal error: Call to undefined function curl_init().
    using server2go.

    Can someone help me please.

  17. how to remove?

    Postage and packaging:
    Delivery discount –

  18. he saron this very nice way to use paypal express check out one thing can u please tale me how to send custom value and return that value becouse i want to send customer id and return that also

  19. Getting error :
    Fatal error: Call to undefined function curl_init().

    • Hello Nab
      tick php_curl in phpextension of
      WAMP server
      it is nothing but a curl package

  20. Hi Saran (This is the corrected comment the first one needs deleting!!)
    Great site works a treat I have bolted it to my takaway food database and everything works very well . It goes into the sandbox and all the products are there I log in to the first paypal screen with no problem then into the second paypal screen then when I click pay it returnes a no data error screen and does the same when I click the cancel link in paypal you get the same error screen.

    I have tried the program just out of the box and the same thing happens I have put all correct paypal and database details into the config file.

    So what am I doing wrong ??

  21. It works fine when tested locally, but when I test it on a web server the process.php page is blank after the pay now button is clicked. It’s crazy because the process page is the same as the local version.
    How do I fix this please?

  22. Hi Saran,
    Nice post! you safe my life…

  23. How can you make this process the checkout without PayPal and return the cart to a SQL database instead?

  24. I am getting this error again and again, i am testing it in localhost and using sanbox bussiness account api username, password and signature, everything is alright. I searched on google also and couldn’t solve it. I am really got stuck in this, everything is working but “Respond according to message we receive from Paypal”=>SetExpressCheckOut, this is not working or this is sending false or error message. I will really aperciate for the answer, Thanks in advanced
    Error : Security header is not valid
    [TIMESTAMP] => 2014%2d04%2d27T07%3a28%3a29Z
    [CORRELATIONID] => e8994b21364ad
    [ACK] => Failure
    [VERSION] => 109%2e0
    [BUILD] => 10775543
    [L_ERRORCODE0] => 10002
    [L_SHORTMESSAGE0] => Security%20error
    [L_LONGMESSAGE0] => Security%20header%20is%20not%20valid
    [L_SEVERITYCODE0] => Error

    • sorry not in localhost, m testing it on server

    • I have finally solved it, thanxs alot for the nice tutorila.

    • hi. how you solve it?

    • This types of error mainly occurs because of wrong input in your api username or password or signature. Just check your api username, password and signature properly. Also check on which mode you are checking it, either sanbox or live mode. Use sandbox api username, password and signature for sandbox mode and for live use live credentials .

  25. hey saran,
    I run your website and it is interesting website,
    but l have a simple question,
    why when I open the folder the first page in appear the index page?
    which code open the index page directly ?

  26. hello saran,
    l download your website in my computer, it is interesting website
    but I have question
    why the first page in open the index page?
    why doesn’t open the all file then l choose which page I want to display?
    which code is open the index page directly?

  27. Thanks for a great tutorial!!
    one question though, what information should i store in database (from the array showed in the success page)?

    • sorry, i found the commented part in the code that relates to the database insertion, but i seem to be missing a few variables ($ItemName, $ItemNumber, $ItemQty). also, if it was a multi-item transaction , how sould i put it in one row? or shouldnt i?

    • You can json encode multi item values and store in a row.

  28. Resolved. Thank you so much ~ ^^

  29. Error : Security header is not valid
    [TIMESTAMP] => 2014%2d02%2d08T15%3a22%3a16Z
    [CORRELATIONID] => 3e0151c15ecd
    [ACK] => Failure
    [VERSION] => 76%2e0
    [BUILD] => 9605603
    [L_ERRORCODE0] => 10002
    [L_SHORTMESSAGE0] => Security%20error
    [L_LONGMESSAGE0] => Security%20header%20is%20not%20valid
    [L_SEVERITYCODE0] => Error

    How do i eliminate this error. please assist

  30. in case user will click on process..php than open paypal page incase user will be press on back to website witch page insert record in my database i am a fresher please help me fast solve this problem replay to my mail account

  31. Need help with this!!!

    I can get this working on a website hosted on but when I try to host it myself on a Raspberry Pi I just get a blank screen. The PHP shopping cart works fine on the RPi but as soon as I try to proceded to the paypal checkout it opens the process.php file and gives a blank screen. I have echoed out the results from the database query and can get that to appear on the screen.

    Anyone got any ideas as to why it does not work on the RPi????

  32. Hi Saran, Please tell me how can I send any additional value/data to paypal e.g. I want to send an Order Number and a Customer ID among Mainly 4 variables as below:

    $paypal_data .= '&L_PAYMENTREQUEST_0_QTY'.$key.'='. urlencode($_POST['item_qty'][$key]);
    $paypal_data .= '&L_PAYMENTREQUEST_0_AMT'.$key.'='.urlencode($_POST['item_price'][$key]);
    $paypal_data .= '&L_PAYMENTREQUEST_0_NAME'.$key.'='.urlencode($_POST['item_name'][$key]);
    $paypal_data .= '&L_PAYMENTREQUEST_0_NUMBER'.$key.'='.urlencode($_POST['item_code'][$key]);
  33. Hey Saran

    Excellent work.


  34. Using default config.php from the download. I am getting this error:

    <b>Error : Security header is not valid</b>
        [TIMESTAMP] => 2014%2d02%2d08T15%3a22%3a16Z
        [CORRELATIONID] => 3e0151c15ecd
        [ACK] => Failure
        [VERSION] => 76%2e0
        [BUILD] => 9605603
        [L_ERRORCODE0] => 10002
        [L_SHORTMESSAGE0] => Security%20error
        [L_LONGMESSAGE0] => Security%20header%20is%20not%20valid
        [L_SEVERITYCODE0] => Error

    Can I get some dummy account details to show my client that this cart system which I have embedded in website, will take you to paypal website properly. PLEASE REPLY

  35. Excellent explanation!!!! The whole series was just great. I have been looking for a solution to mutiple items in the cart for awhile and the explanations and garble has been exasperatingly unfruitful .
    Really got a lot of this
    Thank You,

  36. I need to pass shipping cost and I am passing one extra parameter like
    As above I am trying to add shipping cost but it wouldn’t allow me to add and gave error “Error : The totals of the cart item amounts do not match order amounts”

  37. Hi, Very nice post but i am stuck with a problem .Getting an error “order total is missing” any one worked on it. Please reply.

  38. Thanks for your script. i am getting error while sending request to Paypal. Can you please check the below error.

    SetExpressCheckout failed: Unknown SSL protocol error in connection to (35)

  39. There is a problem with payment example(with out any modifications) gives error 10400 “Order total is missing”

  40. how to chnge $ to rupee symbol

  41. and i want to include pagination also because i have more then 100 products

  42. I want send that item to website owner instead of paypal. how to do?

  43. I’ve download the code , i put on my UNI server but is not working , php version 5.1 , in fact even in downloads section all those scripts are not working , any ideea ? Thanks

  44. i mean that php code is missing in the first and last lines.

  45. You forgot to put in the last line. this makes web editors to think it is HTML code and gives errors

  46. Hello,
    First thank you for the script. It worked great.
    Now, I need to send Shipping Cost and Shipping Address to paypal.
    How can i do so?? Is it possible??

    • how did u sort out everything , i follow the scripts but is not working ?

    • Hi adrian ! Download the demo script and add your credentials (paypal api username, password, key) to the config file included. And try it.

    • I did that , put as soon as I open it in my local server is says , Demo not available , what PHP version is it used in that script , do you know ?

      Thank You very much in advance

    • Adrian ! Downloaded file has mysql_import.sql file. Which needs to be imported in a database. And you will need to configure config.php.

    • dear this script is not working in my site just add to cart working and payment through paypal or process.php is not working tell me the solution

  47. Hi, i tested, all work great,
    but i can not see any order detail on Paypal transaction, like itemname, itemnumber ?
    any way to save the order detail in paypal ?

  48. hi saaraan
    how can I save in database products cart
    a single product mutli product

  49. Hey Saran

    Awesome work!! Thank you! I was wrecking my brain with this one!


Message Type : Question Comment ?
  • Question : Can include code, jsFiddle, codePen etc using Markdown Syntax.
  • Comment : Short comments and questions.