How to do PayPal Integration in PHP? (Step by Step Tutorial)

paypal integration in php

This is a tutorial for PayPal integration in PHP.

If you are using a PHP based eCommerce platform, then you can follow this tutorial to implement PayPal payment on your store.

What is PayPal?

PayPal is a popular payment gateway that offers secure and easy to use payment processing globally. 

A customer can add his bank account, debit card, or credit card and start with PayPal. Currently, 286 Million users are using it, and nearly 87.5% of online buyers make the payment with PayPal.

So having PayPal on your site is one of the suggestion we give to our clients..

Best features that PayPal offers include: 

  • Credit Cards, Debit Cards
  • Create an online invoice
  • Buyer and seller accounts
  • Cart
  • Mobile Application
  • International money transfer

How PayPal Works?

Using PayPal for transactions and online shopping is secure. If the user already has an account on PayPal, then he can quickly checkout.

He has to login to the account and then confirm the amount. After selecting the bank/card, the payment will be made in one click.

Paypal Blog Image 1 PayPal Integration in PHP

It is easy for the customer.

The merchant has to set up PayPal in the store. And if it is a software product, and requires recurring payments, you have to do the PayPal integration in PHP.

In this tutorial, I will tell you how to do PayPal Integration in PHP, and in the end, you will be able to integrate PayPal into your store.

Basic Terms

Here are a few basic terms you need to know before you read the tutorial.

Instant Notification Process: Instant Payment Notification (IPN) is a notification service that automatically sends the notification of any event related to PayPal transactions to merchants. eCommerce store owners can use it in many ways, such as fulfilling orders automatically and providing customers with order status.

Payment Form: A form on your site will send the values such as customer name/email address to PayPal.

payment.php page: The payment.php page on your website is that page that will handle all the outgoing requests to the PayPal, and the incoming request coming from PayPal.

PayPal Integration in PHP Step by Step

STEP 1 – Setup PayPal Account

The first step is to sign up for a PayPal account. Go to PayPal and click on SignUp.

paypal byusiness account 1 PayPal Integration in PHP

You must open the business account to be able to access IPN. After setting up the PayPal account properly, you would be able to access IPN.

Go to “edit profile” option of your PayPal account and look for the following settings:

Navigate to the “My Selling Preferences” and find the Getting Paid and Managing Risk.

  • Open the Instant payment Notification Process
  • Turn ON the IPN Value
  • Change the URL of IPN to the PHP page containing the IPN code (http://www.example.com/payment.php)

Navigate to the “My Selling Preferences” and find the Getting Paid and Managing Risk.

  • Open the Block Payments
  • Turn off the payment from the users who pay with eCheque by blocking it

Navigate to the ‘account information’ and find ’email’

  • Enter your primary email address. This email will be visible to users, so keep it professional.

STEP 2 – Creating HTML Form

You need to set a form on your site to send the basic information about the payee to PayPal.

You can use this HTML code to create the HTML form.


<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Paypal Integration Test</title>
</head>
<body>

    <form class="paypal" action="payments.php" method="post" id="paypal_form">
        <input type="hidden" name="cmd" value="_xclick" />
        <input type="hidden" name="no_note" value="1" />
        <input type="hidden" name="lc" value="UK" />
        <input type="hidden" name="bn" value="PP-BuyNowBF:btn_buynow_LG.gif:NonHostedGuest" />
        <input type="hidden" name="first_name" value="Customer's First Name" />
        <input type="hidden" name="last_name" value="Customer's Last Name" />
        <input type="hidden" name="payer_email" value="customer@example.com" />
        <input type="hidden" name="item_number" value="123456" / >
        <input type="submit" name="submit" value="Submit Payment"/>
    </form>

</body>
</html>

More sensitive information like price, business name, etc., will be sent in the next step.

STEP 3 – Sending Request

As I mentioned, the payment.php page will handle the outgoing request to the PayPal, and the incoming response after the processing for the Payment.

However, you have to build up the parameters and pass them through PayPal via query strings before sending them.

  • Values that need to be sent:
  • business: email address of your PayPal account
  • Item_name: name of the item
  • Amount: the price of the product
  • Return: return address after payment success
  • Cancel_return: if payment is canceled, the return address
  • Notify_url: payment.php page URL on your site
  • Custom: any other data you want to send via PayPal request
 // For test payments we want to enable the sandbox mode. If you want to put live
// payments through then this setting needs changing to `false`.
$enableSandbox = true;

// Database settings. Change these for your database configuration.
$dbConfig = [
    'host' => 'localhost',
    'username' => 'user',
    'password' => 'secret',
    'name' => 'example_database'
];

// PayPal settings. Change these to your account details and the relevant URLs
// for your site.
$paypalConfig = [
    'email' => 'user@example.com',
    'return_url' => 'http://example.com/payment-successful.html',
    'cancel_url' => 'http://example.com/payment-cancelled.html',
    'notify_url' => 'http://example.com/payments.php'
];

$paypalUrl = $enableSandbox ? 'https://www.sandbox.paypal.com/cgi-bin/webscr' : 'https://www.paypal.com/cgi-bin/webscr';

// Product being purchased.
$itemName = 'Test Item';
$itemAmount = 5.00;

// Include Functions
require 'functions.php';

// Check if paypal request or response
if (!isset($_POST["txn_id"]) && !isset($_POST["txn_type"])) {

    // Grab the post data so that we can set up the query string for PayPal.
    // Ideally we'd use a whitelist here to check nothing is being injected into
    // our post data.
    $data = [];
    foreach ($_POST as $key => $value) {
        $data[$key] = stripslashes($value);
    }

    // Set the PayPal account.
    $data['business'] = $paypalConfig['email'];

    // Set the PayPal return addresses.
    $data['return'] = stripslashes($paypalConfig['return_url']);
    $data['cancel_return'] = stripslashes($paypalConfig['cancel_url']);
    $data['notify_url'] = stripslashes($paypalConfig['notify_url']);

    // Set the details about the product being purchased, including the amount
    // and currency so that these aren't overridden by the form data.
    $data['item_name'] = $itemName;
    $data['amount'] = $itemAmount;
    $data['currency_code'] = 'GBP';

    // Add any custom fields for the query string.
    //$data['custom'] = USERID;

    // Build the query string from the data.
    $queryString = http_build_query($data);

    // Redirect to paypal IPN
    header('location:' . $paypalUrl . '?' . $queryString);
    exit();

} else {
    // Handle the PayPal response.
}

STEP 4 – Incoming Response

Now the PayPal will send the response, and the payment.php page we made will read the response. 

We have to add this code to the else statement of our payment.php script. It will check out if we have already processed this transaction before adding the payment to the database.


// Handle the PayPal response.

// Create a connection to the database.
$db = new mysqli($dbConfig['host'], $dbConfig['username'], $dbConfig['password'], $dbConfig['name']);

// Assign posted variables to local data array.
$data = [
    'item_name' => $_POST['item_name'],
    'item_number' => $_POST['item_number'],
    'payment_status' => $_POST['payment_status'],
    'payment_amount' => $_POST['mc_gross'],
    'payment_currency' => $_POST['mc_currency'],
    'txn_id' => $_POST['txn_id'],
    'receiver_email' => $_POST['receiver_email'],
    'payer_email' => $_POST['payer_email'],
    'custom' => $_POST['custom'],
];

// We need to verify the transaction comes from PayPal and check we've not
// already processed the transaction before adding the payment to our
// database.
if (verifyTransaction($_POST) && checkTxnid($data['txn_id'])) {
    if (addPayment($data) !== false) {
        // Payment successfully added.
    }
}

verifyTransaction function will verify the authenticity of the response. After calling it, the function will take the data received from the PayPal, and will validate it by making the curl request to PayPal with the transaction data received. 

If the response is the same, we will get the VERIFIED message, and we will know that everything is OK. Then the payment will be added to the database.

The verifyTansaction function:


function verifyTransaction($data) {
    global $paypalUrl;

    $req = 'cmd=_notify-validate';
    foreach ($data as $key => $value) {
        $value = urlencode(stripslashes($value));
        $value = preg_replace('/(.*[^%^0^D])(%0A)(.*)/i', '${1}%0D%0A${3}', $value); // IPN fix
        $req .= "&$key=$value";
    }

    $ch = curl_init($paypalUrl);
    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
    curl_setopt($ch, CURLOPT_SSLVERSION, 6);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
    curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));
    $res = curl_exec($ch);

    if (!$res) {
        $errno = curl_errno($ch);
        $errstr = curl_error($ch);
        curl_close($ch);
        throw new Exception("cURL error: [$errno] $errstr");
    }

    $info = curl_getinfo($ch);

    // Check the http response
    $httpCode = $info['http_code'];
    if ($httpCode != 200) {
        throw new Exception("PayPal responded with http code $httpCode");
    }
    curl_close($ch);

    return $res === 'VERIFIED';
}

We can also call to checkTxnid. The function’s purpose is simple; it checks if the txn_id value from PayPal already exists in our database.

After verifying the payment, it is a good idea to call this function and check if you have already added the transaction to the database.

Txn_id function:


function checkTxnid($txnid) {
    global $db;

    $txnid = $db->real_escape_string($txnid);
    $results = $db->query('SELECT * FROM `payments` WHERE txnid = \'' . $txnid . '\'');

    return ! $results->num_rows;
}

Here, you can add as many checks as you like. This is the opportunity to verify the various aspects of the payment. 

STEP 5 – Adding Payment

The final step after verifying the payment, doing the additional checkup is adding the payment to the database.

We will create a payment table to store the payment details in the database system. 

Here is the code to create the payments table in MySQL:


CREATE TABLE IF NOT EXISTS `payments` (
    `id` int(6) NOT NULL AUTO_INCREMENT,
    `txnid` varchar(20) NOT NULL,
    `payment_amount` decimal(7,2) NOT NULL,
    `payment_status` varchar(25) NOT NULL,
    `itemid` varchar(25) NOT NULL,
    `createdtime` datetime NOT NULL,
    PRIMARY KEY (`id`)
    ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

Then we have to set the function to call the addPayment.

Here is the function to do this task:


function addPayment($data) {
    global $db;

    if (is_array($data)) {
        $stmt = $db->prepare('INSERT INTO `payments` (txnid, payment_amount, payment_status, itemid, createdtime) VALUES(?, ?, ?, ?, ?)');
        $stmt->bind_param(
            'sdsss',
            $data['txn_id'],
            $data['payment_amount'],
            $data['payment_status'],
            $data['item_number'],
            date('Y-m-d H:i:s')
        );
        $stmt->execute();
        $stmt->close();

        return $db->insert_id;
    }

    return false;
}

Testing

Lastly, we will check if the integration is done correctly and working correctly. 

PayPal Sandbox is similar to PayPal and provides all the functionality of PayPal. But instead of using real properties, you can use fake properties in Sandbox. 

You can create fake accounts of buyers and sellers. Set the development site, and the test the PayPal integration through the stage.

Creating Sandbox accounts is free, and it can be done from the PayPal Developer website.

The code provided in the post is optimized for the Sandbox. The URL in the request is www.sandbox.paypal.com. 

You have to change the value of $enableSandbox from true to false. This will update the PayPal URLs in the coding.

Final Words

The process is tricky if you do not know coding and php. But for the developers, it is not that complicated.

However, if you are on WordPress or Magento, you should use a plugin or extension. 

In this tutorial, you learned about how you can do PayPal integration in PHP step by step. This is the basic guide.

Still, if there are any doubts or issues, you can leave it in the comments section.

*you can find the source code on this GitHub

Latest Magento Tips, Guides, & News

Stay updated with new stuff in the Magento ecosystem including exclusive deals, how-to articles, new modules, and more. 100% Magento Goodness, a promise!

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.