Blog : How to easily integrate a PayPal Checkout with PHP

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.
•   Download
 
•   Demonstration
 
•   Share on Twitter
 
•   Share on Google
 
•   Share on Facebook
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 easilyregister 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.   
6.    //default settings
7.    $settings = array(
8.    'business' => 'jeremy@jdmweb.com', //paypal email address
9.    'currency' => 'GBP', //paypal currency
10.    'cursymbol' => '£', //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.    );
18.   
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.    }
27.   
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 htmlcurrency 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.   //=====================================//
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['quantity'])
18.    && is_numeric($item['quantity'])
19.    && $item['quantity'] > 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.   

    2.   
  • 4 x "Gold Tickets" at £30 for £120

  • 3.   
  • 2 x "Silver Tickets" at £20 for £40

  • 4.   
  • 2 x "Bronze Tickets" at £15 for £30

  • 5.   
  • Total: 8 Items for £190

  • 6.   

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: 
 
 
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:  As you can see, PayPal understood our request. It shows here that the account that will receive the funds is as specified jeremy@jdmweb.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.