This PHP PayPal class provides a very simple interface for integrating Paypal payments into a website:
The Minfraud bundle includes the Maxmind Minfraud API wrapper component that was built to support this component and detect fraud using the Maxmind Minfraud service.
See the component page for more details.
"I was really happy to find a class to communicate with what must be one of the worst APIs on the internet."
Jonas Van Schoote, madewithlove.be
As seen on Smashing Magazine: Getting Started with the Paypal API
The package contains the following structure:
/
|-- library
| |-- Lionite
| | `-- Paypal.php
| | |-- Cert
| | | `-- cacert.pem
|-- tests
| |-- simpletest
| | `-- PaypalTest.php
| |-- PHPUnit
| | `-- PaypalTest.php
|-- examples
| `-- example scripts
The /Lionite folder can be placed anywhere in your application. Include the Paypal.php file inside of it to get started.
In order to use the Lionite_Paypal class, you need a Paypal account (for live payments) and optionally a sandbox account (for testing). You can create API signatures in your Paypal account under Profile - API access. Then, change the values of the $_settings parameter in the Lionite_Paypal class with your account's API details.
/**
* Paypal API credentials
*
* - Configure those settings with your Paypal account and sandbox API signatures
* @var array
*/
protected $_settings = array (
'live' = array (
'username' = 'testuser.lionite.com',
'password' = 'QS3KG4HKZZ8LO1X8',
'signature' = 'AwHw4G-7iVdHJ-5124kaDF1CaFqGAubxWbMMGTVn9T618xWex1U1DGj1',
// Don't change below this line
),
'sandbox' = array (
'username' = 'test_1293871312.lionite.com',
'password' = 'FDXC0WSCOR8PS9K4',
'signature' = 'TmgX50krWo1qxyLUzHW4vS4g1XvAAPUqUtaLk2Vh1irO8sH9wDLWOaDV',
// Don't change below this line
)
);
Paypal provides the option to use a certificate file instead of a string signature, which some 3rd party eCommerce solutions support.
Paypal recommends using a signature, but if by some circumstances you are forced to use a certificate, this class supports it in the following manner:
Notice that are no separate variables for sandbox and live environment certificates. There should be no reason why you couldn't use the signature for the sandbox.
You can change the default operating mode of the Lionite_Paypal class from sandbox (testing) to live (production), by changing the value of the $_sandbox parameter in the class to true (sandbox) or false (production). If you want to dynamically decide which environment to use, you can call the static method sandbox() anywhere in your code (usually where you set your application configuration).
Lionite_Paypal::sandbox(true); //Activates sandbox mode for all instances of the Lionite_Paypal class
NOTE - In the express checkout example script (checkout.php), the sandbox mode is turned on using the static method. If you try to test your live credentials, you will have to comment that line out or changed the value passed to the method to false.
The express checkout payment method sends users to the Paypal site to pay, either using a Paypal account or a credit-card. After paying, the user is returned to your site to complete the transaction. You should use the Express Checkout method if you:
Express Checkout process:
To generate the redirect URL to Paypal, we'll use the getCheckoutUrl() method.
public function getCheckoutUrl( $options = array(), $items = array() )
We pass configuration options through the $options parameters. We need to provide two endpoint URLs to generate the token -
return - The confirmation URL which points at the confirmation script, where the user would be redirected if he complete the payment on Paypal.
cancel - The cancellation URL, where the user would be redirected if he declines to pay on Paypal. It can be any page on your site.
For a complete list of possible options and their default value, see the $_paymentOptions array in the class - it's fully documented.
We can provide provide the contents of the payment either as a single payment item or as an array of items (common if we use a shopping cart). A payment item is of the following form:
$item = array(
'cost' = 35, //Item cost in the selected currency, default is USD
'amount' = 2, //Amount of items of this type, default is 1
'name' = 'D80 Nikon Camera' //Item name
);
To see the complete list of optional item parameters (such as shipping, description, weight), please take a look at the $_itemParams parameter in the Lionite_Paypal class.
A complete example, taken from the demo site:
$items = array(...); //Array of shopping cart items or a single item
$returnURL = 'http://demo.lionite.com/paypal/confirm'; //Confirmation URL
$cancelURL = 'http://demo.lionite.com/paypal/checkout'; //Cancellation URL
$paypal = new Lionite_Paypal();
$options = array(
'return' = $returnURL,
'cancel' = $cancelURL
);
//Generate the redirect URL
$redirect = $paypal -> getCheckoutUrl($options, $items);
if($redirect !== false) {
header("Location: " . $redirect);
}
After generating the checkout URL, we redirect the browser to it using the header() PHP function.
After the user completes the payment on the Paypal site, he is redirected to the confirmation URL we specified when generating the checkout token (step 1). Before we confirm the payment and complete the transaction, we can get additional information on the payment / payer. Such information includes name, Email, full address and the complete payment details we supplied in step 1.
$paypal = new Lionite_Paypal();
$details = $paypal -> getCheckoutDetails();
In order to complete the transaction at the confirmation URL, we need to send a request back to Paypal. If we previously called getCheckoutDetails() we do not need to supply any parameters:
$result = $paypal -> confirmCheckoutPayment();
Otherwise, we need to provide the total payment charge to Paypal:
$result = $paypal -> confirmCheckoutPayment(array('cost' = 35));
The $result parameter will contain a Paypal transaction ID if the payment was successful, or a boolean false indicating payment failure. In the case of payment failure you can get an errors array by calling getErrors()
$errors = $paypal -> getErrors();
var_dump($errors);
Use the direct payment method when you want to accept credit-card payments directly on your site. You need a Website Payments Pro account (available only in the U.S, Canada and the UK) to use this method.
You can use the form in the Direct Payment example script (direct.php) as a reference for the parameters you need to send to complete a credit-card transaction. The full list is as follows:
//Example direct payment parameters received from a POST form
$data = array(
"card_type" = "Visa",
"card_holder" = "John Doe",
"card_number" = "4580035948599459",
"expiry_month" ="05",
"expiry_year" = "2014",
"cvv" = "545",
"first_name" = "John",
"last_name" = "Doe",
"email" = "johndoe@lionite.com",
"country" = "US",
"city" = "New York",
"state" = "NY",
"street" = "345 Argyle Rd.",
"street2" = "",
"zipcode" = "10010",
"phone" = "202-349-4567"
);
To process a Direct Payment transaction, we use the directPayment() method. We pass the credit-card form data, along with an array of item(s) as explained in the Express Checkout method:
$paypal = new Lionite_Paypal();
$result = $paypal -> directPayment($data,$items);
The $result parameter contains either a Paypal transaction ID (string) or a boolean false indicating payment failure. In the case of payment failure you can get an errors array by calling getErrors()
$errors = $paypal -> getErrors();
var_dump($errors);
Note: To be able to use the Masspay API, your account needs to be white-listed by Paypal. Please contact Paypal first to ensure your account is eligible.
The masspay API method allows you to send payments to multiple addresses with one API call, usually using a reduced transaction commission compared to individual payments.
To use the masspay() method, pass an array of payments with each payment containing the following fields:
email - Payee PayPal addressamount - Amount to be paid (in the transaction currency)note - Payment description (optional)You can pass the subject of the payment notification Email as the second parameter of the method (pass null for the PayPal default), and the currency of the amounts (default is USD).
Example usage:
$payments = array(
0 = array(
'email' = 'johndoe@gmail.com',
'amount' = '49.99',
'note' = 'Payment for services rendered'
),
1 = array(
'email' = 'janedoe@yahoo.com',
'amount' = '35.99',
'note' = 'Website design payment'
)
);
$paypal = new Lionite_Paypal();
$result = $paypal -> masspay($payments,'Lionite payment sent');
// $result contains the mass payment correlation number on success or false on failure
Recurring payments allow you to receive subscription and other payments that are not one-time payments. You can define payment period, frequency and overall number of payments amongst other things.
Recurring payments are handled in Paypal via recurring payment profiles. A recurring payment profile contains the details of the recurring payment - such as billing period, frequency, amount, billing date and more. There are two ways to create a recurring payment profile -
Setting up a recurring payment with Express Checkout is almost identical to the process outlined above under Express Checkout. We obtain an express checkout token, use it to redirect to Paypal and then confirm the transaction on a confirmation page.
Setting up the Express Checkout token
This step is shown in the example scripts under recurring-payments/create-expressCheckout.php
A subscription item simply included the subscription description. You can also pass payment specifics, such as length and amount - this will be shown to the user before he accepts the subscription.
$item = array(
'subscription_description' = 'Time magazine monthly subscription for 1 year'
);
Apart from this parameter, the process is exactly the same as the beginning of the Express Checkout process explained above. You pass the item along with other payment options to getCheckoutUrl() and redirect to Paypal if successful.
Creating a recurring payment profile
This step is shown in the example scripts under recurring-payments/confirm-expressCheckout.php
After the user confirms the payment and is redirected back to the confirmation script you passed when generating the Express Checkout token, we can create a recurring payment profile. This is done using createRecurringProfile() as shown in the example script. The parameters this method accepts are documented in detail in the Lionite_Paypal class. The important parameters are:
date('c',$time) to format a timestamp into UTC format.We also need to pass the original item details again to the profile creation method. Full example:
$date = date('c',time() + 7 * 24 * 3600);
$profile = array(
'cost' = '29.99',
'period' = 'Month',
'frequency' = 1, // Bill every 1 month
'total_cycles' = 12, // End after 12 cycles (1 year). Use 0 for unlimited
'desc' = 'Time magazine monthly subscription for 1 year', // Must be the same as we defined at the start of the Express Checkout process
'start_date' = $date, // Profile start date
'currency' = 'GBP' // Payment currency
);
$profileId = $paypal -> createRecurringProfile($profile);
See the included example scripts for a more detailed walkthrough.
Updating a recurring payment profile
As shown in the example scripts under recurring-payments/update.php
You can update some parameters of an existing recurring payment profile by passing new parameters and the profile ID.
For example, updating the cost of subscription payment:
$paypal = new Lionite_Paypal();
$updateData = array(
'cost' = '31.99',
'currency' = 'GBP'
);
$result = $paypal -> updateRecurringProfile($profileId,$updateData);
For more information on what fields can be updated, see the official API documentation.
Website Payments Pro account holders can create recurring payment profiles directly using credit-card details. The credit-card details are the same as outlined in the direct payment operation, and the recurring payment profile details are the same as shown in the Express Checkout method above.
Example:
$date = date('c',time() + 7 * 24 * 3600);
$profile = array(
'cost' = '29.99',
'period' = 'Month',
'frequency' = 12,
'desc' = 'Time magazine monthly subscription for 1 year',
'start_date' = $date,
'currency' = 'GBP',
// Credit card and payer details
'name' = 'Test User',
'email' = 'test@test.com',
'card_number' = '4929802607281663',
'card_type' = 'Visa',
'cvv' = '545',
'expiry_date' = '052015',
'zipcode' = '10010',
'city' = 'New York',
'country' = 'US',
'state' = 'NY',
'street' = '14 Argyle Rd.'
);
$profileId = $paypal -> createRecurringProfile($profile);
A more detailed example is included in the example scripts.
You can define a trial period while setting up a recurring payment profile. The parameters are the same, but prefixed with trial_. The regular payment period will commence once the trial period has expired. Example:
$profile = array(
'trail_period' = 'Month',
'trial_frequency' = 12,
'trial_total_cycles' = 1, // 1 Month trial period
'trial_cost' = 0, // Trial period cost, needs to be specified separately from regular cost
'cost' = '29.99',
'period' = 'Month',
'frequency' = 12,
'desc' = 'Time magazine monthly subscription for 1 year',
'start_date' = $date, // Profile start date
'currency' = 'GBP' // Payment currency
);
$profileId = $paypal -> createRecurringProfile($profile);
We set the total billing cycles to 1, which means the trial period will stop after 1 month. If not canceled, regular payments will begin at that time.
You can programmatically refund payments using each payment transaction ID. By default, the full amount is refunded, however you have more fine-grained control over the exact refund details using method parameters:
The operation will return the refund transaction ID or false on failure. Code example:
// Transaction identifier
$transactionId = '5VY631383V0066111';
// Optional parameters, see method comments in class for details
$options = array(
'refund_type' = 'Full'
);
$result = $paypal -> refund($transactionId,$options);
Instant Payment Notifications are Paypal initiated requests that are used to notify your system of changes to Paypal transactions. It can be used to confirm Express Checkout payments (replacing the return URL confirmation) and confirm / cancel subscription payments.
To activate IPN messages, you need to turn on IPN messages in your Paypal profile. You can set the IPN URL directly in your account settings, or pass it as the 'ipn_url' parameter the $options array to the various confirmation methods
confirmCheckoutPayment() for Express CheckoutdirectPayment() for Direct PaymentIn order to receive IPN messages, you need to set up an endpoint URL on your website. On that endpoint, invoke the Lionite_Paypal class and send the IPN data into the confirmIpn() method:
$paypal = new Lionite_Paypal();
$result = $paypal -> confirmIpn($_POST);
The $result parameter contains Paypal transaction ID(s) if the IPN confirmation was successful and false on failure. If the IPN request was for a mass payment, the result will include multiple transaction IDs in an array.
$_POST is the POST data sent from Paypal, as is.
You can determine the transaction type via a parameter named 'txn_type' included in the POST request from Paypal.
'web_accept' - Payment received for 'Buy now' and 'donation' buttons
'express_checkout' - Express checkout payment received
'subscr_signup' - Subscription sign-up confirmation
'subscr_cancel' - Subscription cancellation
'subscr_modify' - Modification to an existing subscription
'subscr_failed' - Subscription sign-up failure
'subscr_payment' - Subscription periodical payment
'subscr_eot' - Subscription end-of-term
'masspay' - Mass payment confirmation
See the Paypal manual for more transaction types.
You can test your IPN receiver script using the IPN Simulator under Test Tools in your sandbox account. Since you cannot observe the request (it is sent from Paypal), you can save it to a file or send it to your Email account for verifying and debugging your script.
You can turn on logging for the class that will log any request made to the PayPal API along with the returned response. Use the log() method to turn on logging, by passing a boolean true or a path to the log files (default is the same folder as the Paypal.php file).
$paypal = new Lionite_Paypal();
$paypal -> log(); // Turn on logging
Log files will appear in the log path for every Paypal API request.

"I was really happy to find a class to communicate with what must be one of the worst APIs on the internet."
> Jonas Van Schoote madewithlove.be
Fantastic! Massive time saver.
It's pitty that from the rating questions is missing rating for Support. Is really fast (very fast) and friendly. Other than this, even if the script has dozens of features, is very easy to integrate it. There are so many examples in the distribution file that makes impossible to find something that is not covered.
Without this class I would've spent ages integrating PayPal to our app, but thanks to this class it was a piece of cake!
Questions & Comments