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

166 Comments Add Comment

  • Hi Saran and friends,
    This useful tutorial helped me a great deal and I’m very close to opening my web store. It is currently in testing: (
    But I get the following error message after arriving on the PayPal page:

    Warning: Invalid argument supplied for foreach() in /home/digimax/public_html/sandbox/paypal-express-checkout/index.php on line 124
    Error : OrderTotal (Amt) : Required parameter missing
    [TOKEN] => EC%2d14A102362G767925D
    [TIMESTAMP] => 2017%2d01%2d01T17%3a29%3a59Z
    [CORRELATIONID] => ff3b0bdeb7332
    [ACK] => Failure
    [VERSION] => 109%2e0
    [BUILD] => 28387177
    [L_ERRORCODE0] => 81100
    [L_SHORTMESSAGE0] => Missing%20Parameter
    [L_LONGMESSAGE0] => OrderTotal%20%28Amt%29%20%3a%20Required%20parameter%20missing
    [L_SEVERITYCODE0] => Error

    I have viewed all the previous comments to find solutions and all point to…
    Error : OrderTotal (Amt) : Required parameter missing.

    I know the Order Total is missing but how do I add it so that it works? I placed my API PayPal credentials and the PayPal mode is set to sandbox. I still can’t figure out how to fix it. Is it the syntax or is PayPal not picking up the shopping cart session?

    As for Line 124, it is….
    foreach($paypal_product[‘items’] as $key=>$p_item)
    $paypal_data .= ‘&L_PAYMENTREQUEST_0_QTY’.$key.’=’. urlencode($p_item[‘itm_qty’]);
    $paypal_data .= ‘&L_PAYMENTREQUEST_0_AMT’.$key.’=’.urlencode($p_item[‘itm_price’]);
    $paypal_data .= ‘&L_PAYMENTREQUEST_0_NAME’.$key.’=’.urlencode($p_item[‘itm_name’]);
    $paypal_data .= ‘&L_PAYMENTREQUEST_0_NUMBER’.$key.’=’.urlencode($p_item[‘itm_code’]);

    If there’s anyone who can remotely point me in the right direction and let me how to fix it, I would be very grateful.

    • UPDATE!!!!!!!

      The problem has been fixed. I guess it pays off to read the previous comments in the thread. Thanks to Scott Machalk’s comment dated May 12, 2015, my site actually works and now I get a success message.

      Regarding: “Error : OrderTotal (Amt) : Required parameter missing” message.

      All you have to do is make SURE that your PayPal return URL and PayPal Cancel URL contains the www of your URL. And that’s it. Everything is working fine. I had overlooked this comment so many times. It was out of frustration that I tried every suggestion and this one worked!

    • Glad it helped someone. : )


  • i want to add the updated cart value to my database how can i do this …

  • How can I remove the pop-up table and replace it with a cart icon and when I click add, the cart icon will show number 1 as quantity of added item. Please help me. Thanks

  • This is really nice article for adding multiple items at checkout :
    If you want to add multiple items to paypal checkout using: please visit

  • It is working properly but I want to change the label field ‘VAT’ to ‘Tax’ and ‘P&P’ to ‘Delivery’. How can I change?

  • Error : Security header is not valid

    [TIMESTAMP] => 2016%2d08%2d10T20%3a51%3a31Z
    [CORRELATIONID] => 66360e51c6dc2
    [ACK] => Failure
    [VERSION] => 109%2e0
    [BUILD] => 24362847
    [L_ERRORCODE0] => 10002
    [L_SHORTMESSAGE0] => Security%20error
    [L_LONGMESSAGE0] => Security%20header%20is%20not%20valid
    [L_SEVERITYCODE0] => Error

  • Ashok Sound Official Channel

    Hello, i’ve cart built using custom php scrip, having problem in cart pahe when more than one item in cart and click payment via paypal, a paypal checkout page get show only one item from cart which is last in current cart, have problem only with paypal checkout page i’ve another payment gateway integrate with my site but that is work vary well.

  • How to allow user to pay with credit card thru paypal payment gateway too ?

  • ( ! ) Fatal error: Call to undefined function curl_init() in C:\wamp\www\KAYA KO TO!\paypal-express-checkout\paypal.class.php on line 16
    Call Stack
    # Time Memory Function Location
    1 0.0021 431160 {main}( ) ..\index.php:0
    2 0.0213 473136 MyPayPal->PPHttpPost( ) ..\index.php:89

    please help me

  • Fatal error: Call to undefined function curl_init() in C:\wamp\www\MNL\paypal-express-checkout\paypal.class.php on line 16

  • I have a new error:
    [TIMESTAMP] => 2016%2d03%2d01T21%3a22%3a48Z
    [CORRELATIONID] => 78317c86c95c3
    [ACK] => Failure
    [VERSION] => 109%2e0
    [BUILD] => 18316154
    [L_ERRORCODE0] => 10001
    [L_SHORTMESSAGE0] => Transaction%20failed%20due%20to%20internal%20error
    [L_LONGMESSAGE0] => Internal%20Error
    [L_SEVERITYCODE0] => Error

    It worked once but now I keep getting this error.

    • If you are getting the internal error when in sandbox mode just try back later. It seems to be something that happens sometimes on PayPal side when their sandbox servers get busy.

  • from where i will get this all

    $PayPalApiUsername = ‘[email protected]’; //PayPal API Username
    $PayPalApiPassword = ‘979797979’; //Paypal API password
    $PayPalApiSignature = ‘AewouidSeoiewDradoZcgqH3hpacAokIiuNjAwoiedkew’; //Paypal API Signature
    $PayPalCurrencyCode = ‘USD’; //Paypal Currency Code

  • Hi

    I seem to be able tot execute a transaction (I don’t receive any errors whatsoever) but I don’t see them in the transaction overview of my sandbox account so I assume there’s something wrong anyway.

    Any suggestions?

    Much obliged

  • I am getting error:
    SetExpressCheckout failed: SSL connect error(35)
    When I click the Pay with PayPal button

    • For those who are getting the error:
      SetExpressCheckout failed: SSL connect error(35) or something similar, try adding
      curl_setopt($ch, CURLOPT_SSLVERSION, 6); to the paypal.class.php

  • Hi..
    I want to see the transaction ID on success page using shopping cart in site plz help me

  • Not Found

    The requested URL /shopping-cart/paypal-express-checkout/cancel_url.html was not found on this server.

    Apache/2.4.9 (Win32) PHP/5.5.12 Server at Port 80

  • Hello,

    Do I still need IPN listener to pay pal express checkout or that’s totally unecessary?

    Thank you!

  • Hello Saran,
    I am getting following error when trying to implement this script-

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

    Please advise what could be the reason.
    Thanks in advance.

  • Fatal error: Call to undefined function curl_init() in C:\wamp\www\PHP-Shopping-Cart-PayPal-Express-Checkout-master\paypal-express-checkout\paypal.class.php on line 16

    Please help me! ty!

  • Thanks !That’s very useful .

  • Dear, Thank you for this nice tutorial, Please help me to remove … .. .. ..Test Store from paypal. I can’t remove this. I have a personal account on paypal. Bussiness a/c at sandbox.

  • Sorry, but this tutorial is garbage. Unless the developer is working towards this one very rigid use-case, it doesn’t work. Unfortunately, I’ve spent days going down the road of this code and it has been a complete waste of time. This should be taken down or updated to fit more common use-cases.

  • There is a significant flaw in this code that seems to be the root of a lot of issues: you have to make sure you include the post variables in the view_cart page. This is a huge miss in this tutorial, so I’d expect anyone trying to work customization into the code would receive the “Order total is missing” error. This is the code you must ensure you include:

    product_name.'” />’;
    product_desc.'” />’;
    $cart_items ++;

    The idea of hard-coding taxes, discounts, etc. also doesn’t make sense for any use-case I could think of. So with that said, you may want to pass the tax_list value(s) in the post method as well.

    • Hi Dave,
      The owner of this site seems not to be doing anything anymore.
      I had this code working, but I don’t have time right now to help you out.
      As soon as I can I will put a post with a link to the working code.

    • Hi Alain
      Please let me know when you put a post with a link to the working code.

      Thanks a lot Man

    • No problem. I will.

  • I got stuck at the actual payment method with the following error message:
    Error : PaymentAction : Required parameter missing
    I have the parameters set just as in the sample code, but it has been to no avail. Any suggestions would be appreciated.

  • hi.. i want to ask you .. after the payment is done..why this message appear? and it also does not insert data in my database..
    please help me! thank you


    Your Transaction ID : 8BG179154L751634R
    Payment Received! Your product will be sent to you very soon!

    Stuff to store in database :
    Success! ID of last inserted record is : 4
    [TOKEN] => EC%2d5MX00444HW9472833
    [CHECKOUTSTATUS] => PaymentActionCompleted
    [TIMESTAMP] => 2015%2d11%2d07T09%3a12%3a00Z
    [CORRELATIONID] => 8027e8fbcb868
    [ACK] => Success
    [VERSION] => 109%2e0
    [BUILD] => 18308778
    [EMAIL] => saril21%40personal%2ecom
    [PAYERSTATUS] => verified
    [FIRSTNAME] => saril
    [LASTNAME] => muhammad
    [SHIPTONAME] => saril%20muhammad
    [SHIPTOSTREET] => Level%2001%2c%20No%201%2c%20First%20Avenue%20Bandar%20Utama
    [SHIPTOCITY] => Petaling%20Jaya
    [SHIPTOSTATE] => Selangor
    [SHIPTOZIP] => 47800
    [ADDRESSSTATUS] => Unconfirmed
    [AMT] => 56%2e48
    [ITEMAMT] => 50%2e90
    [SHIPPINGAMT] => 3%2e00
    [HANDLINGAMT] => 2%2e00
    [TAXAMT] => 2%2e58
    [INSURANCEAMT] => 1%2e00
    [SHIPDISCAMT] => %2d3%2e00
    [L_NAME0] => 5%20in%201%20Diaper%20Bag%20Brown
    [L_NUMBER0] => 001
    [L_QTY0] => 1
    [L_TAXAMT0] => 0%2e00
    [L_AMT0] => 50%2e90
    [L_ITEMWEIGHTVALUE0] => %20%20%200%2e00000
    [L_ITEMLENGTHVALUE0] => %20%20%200%2e00000
    [L_ITEMWIDTHVALUE0] => %20%20%200%2e00000
    [L_ITEMHEIGHTVALUE0] => %20%20%200%2e00000
    [PAYMENTREQUEST_0_AMT] => 56%2e48
    [PAYMENTREQUEST_0_SHIPTONAME] => saril%20muhammad
    [PAYMENTREQUEST_0_SHIPTOSTREET] => Level%2001%2c%20No%201%2c%20First%20Avenue%20Bandar%20Utama
    [PAYMENTREQUEST_0_SHIPTOCITY] => Petaling%20Jaya
    [L_PAYMENTREQUEST_0_NAME0] => 5%20in%201%20Diaper%20Bag%20Brown
    [L_PAYMENTREQUEST_0_TAXAMT0] => 0%2e00
    [L_PAYMENTREQUEST_0_AMT0] => 50%2e90
    [L_PAYMENTREQUEST_0_ITEMWEIGHTVALUE0] => %20%20%200%2e00000
    [L_PAYMENTREQUEST_0_ITEMLENGTHVALUE0] => %20%20%200%2e00000
    [L_PAYMENTREQUEST_0_ITEMWIDTHVALUE0] => %20%20%200%2e00000
    [L_PAYMENTREQUEST_0_ITEMHEIGHTVALUE0] => %20%20%200%2e00000

  • Christopher Taylor

    Thanks for a great tutorial. There are some something scenarios I’m thinking of and that need to be covered and there are multiple ways, I’m just wondering how you would do it. I’m just after an opinions.
    So, the cart is stored as session variable, but, lets imagine user1 and user2 have the same page open and I only have 1 of a particular item in stock.
    user1 adds the item to the cart, which is stored in a SESSION var, and is on the checkout_page, but not yet checked out. user2 then picks up the same item, and user1 checks out. user2 arrives at the checkout with the item that has the item user1 has bought… how would you address this race condition?

    I would probably do a quick SQL query to ensure the order can be fulfilled at the point of checkout – just before payment is taken. Anyone else got any thoughts?


    • thanks a lot.
      I tried a lot of script about paypal checkout express without success.
      Your scripts works fine!

  • One important question I have, the workflow I did and everything works nice, until one small thing:

    1. The customer can add each product per add. This goes into the cart
    2. Check Out Cart, works too
    3. Payment Checkout, then redirect to paypal
    4. Return to the page self.

    How I empty my cart?

    Kindly Simon

  • Hi
    Anyone help me please. After I click Pay Now button, I got a blank page(white).
    I have tried to many times to find out where the error is,but I cannot figure out.
    I test it on Sandbox on server(not using xampp).I have tried using API credential so many times.Still not working. I wonder that..
    1).Besides the API credential such as API password,user name and signature,is there any paypal parameter or constant value that I need to change/modify in the config.php,process.php and/or paypal.class.php? Like API version(example:$version = urlencode(‘109.0’),
    API_Endpoint( example:”https://api-3t”.$paypalmode.””;) or anywhere that I miss.
    Please help
    It is my final college project.I have been stuck almost 2-3 weeks now.
    Thank you

  • After clicking pay now button I’m getting this message
    (SetExpressCheckout failed: Failed connect to; No error(7))

  • Those of you that are having issues with the “Error: Order total is missing” message, make sure the url in your PayPal variables matches your site.
    In my case, I had set as the return page and I was actually working from
    I was having very inconsistent behavior with different browsers and computers. If you do this, you will lose your $_SESSION variables and you will get the above error message. I’ve been pulling my hair out over this one.
    If this helps you, let me know!

  • Thank You. This is one of the best series of tutorials ever. Keep up the good work.

  • I successfully process a payment via sandbox and get the transaction id information, how do I redirect to a payment success page after payment complete.


    • Also Wish To Display information from the transaction on the payment complete page and also the cart doesn’t empty upon successful transaction via paypal.

      Can you help?>

    • The success message can be modified in the downloadable process.php page around line 134.

  • I check it localhost just tri it demo but this error
    Fatal error: Call to undefined function curl_init() in C:\xampp\htdocs\paypal\paypal-express-checkout\paypal.class.php on line 16
    pls solution give me

  • Hi,
    I have been using php multiple shopping cart and I have a small problem
    I have set the Paypal process page to save information in to MySQL database. I have it saving customer information and I can only get it to save one shopping cart item. Please could you help me save more than one item to the database.


  • i got this error
    Error : Security header is not valid
    [TIMESTAMP] => 2015%2d03%2d22T11%3a54%3a08Z
    [CORRELATIONID] => 6779aac4dd310
    [ACK] => Failure
    [VERSION] => 109%2e0
    [BUILD] => 15826044
    [L_ERRORCODE0] => 10002
    [L_SHORTMESSAGE0] => Security%20error
    [L_LONGMESSAGE0] => Security%20header%20is%20not%20valid
    [L_SEVERITYCODE0] => Error
    Please help me :(

    • Change the paypal setting in config.php as shown in below

      $PayPalMode = ”;
      $PayPalApiUsername = ‘ ‘; // type your PayPalApiUsername
      $PayPalApiPassword = ‘ ‘; // type your PayPalApiPassword
      $PayPalApiSignature = ‘ ‘; // type your PayPalApiSignatur

    • thanks so much PRO !

  • hello . i’ve try the code but the order are not be insert into the SQL .. can u help me ?

  • Hello guys, I have tried this code on xampp and it works. But when I upload the code to the server, everything works correctly until I click “pay now bottom”, then I get to this link “” and it stays with a white/empty site.

    So I am wondering what I can do to make it work online, as it does in localhost?

    • Hi Ari
      How did you find out ? I’ve got the same problem with blank(white) page after clicking the pay now button.
      I have been stuck 2 weeks now.If you don’t mind.Put answer here or to my email: [email protected]

  • how can i change the logo of sanwebe on paypal ??

  • i got this error in process.php how can i fix this.

    Error : Security header is not valid
    [TIMESTAMP] => 2015%2d03%2d15T19%3a20%3a11Z
    [CORRELATIONID] => dfae9f58a55da
    [ACK] => Failure
    [VERSION] => 109%2e0
    [BUILD] => 15735246
    [L_ERRORCODE0] => 10002
    [L_SHORTMESSAGE0] => Security%20error
    [L_LONGMESSAGE0] => Security%20header%20is%20not%20valid
    [L_SEVERITYCODE0] => Error

    • vinay kumar singhal

      You will need to add complete path in config.php

      $PayPalReturnURL = ‘http://localhost/paypal-shopping-cart-example/paypal-express-checkout/process.php’; //Point to process.php page
      $PayPalCancelURL = ‘http://localhost/paypal-shopping-cart-example/paypal-express-checkout/cancel_url.html’; //Cancel URL if user clicks cancel

  • i got an error in Call to undefined function curl_init() in C:\wamp\www\paypal\paypal.class.php on line 16
    how do i fix this?

  • my cart doesnt connect to paypal?? i changed my sadnbox apis

  • Hi. What webhost did you used for the paypal express checkout? I’m using but it doesn’t support the checkout anymore. Please suggest me a good webhosting site with database that supports this checkout. THANK YOU SO MUCH

  • hi could you help me please, when i click on pay now i dont get transfered to paypal? error in process php?

  • ERROR: Invalid Header
    Multiple Items PHP Shopping Cart to PayPal

    Sir Please Help..

  • Great script! Can the shopping cart be saved in a database instead of Paypal processing?

  • Hi i am getting this error, the problem is it happens sometimes !
    any fixes would be welcome, thanks in advance

    Order total is missing.
    Array ( [TIMESTAMP] => 2015%2d01%2d27T22%3a18%3a57Z [CORRELATIONID] => 7ad534795d0d6 [ACK] => Failure [VERSION] => 109%2e0 [BUILD] => 15009693 [L_ERRORCODE0] => 10400 [L_SHORTMESSAGE0] => Transaction%20refused%20because%20of%20an%20invalid%20argument%2e%20See%20additional%20error%20messages%20for%20details%2e [L_LONGMESSAGE0] => Order%20total%20is%20missing%2e [L_SEVERITYCODE0] => Error )
  • Hi,can u pls help me to solve this issue??I got one error when running this.The error showing
    Got Http response code 401 when accessing
    what is the reason??plsss help.otherwise ur work is appreaciated..more helpful for me

  • Thank you very much chief Saran
    All works well after the following changes:
    1) in process.php and paypal.class.php change [$paypalmode = ($PayPalMode==’sandbox’) ? ‘.sandbox’ : ”;] TO [$paypalmode = ($PayPalMode==”) ? ” : ”;] if you don’t use sandbox.
    2) in process.php change the variable ($ItemTotalPrice) TO ($total)
    3) in config.php change ($PayPalMode = ‘sandbox’;) TO ($PayPalMode = ”;)

    That’s it, and all work beautifully.

  • Hi,

    Any suggestion which function to trigger for update when an user is at view_cart.php and decides to alter the quantities of a product??

    Any tips?

    • I have the same problem. View Cart works when the action of the form is cart_update.php and paypal works when the form is process.php but they don’t work together.

  • Hi, everyone i am getting this error, i’ve spent hours on and found any fix, any fix will be welcome !

    Error : Order total is missing.

    thx a lot

    • the problem is, sometimes scripts work fine, sometimes not !

    • I think there is a significant disparity in the nomenclature: product_ vs. item_ is extremely confusing in the context of the tutorial. I have spent days trying to troubleshoot but it’s been to minimal avail thus far.