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.

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
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

160 Comments Add Comment

  • Thanks so much :)

     Reply
  • 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,
    Ben

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

     Reply
  • 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

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

     Reply
  • 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……..

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

    $API_Endpoint = “https://api-3t”.$paypalmode.”.paypal.com/nvp”;
    (this line must config for paypal.com 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….)

     Reply
  • 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?

     Reply
  • 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

     Reply
  • 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.
    Michele

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

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

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

     Reply
  • 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

     Reply
    • hi alain, how to setup your cart in purchasing items? i already done with that but.. in my sandbox paypal account.. i dind’t receive money transper.. what should i do???
      thank hope your reply to my email: [email protected]

  • 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!

     Reply
  • I have the same error:

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

    Can someone help me please.

     Reply
  • how to remove?

    VAT:
    Postage and packaging:
    Delivery discount –
    Insurance

     Reply
  • 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

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

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

  • 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 ??

     Reply
  • 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?

     Reply
  • Hi Saran,
    Nice post! you safe my life…
    Thanks..

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

     Reply
  • 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
    Array
    (
    [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
    )

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

  • 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 ?

     Reply
  • 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?

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

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

  • Resolved. Thank you so much ~ ^^

     Reply
  • Error : Security header is not valid
    Array
    (
    [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

     Reply
    • I usually get this error when sandbox API credentials are used in live mode.. or vice versa.

  • 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

     Reply
  • Need help with this!!!

    I can get this working on a website hosted on uk.godaddy.com 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????

     Reply
  • 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:

    1
    2
    3
    4
    $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]);
     Reply
  • Hey Saran

    Excellent work.

    Bussa

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

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    <b>Error : Security header is not valid</b>
    Array
    (
        [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

     Reply
  • 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,
    CBT

     Reply
  • I need to pass shipping cost and I am passing one extra parameter like
    &PAYMENTREQUEST_0_SHIPPINGAMT=3.00
    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”

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

     Reply
  • 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 api-3t.sandbox.paypal.com:443 (35)

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

     Reply
  • how to chnge $ to rupee symbol

     Reply
  • and i want to include pagination also because i have more then 100 products

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

     Reply
  • 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

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

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

     Reply
  • 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??
    Thanks.

     Reply
    • 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

  • hey Saaran

    thanks dude!!!

     Reply
  • 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 ?

     Reply
  • hi saaraan
    how can I save in database products cart
    a single product mutli product

     Reply
  • Hey Saran

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

    Roy

     Reply