PHP Paypal API class

PHP Paypal API class

Released 6 years ago , Last update 8 months ago

The simplest way to handle online transactions using PayPal. Get started quickly with Express Checkout, Direct Payments, recurring payments, IPNs and more using this PHP PayPal API class.

An easy way to add advanced Paypal functionality into your site

This PHP PayPal class provides a very simple interface for integrating Paypal payments into a website, hiding away most of the complexity of the Paypal API. With a few lines of code, you can add advanced Paypal features to your site.

Multiple payment methods:

  • Allow offsite checkout on the PayPal website using Express Checkout.
  • Receive credit-card payments directly on your site using Direct Payments (requires a Website Payments Pro account)
  • Create and manage recurring payments using the Express Checkout flow or directly using credit-card details (Direct payments requires a Website Payments Pro account). Also supports subscription trial periods
  • Send payments to multiple recipients with reduced commissions using Mass Payments (Note: mass payments must be enabled manually by contacting PayPal, and requesting the Masspay API)
  • Receive payments status updates via Instant Payment Notifications (IPN)
  • Refund payments programmatically

Additional features:

  • Live and sandbox mode switching - test your PayPal integration before going live!
  • Normalization of Paypal parameters into a more readable format - reduce development time and work naturally with existing code.
  • Automatic calculations of transaction cost from individual items and additional costs such as shipping, handling, tax and insurance in the Express Checkout process - further streamlining checkout and payment confirmation.
  • Support for multiple items (for use with shopping carts) in addition to single item payments
  • Covered by PHPUnit and simpleTest unit-tests
  • Log PayPal requests and responses for auditing / debugging

Fraud detection

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.

  • Single site + Minfraud provides a single-site license for both components.
  • Developer + Minfraud provides a developer license for both components.

See the Minfraud product page for more details.


  • PHP 5+
  • cURL extension installed
  • A Paypal account (Website Payments Pro account is needed for Direct Payments with a credit-card)


Try out Express Checkout and Direct Payment on the live demo.

What our customers say:

"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,

In the media

As seen on Smashing Magazine: Getting Started with the Paypal API

  • 5 46
  • 4 13
  • 3 0
  • 2 0
  • 1 0
59 Reviews Read Reviews


14 day 14-day money-back guarantee


Single Site License

  • Perpetual license

  • 1 site, unlimited servers

  • No distribution (hosted use only)

  • Commercial use


Developer License

  • Perpetual license

  • Unlimited projects

  • Can distribute code and binary products

  • Commercial use

  • 12 months support


Developer + Minfraud

  • Perpetual license

  • Unlimited projects

  • Can distribute code and binary products

  • Commercial use

  • 12 months support


Package contents

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.

Configuring the Lionite_Paypal class

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 an API signature or certificate in your Paypal account, but going through the following steps:

  • In your Paypal account, visit the "Profile" link from the main navigation menu.
  • In the "Profile" page, pick the "My selling tools" link in the left-hand menu.
  • Click the "Update" link in the "API Access" line.
  • Pick option 2 - "Request API credentials"
  • Create API credentials with a signature (simpler), or alternatively create a certificate file.

Using a signature

If you created a signature in the previous step, 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' = '',
            'password' = 'QS3KG4HKZZ8LO1X8',
            'signature' = 'AwHw4G-7iVdHJ-5124kaDF1CaFqGAubxWbMMGTVn9T618xWex1U1DGj1',
            // Don't change below this line
        'sandbox' = array (
            'username' = '',
            'password' = 'FDXC0WSCOR8PS9K4',
            'signature' = 'TmgX50krWo1qxyLUzHW4vS4g1XvAAPUqUtaLk2Vh1irO8sH9wDLWOaDV',
            // Don't change below this line

Using a Paypal certificate

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:

  1. Download your certificate from Paypal
  2. Place it on a location on your server that PHP has the privileges to read from (if you don't know what that means, ask you system administrator)
  3. Change the contents of the $_PaypalCertificate class variable to the location of the certificate file (either relative or full path).
  4. Remove the 'signature' parameter from the $_settings array. Once you do, the class will try and find the certificate file instead.

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.

Live and Sandbox modes

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.


Express checkout

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:

  • Rather leave payment security to Paypal
  • Do not have access to Website Payments Pro - required for the Direct Payment method (available only in the US, Canada and the UK)
  • Believe users would be more inclined to pay using a trusted gateway (Paypal) than at your own site.

Express Checkout process:

1. Generate token and redirect to the Paypal payment page

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 = ''; //Confirmation URL
$cancelURL = ''; //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.

2. Get payment / payer information (optional)

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();

3. Confirm the transaction

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();

Direct Payment

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" = "",
    "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();

Mass payments

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 address
  • amount - 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' = '',
        'amount' = '49.99',
        'note' = 'Payment for services rendered'
    1 = array(
        'email' = '',
        '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

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 -

  1. Using the Express Checkout flow
  2. Directly, using credit-card details (Website Payments Pro accounts only)

Recurring payments with Express Checkout

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:

  • 'cost' - Recurring payment amount
  • 'start_date' - The start date of the recurring payment profile in UTC time. In PHP, you can use date('c',$time) to format a timestamp into UTC format.
  • 'period' - The billing period. Indicates how much time will pass between payments. Available options include: 'Day', 'Week', 'Month', 'SemiMonth', 'Year'. Semi-month indicates two payments a month, on the 1st and 15th of each month.
  • 'frequency' - How many billing periods fit in a billing cycle (up to 1 year). For months it can be 12 or less, for weeks it can be 52 or less and so forth. Payments will be charged every 1 billing cycle, so if we want to charge every 2 months our period should be 'Month' and our frequency should be 2
  • 'currency' - Currency of the payment. Important - currency used to create the recurring payment profile must be the same currency used to generate the express checkout token.

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.

Recurring payments with Direct Payment

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.


$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' = '',
    '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.

Trial periods

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(
    'trial_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.

Payment refund

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:

  • 'refund_type' - Indicates the type of refund. Available options include 'Full', 'Partial' (covered below), 'ExternalDispute' (according to the amount agreed via Paypal dispute system) and 'Other'.
  • 'amt' - Refund amount if 'Partial' is selected as type
  • 'currency' - Currency for partial refund amount
  • 'note' - A custom note for documentation purposes
  • 'source' - Source of funds for sending the refund.
    • 'any' - Use any available fund source
    • 'default' - Use default funding source, as defined in merchant configuration
    • 'instant' - Use merchant's balance as funding source
    • 'eCheck' - Use an eCheck to fund the refund amount. Uses Paypal balance if available

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 Notification(s) (IPN)

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 Checkout
  • directPayment() for Direct Payment

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

Testing IPN messages

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.

Logging Paypal transactions

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.


Made with love

"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

4 licenses, starting from From » $29.99 View Licenses

Get A Quote

What do you need?
  • Custom development
  • Integration
  • Customization / Reskinning
  • Consultation
When do you need it?
  • Soon
  • Next week
  • Next month
  • Anytime

Thanks for getting in touch!

Your quote details have been received and we'll get back to you soon.

Or enter your name and Email
  • AP Andrew Paget 2 months ago
    Is there a tutorial on how to set up IPN with recurring payments...can it be done...documentation not too clear on this?
    • Lionite Publisher 2 months ago
      Hi Andrew, it's covered in the documentation in the product description. It's just 2 lines of code - can you elaborate on what is not clear about it?
    • AP Andrew Paget 2 months ago
      Hi, I have managed to sort this and so the IPN is working but here's my question... Let say I have a web address that needs to be renewed every two years ( how do I indicate this to that when the script sends it to PayPal to create the profile it takes 1 payment every two years?
    • Lionite Publisher 2 months ago
      Hi Andrew - Are you a license holder? if so, please log-in to your account and open a ticket, and we can sort it there.
  • EO Enzo Orsi License holderSingle Site License
    Purchased on Feb 28, 2016
    4 months ago
    I am trying the demo, but it does not work... Before buying the plugin, I would be sure that is fitting with my requirements... Is it possible to have a trial version for a few days?
    • Lionite Publisher 4 months ago
      Hi Enzo, Thanks for letting us know about the demo. It has been fixed and you can try it again now. I'm afraid we don't have trial versions available.
    • EO Enzo Orsi 4 months ago
      Ok, thanks. Could you please confirm that is fully integrable with Joomla Chronoform component?
    • EO Enzo Orsi 4 months ago
      ..and it is still not working the button "Continue to Paypal" in the demo
  • D daniel License holderSingle Site License
    Purchased on Dec 29, 2015
    6 months ago
    Some questions about your support of recurring payments: 1.) Did you solve the issue of the API where recurring payments don't show a description of the price/items ? 2.) Do you support in-context payments for recurring? 3.) Can countries like Israel use in-context payments for recurring subscriptions?
    • Lionite Publisher 6 months ago
      Hi Daniel, 1. The recurring payment has a custom description in the checkout, as it always had. It doesn't show pricing. 2 + 3. "In-context payments" are not supported directly by this class. I have no idea if there's any country limitation for using it
    • D daniel 6 months ago
      Ok, thanks