Personal License $29.99

1 site, unlimited servers No source distribution Commercial use allowed Can modify source Read full license

Developer License $149.99

Unlimited projects Source and binary distribution Commercial use allowed Distribute modifications 1 year support Read full license

You need to log-in or create an account
  • Create an account
  • Log-in
  • Please use your real name.
  • Account activation link will be sent to this address.
  • Minimum 8 characters

Clicking this button confirms you read and agreed to the terms of use and privacy policy.

Starting from $ 29.99

View Pricing 14 days money-back guarantee
(28 ratings)

PHP Paypal API class

  • Developed by Lionite, Released May 9, 2012

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.

Description

This PHP PayPal class provides a very simple interface for integrating Paypal payments into a website:

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: as of August 11th, mass payments are disabled by default and must be enabled manually by contacting PayPal)
  • 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

Requirements:

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

People who used this class 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, madewithlove.be

In the media

As seen on Smashing Magainze

Back to top

Installation

Package contents

The package contains the following structure:

/
 |-- library
 |   |-- Lionite
 |   |   `-- Paypal.php
 |   |   |-- Paypal
 |   |   |   `-- 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 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',
            'endpoint' => 'https://api-3t.paypal.com/nvp',
            'redirect' => 'https://www.paypal.com/webscr'
        ),
        'sandbox' => array (
            'username' => 'test_1293871312_biz_api1.lionite.com',
            'password' => 'U8XD0WSCOR8PS9K4',
            'signature' => 'TmgX50krWo1qxyLUzHW4vS4g1XvAAPUqUtaLk2Vh1irO8sH9wDLWOaDV',
            'endpoint' => 'https://api-3t.sandbox.paypal.com/nvp',
            'redirect' => 'https://www.sandbox.paypal.com/webscr'
        )
    );

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.

Back to top

Documentation

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 -

Confirmation URL - where the user would be redirected if he complete the payment on Paypal.

Cancellation URL - where the user would be redirected if he declines to pay on Paypal.

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.

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();
var_dump($errors);

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

Mass payments

Note: as of August 11th, mass payments are disabled by default and must be enabled manually by contacting PayPal. I have no relation to Paypal, so please make sure you can activate it for your account before purchasing this class for this purpose.

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' => '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

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.

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.

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.

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

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. In order to receive IPN messages, you need to set up an endpoint URL on your website. The URL should transfer the IPN request data to the Lionite_Paypal class for processing.

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

Back to top

Testimonials

"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

Read all 124 comments »

Questions & Comments

  • Denis Yuzvyk License holder said:

    2 days ago
    Hello, i'm trying to create monthly recurring profile.
    To make first charging - I specify "init_amount" at createRecurringProfile option.

    createRecurringProfile retruns only profile id.
    How to get transaction ID of "first charging" with amount specified at "init_amount" field.
    • Lionite Author said:

      2 days ago
      Hi Denis,

      That's a very good question. Unfortunately, Paypal does not provide the transaction ID for the initial charge through the profile creation API. The only way I can think of to capture that transaction ID programatically is through the IPN that is sent when the payment clears.
    • Denis Yuzvyk License holder said:

      2 days ago
      Thank you for your reply.
      I need show login details at confirmation(confirm-expressCheckout.php) page instantly.

      How about such workaround?
      1. remove "init_amount" field from createRecurringProfile option
      2. create profile with starting date NOW() + 30 days
      3. after createRecurringProfile , call confirmCheckoutPayment and get transaction ID.
      4. Extend account with IPN call from createRecurringProfile after 30days
    • Lionite Author said:

      2 days ago
      I would suggest doing almost what you wrote - but instead of extending the account after 30 days, just allow it now if the checkout completes successfully. If the subscription is cancelled or the payment doesn't go through, you will receive an IPN regarding that - you can cancel the account at that time.
  • Erik Olsen License holder said:

    1 month ago
    Hi Lionite,

    I'm using your example product.php to checkout a single product with lots of either-or options through Checkout Express (see http://wedriveleads.net/_new/). However, now I want to add options that may have 3 or 4 selections. Can you guide me through the best way of starting to do that?
    • Lionite Author said:

      1 month ago
      Hi Erik,

      I can't really understand what you want to do from your description. Are you having a problem with the class? if so, please use the issue tracker and not the comment section.
    • Erik Olsen License holder said:

      1 month ago
      I'm not necessarily having a problem with the script. I'm hoping you can guide me in the right direction to changing the way products.php works.

      I'm selling a product that has a base price of say $2000. Then, the customer can choose from a few different select boxes to "upgrade" different options. So each upgrade is an entry in the array in products.php. This works like a charm. The "standard" option in the select has a value of 0 and the "upgraded" option has a value of 1.

      What I'm having trouble with is figuring out how I would go about adding three options to the select box. So option one is "standard (+$0.00), option two is "upgrade 1 (+$100.00), and option three is "upgrade (+$250.00). I just don't know how I would go about doing this and editing products.php and checkout.php to make that happen.

      I realize this is out of the scope of your script, but I'll take any advice you can give. If you want to look at the example, I have it uploaded at http://wedriveleads.net/_new/turbokit.php. I'm trying to make the injectors upgrade function.

      Thanks,
      -Erik
    • Lionite Author said:

      1 month ago
      Hi Erik,

      This is indeed outside the scope of the script and it would be hard for me to give you good advice based on limited information on the code structure of your site. The products.php is included for example purposes only - you are not supposed to use it in your own application, but instead fetch your product data from whatever format it is stored in (static, database or otherwise) and pass it to the Paypal API class. I demonstrate the most basic usage in the example given.

      You need to use the information passed by the user through your form along with your product data to build up the items array as shown in the example. I'm sorry I couldn't be of more help.
  • Andrew Thong License holder said:

    1 month ago
    Is there a way to cancel subscriptions from my site instead of having the subscriber go to their PayPal account to do it?
    • Lionite Author said:

      1 month ago
      You can use the changeRecurringProfileStatus() method to change a recurring profile status to 'Suspend' or 'Cancel' (the first is reversible, the other is permanent). Example usage of this method is shown in 'examples/recurring-payments/status-change.php'

Leave a comment

You must be logged-in to leave a comment.
Log-in now or register for a free account.
You must be logged-in to vote. Log-in to your account or register now.
View all 24 reviews »

User Reviews

    Excellent API Class
    - Chris Goodwin, 4 days ago
    Flag review
    Was this helpful? Yes No
    Very helpful php class. Saves me a lot of time. Thanks to developer.
    - Stanyslav Davydoglov, 1 week ago
    Flag review
    Was this helpful? Yes No
    Seems to be fairly well written and well thought out. There are comments throughout the code.

    It helped for what I needed and saved a few hours of coding. If there's no issues on the production-server, then it was totally worth it. Hopefully there's no funky bugs - fingers-crossed.
    - Lawrence Mak, 1 week ago
    Flag review
    Was this helpful? Yes No

Starting from $ 29.99

View Pricing 14 days money-back guarantee