PHP Paypal API class

PHP Paypal API class

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.

  • Language: PHP
  • Released: Sep 27, 2010
    Last Update: Jun 21, 2014

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

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 component page for more details.

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 Magazine: Getting Started with the Paypal API

Hide

Installation

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

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.

Hide

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 -

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.

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

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.

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

Hide

Testimonials

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 madewithlove.be

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

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

X

Save your watchlist

Fill your details below to receive project updates from your watch list - including new versions, price changes and discounts.

I agree to the terms of use and privacy policy.

4 licenses, starting from From » $29.99 14 day money-back guarantee View Licenses
or Get a quote

for customization or integration services

  • This class definitely makes the PayPal API a bit more approachable. It saved me a lot of time while we added PayPal as a checkout option to our store. The seller's customer support is excellent. This class is well worth the price tag.
    CH Chad Hutchins
    9 months ago, 0 comments
    Was this helpful?
    Flag 1 of 1 people found this review helpful
  • Great class. Saved HOURS of coding, trial, error, and hair pulling. I built something like this in 2001 and it took 2 weeks of hard coding while trying to reverse engineer PayPal's system. Simple to install, simple to configure.
    KF Kay Fielder
    1 year ago, 0 comments
    Was this helpful?
    Flag 1 of 1 people found this review helpful
  • Great component I am using in project for quick and easy PayPal implementation.
    JK Jiri Kral
    1 year ago, 0 comments
    Was this helpful?
    Flag 1 of 1 people found this review helpful
Post a comment

Or enter your name and Email
  • JT John T.Emmatty 2 weeks ago
    We are contemplating on using your services on the web app we are developing, We have following requirements, could you please go through this list of requirements and confirm that your wrapper class' is handling it? Our's is a multisided services platform, an employer assigns a freelancer to do some job. Freelancer will create partial invoices until the full value of the job is realized. We sit as a middle man, and does the job of forwarding the invoice to employer and transfer the amount collected from the employer to the corresponding freelancer, after taking a cut. 1) We need to provide seamless integration on invoicing, The freelancer will use our web interface to create/send invoice. We will record the cost of the invoice in our database. 2) It is the employers prerogative, to decide when to respond on the invoice. Say, he responded after 10 days of receipt of the invoice. When the payment is made our website traps it and records it in the database. 3) When our web app come to know that a payment is made by the employer, we will transfer the amount (after taking a cut) to the freelancer.(adaptive payments) Can you please advice us on which of your offerings is suitable to the above said scenario? We are currently on shared hosting. Is there anything special configuration required on the server to get your API working?
    • Lionite Developer 1 week ago
      Hi John, This class does not support adaptive payments. It supports the Express Checkout and Direct Payment APIs, as well as Masspay and recurring payments. All that is contained is detailed on the project page description. To use the class you need the cURL extension enabled.
  • MK Meggan King 4 weeks ago
    We are considering buying the Paypal API class, but I have a question. We would like to do Recurring Billing using Express Checkout. What type of Paypal account is required for that? Thank you.
    • Lionite Developer 4 weeks ago
      A standard Paypal seller account should suffice for the Express Checkout API. If you want to take credit-cards directly on your own site, you will need a Pro account.
  • RB Randy Bailey License holderSingle Site License 4 weeks ago
    What is returned if buyer selects echeck?
    • Lionite Developer 4 weeks ago
      The payment status returned will be "Pending" and the transaction could not be completed immediately. When allowing non immediate transactions, you should implement the IPN callback to allow completion at a later date. I usually disable non-immediate payment options including echeck and bank transfer as it complicates processing and is often used by fraudsters.
    • RB Randy Bailey License holderSingle Site License 3 weeks ago
      Something like ...?status=Pending... - Thanks!