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 (

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

    <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="[email protected]" />
        <input type="hidden" name="item_number" value="123456" / >
        <input type="submit" name="submit" value="Submit Payment"/>


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' => '[email protected]',
    'return_url' => '',
    'cancel_url' => '',
    'notify_url' => ''

$paypalUrl = $enableSandbox ? '' : '';

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

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

    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:

    `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`)

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(?, ?, ?, ?, ?)');
            date('Y-m-d H:i:s')

        return $db->insert_id;

    return false;


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 

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

Also Read:

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!

9 thoughts on “How to do PayPal Integration in PHP? (Step by Step Tutorial)”

  1. I downloaded the Git source, edited everything correctly, it does redirect to paypal sandbox, where I pay and after back to success html, but there is no change in the database, I tried few guides, all the same problem, it doesn’t insert anything in the table.

  2. Hi, I can see that you redirect page with “Get” method, so what if a smart client change the amount value before PayPal opened? also you didn’t check [gross] value with [site amount] value in verify function!

  3. Hi can you please help me I got and issue on my side that data is not getting stored in my database, but the sandbox accounts are working fine.

  4. Very well explaied ,I have checked so many websites to find a proper way to handle paypal without any package installed, and finally I found yours.Thanks a million.

  5. Hi, for me everything is working perfectly but i don’t know if payment script is executing correctly when i check my database table payments no information there, the script is not adding data to table.

    Thank you very much

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.

Scroll to Top

We can help you. Right now.

Fast growing merchants depend ServerGuy for high-performance hosting. Experience counts. Let's get started.

Talk to a sales representative

USA / Worldwide




Core Web Vitals Book COver

Is your website ready for Core Web Vitals?

Take this FREE book with you and optimize your store for speed.

Learn all about new Google new ranking factors and get that top ranking.