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.

 

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 = “”) {
  5. //default settings
  6. $settings = array(
  7. ‘business’ => ‘jeremy@jdmweb.com’, //paypal email address
  8. ‘currency’ => ‘GBP’, //paypal currency
  9. ‘cursymbol’ => ‘&pound;’, //currency symbol
  10. ‘location’ => ‘GB’, //location code (ex GB)
  11. ‘returnurl’ => ‘http://mysite/myreturnpage&#8217;, //where to go back when the transaction is done.
  12. ‘returntxt’ => ‘Return to My Site’, //What is written on the return button in paypal
  13. ‘cancelurl’ => ‘http://mysite/mycancelpage&#8217;, //Where to go if the user cancels.
  14. ‘shipping’ => 0, //Shipping Cost
  15. ‘custom’ => ” //Custom attribute
  16. );
  17. //overrride default settings
  18. if (!empty($config)) {
  19. foreach ($config as $key => $val) {
  20. if (!empty($val)) {
  21. $settings[$key] = $val;
  22. }
  23. }
  24. }
  25. //Set the class attributes
  26. $this->business = $settings[‘business’];
  27. $this->currency = $settings[‘currency’];
  28. $this->cursymbol = $settings[‘cursymbol’];
  29. $this->location = $settings[‘location’];
  30. $this->returnurl = $settings[‘returnurl’];
  31. $this->returntxt = $settings[‘returntxt’];
  32. $this->cancelurl = $settings[‘cancelurl’];
  33. $this->shipping = $settings[‘shipping’];
  34. $this->custom = $settings[‘custom’];
  35. $this->items = array();
  36. }

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. }
  11. //=====================================//
  12. //==> Add a simple item to the cart <==//
  13. //=====================================//
  14. public function addSimpleItem($item) {
  15. if (//Check the quantity and the name
  16. !empty($item[‘quantity’])
  17. && is_numeric($item[‘quantity’])
  18. && $item[‘quantity’] > 0
  19. && !empty($item[‘name’])
  20. ) { //And add the item to the cart if it is correct
  21. $items = $this->items;
  22. $items[] = $item;
  23. $this->items = $items;
  24. }
  25. }

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 = “https://www.paypal.com/cgi-bin/webscr&#8221; 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”>
  8. <input name = “business” value = “jeremy@jdmweb.com” type = “hidden”>
  9. <input name = “handling_cart” value = “0” type = “hidden”>
  10. <input name = “currency_code” value = “GBP” type = “hidden”>
  11. <input name = “lc” value = “GB” type = “hidden”>
  12. <input name = “return” value = “http://mysite/myreturnpage&#8221; type = “hidden”>
  13. <input name = “cbt” value = “Return to My Site” type = “hidden”>
  14. <input name = “cancel_return” value = “http://mysite/mycancelpage&#8221; type = “hidden”>
  15. <input name = “custom” value = “” type = “hidden”>
  16. <div id = “item_1” class = “itemwrap”>
  17. <input name = “item_name_1” value = “Gold Tickets” type = “hidden”>
  18. <input name = “quantity_1” value = “4” type = “hidden”>
  19. <input name = “amount_1” value = “30” type = “hidden”>
  20. <input name = “shipping_1” value = “0” type = “hidden”>
  21. </div>
  22. <div id = “item_2” class = “itemwrap”>
  23. <input name = “item_name_2” value = “Silver Tickets” type = “hidden”>
  24. <input name = “quantity_2” value = “2” type = “hidden”>
  25. <input name = “amount_2” value = “20” type = “hidden”>
  26. <input name = “shipping_2” value = “0” type = “hidden”>
  27. </div>
  28. <div id = “item_3” class = “itemwrap”>
  29. <input name = “item_name_3” value = “Bronze Tickets” type = “hidden”>
  30. <input name = “quantity_3” value = “2” type = “hidden”>
  31. <input name = “amount_3” value = “15” type = “hidden”>
  32. <input name = “shipping_3” value = “0” type = “hidden”>
  33. </div>
  34. <input id = “ppcheckoutbtn” value = “Checkout” class = “button” type = “submit”>
  35. </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 rzrasel@yahoo.com. 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.

Conclusion

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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s