How to easily integrate a PayPal Checkout with PHP

PayPal is a renowned payment platform that allows you to accept online payments on your site, by taking care of all the money transactions for you. This transparency really is an appreciated quality that allows developers to integrate checkout solutions on merchant sites, by completely outsourcing the banking operations to PayPal.

Another good thing for developers is that the PayPal API is very versatile. It can be very simple if your needs are simple, or it can be very well customized to meet some more advanced needs such as complete shopping carts handling. On the other hand, I sometimes find this API not really user friendly as it works with forms, which fields are not always very intuitive. In other words, depending on the form you are building, you get a different service from PayPal.

In order to get a friendlier and also more generic solution, I wrote a PayPal manager in PHP. This tutorial will show you how you can benefit from this PHP class to integrate PayPal checkouts faster and in a much simpler way.

Thank You for Downloading

I'm glad that you found my work useful. If you did, it might help some other people too. So why not helping me spread the word with a tweet? You could also buy me a coffee to thank me for my code and explanations if you prefer ;).
I hope you'll enjoy your download. Regards. Jeremy.

How to setup

Getting Started

In order to receive PayPal payments, you must have a PayPal account, registered with a valid email address. If you do not have an account, you can easily register here. Then let's start by preparing a set of basic settings that will configure the class in the exact way you want. We'll specify here a few things such as the account you want to use to receive payments, the currency you'd like to use, and your location for example. We'll do so by opening the constructor of the PHP class, and by changing here the different variables with the ones you want:
  1. //=======================================================================//
  2. //==> Class constructor, with default settings that can be overridden <==//
  3. //=======================================================================//
  4. public function __construct($config = "") {
  6. //default settings
  7. $settings = array(
  8. 'business' => '', //paypal email address
  9. 'currency' => 'GBP', //paypal currency
  10. 'cursymbol' => '&pound;', //currency symbol
  11. 'location' => 'GB', //location code (ex GB)
  12. 'returnurl' => 'http://mysite/myreturnpage', //where to go back when the transaction is done.
  13. 'returntxt' => 'Return to My Site', //What is written on the return button in paypal
  14. 'cancelurl' => 'http://mysite/mycancelpage', //Where to go if the user cancels.
  15. 'shipping' => 0, //Shipping Cost
  16. 'custom' => '' //Custom attribute
  17. );
  19. //overrride default settings
  20. if (!empty($config)) {
  21. foreach ($config as $key => $val) {
  22. if (!empty($val)) {
  23. $settings[$key] = $val;
  24. }
  25. }
  26. }
  28. //Set the class attributes
  29. $this->business = $settings['business'];
  30. $this->currency = $settings['currency'];
  31. $this->cursymbol = $settings['cursymbol'];
  32. $this->location = $settings['location'];
  33. $this->returnurl = $settings['returnurl'];
  34. $this->returntxt = $settings['returntxt'];
  35. $this->cancelurl = $settings['cancelurl'];
  36. $this->shipping = $settings['shipping'];
  37. $this->custom = $settings['custom'];
  38. $this->items = array();
  39. }
Line 8, change this email address to the one linked with your PayPal account. Line 9, put the currency code you wish to use, (here GBP). Line 10, write the html currency symbol (this is not a necessary setting but it is useful to have it as you will see later on). Line 11, put the ISO code of your country. The next 3 lines are here to specify how the PayPal interface will behave once the user is logged into PayPal and ready to pay. For example, PayPal shows a button to the user once the transaction is completed to allow him to go back to your site. Line 12 you can specify where this button will link to, typically, a thank you page or something like that. Line 13, write what you want to be written on that button, and line 14, specify the url you'd like the user to visit in case he cancels his transaction. Lines 15 and 16, you have some more advanced settings such as shipping, which allows you to set a shipping price for your cart if you are to send items to a customer (a bit more on that later on). The custom field is a sort of free text field that you can pass to PayPal, typically to identify your cart, such as an invoice number for example. Those settings are your default settings. They can always be overridden when you create instances of the class, but as they are often the same, by using default values you don't have to specify them all the time. That's it for your basic default configuration that contains some account specific information. We'll now see how from this, you can create a shopping cart checkout, and work with it, meaning add to it some cart specific information (as opposed to the account specific ones) in order to send everything you need to PayPal.

The PayPal shopping cart

A PayPal shopping cart is composed of different elements. In order to get paid, what you need to send to PayPal is an account email, a currency, (which have already been defined), and a list of items. You can also set a shipping price, and pass a custom value if needed. In PayPal, items are made of at least 3 elements, a name, which describes the item in the cart, a unit price for this item, and a quantity. The total price for this item will therefore be calculated based on the multiplication of the unit price by the quantity. For the purpose of this example, let's imagine that we are trying to sell tickets for a concert. We'll have three different ticket prices, bronze tickets at £15, silver tickets at £20, and gold tickets at £30. I'm not actually trying to sell any ticket for anything here, it is just for the sake of having a real life example to work with. So now that our account is ready, and that we have a real life problem to solve, let's start to see how we use the manager. As you can see in the demonstration, you can use the form to choose how many tickets from each category you want. After the form has been submitted, the aim is to retrieve the number of wanted tickets from the post and to build a checkout based on those numbers. We can do so like this:
  1. $items = array(
  2. 1 => array(
  3. "name" => "Gold Tickets",
  4. "price" => 30,
  5. "quantity" => (int) htmlentities($_POST["gtkt"], ENT_QUOTES),
  6. "shipping" => 0
  7. ),
  8. 2 => array(
  9. "name" => "Silver Tickets",
  10. "price" => 20,
  11. "quantity" => (int) htmlentities($_POST["stkt"], ENT_QUOTES),
  12. "shipping" => 0
  13. ),
  14. 3 => array(
  15. "name" => "Bronze Tickets",
  16. "price" => 15,
  17. "quantity" => (int) htmlentities($_POST["btkt"], ENT_QUOTES),
  18. "shipping" => 0
  19. )
  20. );
From this array, we can clearly see the different components of each item, its name, its unit price, its quantity (retrieved from the post), and its shipping price, (we are kind enough in this case to offer free shipping ;-)). It is now time to pass those values to our PayPal Manager that will build the correct PayPal form for us. First, we create an instance of the class, then, we add the items simply by calling the addMultipleItems method:
  1. include("lib/paypal_checkout/paypal.php"); //Include the class
  2. $pp = new paypalcheckout(); //Create an instance of the class
  3. $pp->addMultipleItems($items); //Add all the items to the cart in one go
If you are interested about what the addMultipleItems method does, just read on, otherwise, you can jump to the next step. When we call this method, we pass it an array of items. What it does after that is loop through those items, and add them one by one by calling the addSimpleItem method. In turn, the addSimpleItem method checks if the quantity and the name of the item are right before adding it to the cart. Remember, for an item to be valid, it needs to be composed of a name, a unit price and a quantity.
  1. //=========================================//
  2. //==> Add an array of items to the cart <==//
  3. //=========================================//
  4. public function addMultipleItems($items) {
  5. if (!empty($items)) {
  6. foreach ($items as $item) { //lopp through the items
  7. $this->addSimpleItem($item); //And add them 1 by 1
  8. }
  9. }
  10. }
  12. //=====================================//
  13. //==> Add a simple item to the cart <==//
  14. //=====================================//
  15. public function addSimpleItem($item) {
  16. if (//Check the quantity and the name
  17. !empty($item&#91;'quantity'&#93;)
  18. && is_numeric($item&#91;'quantity'&#93;)
  19. && $item&#91;'quantity'&#93; > 0
  20. && !empty($item['name'])
  21. ) { //And add the item to the cart if it is correct
  22. $items = $this->items;
  23. $items[] = $item;
  24. $this->items = $items;
  25. }
  26. }

Checking the cart content

Now that the items have been added, you can check your cart content at any time. There are two ways to do this. The first one is by calling a method called getCartContentAsHtml. As its name implies, when you call this content, you are returned a nicely formatted list, which shows the elements that are about to be sent to PayPal. It's an excellent summary to give to the user before finalising the transaction for example. In our case, if for example we buy 4 gold tickets, 2 silver ones, and 2 bronze ones in one go, and call the getCartContentAsHtml, we will be given this as a result:
  1. <ul id="cartcontent">
  2. <li class="cartitem">4 x "Gold Tickets" at &pound;30 for &pound;120</li>
  3. <li class="cartitem">2 x "Silver Tickets" at &pound;20 for &pound;40</li>
  4. <li class="cartitem">2 x "Bronze Tickets" at &pound;15 for &pound;30</li>
  5. <li class="carttotal">Total: 8 Items for &pound;190</li>
  6. </ul>
As you can see, this method shows each item in the cart with its name, unit price, quantity and total price per item, as well as the final amount of the cart. If you just want to check the items in the cart, in other words, get the raw array of items, you can do so like this: $items = $pp->items; After that, you have an array called items in the variable $items, that you can work with. To do a simple check, just print the array content with the function print_r($items) to see its content.

Getting the PayPal checkout form

Like we've said in the introduction, PayPal works with forms. You build a particular form based on the service you wish to get, and you pass it to PayPal. Upon reception, PayPal prepares the corresponding transaction and takes the user through it. The problem with forms is that it's rather not really user friendly nor straight forward to build and to work with. With the PayPal manager, you don't need to worry about the different forms, or the different variables, not even about the different fields that need to be sent to PayPal. All the hard work will be computed for you. The only thing you have to do is to call the getCheckoutForm method. yes really, as simple as a method call. Based on the items you have in the cart, the method will write and return the correct form. That's what I call easy to work with. In our example, a call to echo $pp->getCheckoutForm(), will return:
  1. <form id = "paypal_checkout" action = "" method = "post">
  2. <input name = "cmd" value = "_cart" type = "hidden">
  3. <input name = "upload" value = "1" type = "hidden">
  4. <input name = "no_note" value = "0" type = "hidden">
  5. <input name = "bn" value = "PP-BuyNowBF" type = "hidden">
  6. <input name = "tax" value = "0" type = "hidden">
  7. <input name = "rm" value = "2" type = "hidden">
  9. <input name = "business" value = "" type = "hidden">
  10. <input name = "handling_cart" value = "0" type = "hidden">
  11. <input name = "currency_code" value = "GBP" type = "hidden">
  12. <input name = "lc" value = "GB" type = "hidden">
  13. <input name = "return" value = "http://mysite/myreturnpage" type = "hidden">
  14. <input name = "cbt" value = "Return to My Site" type = "hidden">
  15. <input name = "cancel_return" value = "http://mysite/mycancelpage" type = "hidden">
  16. <input name = "custom" value = "" type = "hidden">
  18. <div id = "item_1" class = "itemwrap">
  19. <input name = "item_name_1" value = "Gold Tickets" type = "hidden">
  20. <input name = "quantity_1" value = "4" type = "hidden">
  21. <input name = "amount_1" value = "30" type = "hidden">
  22. <input name = "shipping_1" value = "0" type = "hidden">
  23. </div>
  24. <div id = "item_2" class = "itemwrap">
  25. <input name = "item_name_2" value = "Silver Tickets" type = "hidden">
  26. <input name = "quantity_2" value = "2" type = "hidden">
  27. <input name = "amount_2" value = "20" type = "hidden">
  28. <input name = "shipping_2" value = "0" type = "hidden">
  29. </div>
  30. <div id = "item_3" class = "itemwrap">
  31. <input name = "item_name_3" value = "Bronze Tickets" type = "hidden">
  32. <input name = "quantity_3" value = "2" type = "hidden">
  33. <input name = "amount_3" value = "15" type = "hidden">
  34. <input name = "shipping_3" value = "0" type = "hidden">
  35. </div>
  37. <input id = "ppcheckoutbtn" value = "Checkout" class = "button" type = "submit">
  38. </form>
As you can see, there's a lot going on here from a simple method call. Let's have a look at what all of this means. From line 2 to 7, you can find fields and variables that are specific to PayPal card checkouts. I personally never change them. Lines 9 to 16, you actually retrieve most of the variables we defined at the very beginning of this tutorial. For example, line 9 is your account email, line 11 the currency, line 12 your location, and line 13, 14 and 15 the button behaviour. If you wish to change those values, simply change the instance attributes like this : $pp->location="FR" and $pp->currency="EUR" for example if you wish to get euros in France for example, just before calling the getCheckoutForm method. You can also change the default settings like we did at the beginning as well if you prefer. Personaly, I tend to set default settings with the values I always use, and I then deal with the cart specific data by changing the instance attributes. After that, between the lines 18 and 35, you have your items. For each as you can see you retrieve the name, the quantity, the amount (which is the unit price), and the shipping value, (which is free in our case). Finally, line 37, you have your submit button. If you wish to change the way this submit button looks, you can do so in the getCheckoutForm method line 153. Your form is now ready to be sent to PayPal. When the user will press the submit button, he will be redirected to PayPal, which will display the following screen: paypal checkout summary As you can see, PayPal understood our request. It shows here that the account that will receive the funds is as specified It displays a complete breakdown of what is going to be billed based on the item we sent. And it computes the final amount to be paid.


Working with PayPal form is not the most convenient thing to do. This little manager helps you streamline the process of integrating PayPal checkouts easily, by proposing a set of handy little methods. It certainly saved me a lot of time. You are free to reuse and expand the code for your own convenience. I hope it will help you in your future PayPal integrations.

38 Responses to How to easily integrate a PayPal Checkout with PHP

  1. But what about crediting the user with the purchase? I have a membership oriented site, so there's nothing to ship. I collect money and need to credit the sale to the user so that I know he has paid. This would be a great guide if you would add that kind of information.

  2. Really helpful for multiple implementations, for sure. I'm leaning more towards the doDirectPayment API, but man is it ever a pain.
    Well done.

  3. What Paypal Account was this done with, The free paypal Standard or Paypal Express (£20) per month account ?


  4. @James. It has been done with the standard free paypal account. Regards. Jeremy

  5. thanks so much. this article appear just in time.

  6. This is a great write up, and I'm looking forward to using it, but I'm running into some problems. Originally I was getting an unexpected t_string error, so I uploaded the script to a PHP5 sever. Now it's all white.
    Any suggestions?

  7. I'm extremely impressed with your writing skills as well as with the layout on your blog. Is this a paid theme or did you modify it yourself? Anyway keep up the nice quality writing, it is rare to see a nice blog like this one these days..

  8. What ever information is given here is quite enough to start work else part i need to customize .. Thanx for this kind of info..

  9. Hi could you please help me, I get an error at
    Line 4.
    public function __construct($config = "") {

    • That's just the constructor. You have to put it in a class.

      • Add how do you do that

  10. Hello, can you please help me about a question? When I try your sample and everything was okay, but I am confused that I set a sandbox account of Business and paid to this account, why is the balance always 0? I tested to creat another account ... but it was no solved. I was at a loss about what to do lol....

  11. it's simple

  12. This is really awesome and really simplifies the process of integrating paypal into a website. I was wondering if you could provide some pointers for adding a function for removing an item from the cart and updating the quantity as well. Thank you!

  13. Thank-you so much for this! Very concise, very useful.

  14. This method is crazy unsafe!!! And I keep seeing this over and over again. Anyone could easily tamper with the form inputs anything from changing the price to $1 or even the account to which the money is going. So I could essentially pay $1 to myself and claim the digital product your selling, because paypal wound send you a success notification. Of course there are things you could do to validate Paypal response, but its just bad practice. Don't ever post business critical data in an HTML!!!

  15. I agree it's unsafe.It is very obvious. But how to make it safe???

  16. When you post the form you would simply append these business details to the postdata of a cURL or something to that effect where the user never sees this information and more importantly cant change the price you send to PayPal

  17. i have implemented sandbox paypal button . the transaction is done proerly from my personal sandbox account to businees sandbx account. Even after succesful transaction it returns to my thankyou page as i have given link for succesful and notify url. But i get return array as balnk with just auth key.Why am i not getting full payment array.i tried sending hidden fields with values. not getting them also.
    please suggest. thanks :)

  18. Tank you very much ;)

  19. I have a query?
    i want to know like this is the code for PayPal Integration but how we can use PHP PayPal API with the code.
    I have downloaded the API and now how can i use that API with code?
    I m beginner so want to ask how can i can use PayPal.
    Please help me!!!!

  20. Very nice and helpful code. But there is no way to verify that this return path is hit by paypal return instead of manually hit. Please suggest me some way how to validate this payment process something like the way PayPal IPN do.

  21. wow

  22. Great post, but as with the above commenter's I wanted a more secure method, which I found in this post on Stackoverflow:

    Also to validate/verify a payment via PayPal IPN, I used this post as reference:

    Currently I'm putting together what I learned here, as well as the above to links, to create a final PayPal class file to handle the whole processes.

  23. hi
    I am new..can you just tell me how i can save these files and wich names are these files??

  24. What about preventing user to modify amount of item from html source code ?

  25. dosnt work anymore paypal has change the api and the way to request this code may need to update
    anyway thank you

  26. Hey brother!

    I am creating a website where i want to sell virtual coins. So i want to add paypal system there so that one can buy coins. All coins has same price. I am unable to get the top mentioned things. Please help me out

  27. Thank you very much but how and where can I get paypal package folder to implement those instance and classes?

  28. Hi,
    This is classified website. I did successfully payment on paypal. But after payment I want to return on my website. and do my website functionality but I can't return on my website after payment. Can u help me out. How I can do this work

  29. Pingback: Anonymous

  30. in payment process after success payment it will not return to my site.?? why??

  31. It's awesome to visit this web site and reading the views of all colleagues about this article,
    while I am also zealous of getting know-how.

  32. For most recent information you have to pay a quick visit the web and on the
    web I found this web page as a most excellent web page for most recent updates.

  33. This web site definitely has all of the info I wanted
    concerning this subject and didn't know who to ask.

  34. Hi there, everything is going well here and ofcourse every one is sharing information, that's actually good,
    keep up writing.

  35. It's really a cool and helpful piece of information. I am
    happy that you simply shared this useful info with us.
    Please keep us up to date like this. Thank you for sharing.

  36. Oh my goodness! Impressive article dude! Thank you so much, However I am having problems with your RSS.
    I don't know why I cannot subscribe to it. Is
    there anybody having the same RSS problems?
    Anyone who knows the solution can you kindly respond? Thanx!!

Leave a Reply

Your email address will not be published. Required fields are marked *

Other Useful Resources

How to make SEO friendly urls illustration

It's now quite common to swap the old url format containing file extensions and non explicit query strings by SEO friendly ones, only made of keywords and slashes, hence their name.

There are several techniques to do so, and I certainly do not have the pretention to say that this one is the best of all, but it is the one I use in personal projects as it works nicely, and it is robust and dynamic.

It makes use of an .htaccess file to rewrite the urls, of a php function to parse the given parameters, and a content manager to serve the appropriate content according to them.

Before we start I'd like to make a personal thanks to Josh Moont for his precious help.

Read more
Creating a simple image gallery with PHP & jQuery illustration

An image gallery is a very common feature for a website to have. It is an efficient way to nicely present a set of pictures. With the increasing popularity of JavaScript plugin, image galleries are nowadays implemented with rich features, effects, and transitions, in order to emphasize the given content.

When you wish to create a picture gallery, there are several steps involved in the process. In this tutorial, we will see how you can set everything up, and then add, remove, or edit pictures in your gallery, in a simple and dynamic manner. Finally, we will explain how we can setup the jQuery lightbox plugin in order to work with our pictures.

What are the benefits of this solution? This methods is sooo easy to setup, but still achieves quite a lot. Little efforts, great rewards. You only have to put your images in a folder, and give that folder path to the class. You also tell the class how big you want your pictures to be, and it handles all the hard work for you. Just by calling a method, you can see your gallery on the page. So if you are looking for a fast and convenient way to put an image gallery on a site, read on.

Read more
How to create an Ajax, validated form illustration

Even on some very famous websites and blogs based on the WordPress platform, such as Smashing Magazine or Webdesigner Depot for example, the comment forms are not checked prior to submission. Which means that if the user hits the submit button without actually filling any information, he is redirected to the famous error: "Error: please fill the required fields (name, email).".

Thanks to jQuery and its plugins, it is possible to change the way those forms are handled, in order to obtain slick effects, and an overall better user experience.

In this tutorial, we'll associate the validation plugin, and the form plugin, to get a contact form that is validated before submission, and submitted via ajax. Why don't you give it a try?

Read more
@Bentoutif Il occupe tout le monde afin que pendant ce temps on parle moins des résultats moyens de l'OL. A la Mourinho. Et ça marche.20 Sep / 09:12