PayPal Pro Payment Gateway Integration in PHP

If you are working on eCommerce project and concerned about the payment gateway for accepting credit card, then PayPal Payments Pro could be the best option for you. The main advantages of the PayPal Pro are the customers don’t need to leave your site for making payment. The customer can make credit card payment within your site and without any PayPal account.

The PayPal Payments Pro provides the powerful and customizable solution to accept payment in the web application. Website Payments Pro allows you to credit and debit cards directly on the website. In this tutorial, we will show how you can easily integrate PayPal Pro payment gateway in PHP with PayPal API. Through the PayPal Pro payment gateway integration, you will be able to collect payment online using the credit card or debit card.

Create PayPal Sandbox Account

Before start accepting payment via PayPal Pro payment gateway, payment process need to be tested. To test PayPal transaction process you need a PayPal sandbox account. At first, create a PayPal sandbox account and get the API credentials of sandbox Business account. PayPal Pro payment gateway API requires a Website Payments Pro account. If you want to use a credit card as a payment method in your test transactions, you must configure a sandbox Business account as a Website Payments Pro account.
Once the PayPal business pro account creation is done, you will get the Classic Sandbox API Credentials under the API Credentials tab.


See this detailed guide to create a PayPal website payment pro sandbox account – Creating PayPal Sandbox Test Account and Website Payments Pro Account

Before you get started to implement PayPal Pro payment gateway in PHP, take a look the files structure.


Create Database Table

To store the transaction details, a table needs to be created in the database. The following SQL creates an orders table in the MySQL database to store the PayPal transaction information.

CREATE TABLE `orders` (
 `name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
 `email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `card_num` bigint(20) NOT NULL,
 `card_cvc` int(5) NOT NULL,
 `card_exp_month` varchar(2) COLLATE utf8_unicode_ci NOT NULL,
 `card_exp_year` varchar(5) COLLATE utf8_unicode_ci NOT NULL,
 `item_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `item_number` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
 `item_price` float(10,2) NOT NULL,
 `item_price_currency` varchar(10) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'usd',
 `paid_amount` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
 `paid_amount_currency` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
 `txn_id` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
 `payment_status` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
 `created` datetime NOT NULL,
 `modified` datetime NOT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Database Configuration (dbConfig.php)

The dbConfig.php file is used to connect and select the database. Specify the database host ($dbHost), username ($dbUsername), password ($dbPassword), and name ($dbName) as per your database credentials.

//Database credentials
$dbHost     'localhost';
$dbUsername 'root';
$dbPassword 'root';
$dbName     'semicolonworld';

//Connect with the database
$db = new mysqli($dbHost$dbUsername$dbPassword$dbName);

//Display error if failed to connect
if ($db->connect_errno) {
printf("Connect failed: %s\n"$db->connect_error);

PayPal Pro Checkout Form (index.php)

JavaScript Code:
This example code uses jQuery, include the jQuery library first.

<script src=""></script>

To validate credit card number we will use Credit Card Validator jQuery plugin, so include the creditCardValidator library.

<script type="text/javascript" src="js/creditCardValidator.js"></script>

Card Form Validation:
The cardFormValidate() method helps to validate card details using jQuery.

function cardFormValidate(){
    var cardValid = 0;
    //card number validation
    $('#card_number').validateCreditCard(function(result) {
        var cardType = (result.card_type == null)?'';
        if(cardType == 'Visa'){
            var backPosition = result.valid?'2px -163px, 260px -87px':'2px -163px, 260px -61px';
        }else if(cardType == 'MasterCard'){
            var backPosition = result.valid?'2px -247px, 260px -87px':'2px -247px, 260px -61px';
        }else if(cardType == 'Maestro'){
            var backPosition = result.valid?'2px -289px, 260px -87px':'2px -289px, 260px -61px';
        }else if(cardType == 'Discover'){
            var backPosition = result.valid?'2px -331px, 260px -87px':'2px -331px, 260px -61px';
        }else if(cardType == 'Amex'){
            var backPosition = result.valid?'2px -121px, 260px -87px':'2px -121px, 260px -61px';
            var backPosition = result.valid?'2px -121px, 260px -87px':'2px -121px, 260px -61px';
        $('#card_number').css("background-position", backPosition);
            cardValid = 1;
            cardValid = 0;
    //card details validation
    var cardName = $("#name_on_card").val();
    var expMonth = $("#expiry_month").val();
    var expYear = $("#expiry_year").val();
    var cvv = $("#cvv").val();
    var regName = /^[a-z ,.'-]+$/i;
    var regMonth = /^01|02|03|04|05|06|07|08|09|10|11|12$/;
    var regYear = /^2017|2018|2019|2020|2021|2022|2023|2024|2025|2026|2027|2028|2029|2030|2031$/;
    var regCVV = /^[0-9]{3,3}$/;
    if(cardValid == 0){
        return false;
    }else if(!regMonth.test(expMonth)){
        return false;
    }else if(!regYear.test(expYear)){
        return false;
    }else if(!regCVV.test(cvv)){
        return false;
    }else if(!regName.test(cardName)){
        return false;
        $('#cardSubmitBtn').prop('disabled', false);  
        return true;

Payment Process using jQuery Ajax:
The credit card details are sent to the PHP script (payment_process.php) via jQuery Ajax for further card payment processing using PayPal Pro payment gateway. Based on the payment status, the order info is shown to the user.

    //initiate validation on input fields
    $('#paymentForm input[type=text]').on('keyup',function(){
    //submit card form
        if (cardFormValidate()) {
            var formData = $('#paymentForm').serialize();
                dataType: "json",
                beforeSend: function(){  
                success:function(data){ //console.log(data);
                    if(data.status == 1){
                        $('#orderInfo').html('<p>The transaction was successful. Order ID: <span>'+data.orderID+'</span></p>');
                        $('#orderInfo').html('<p>Transaction has been failed, please try again.</p>');

HTML Code:
The following HTML creates payment form to provide the card details (Card Number, Expiration Date, and CVC No.). The orderInfo section is used to display the order details.

<div class="card-payment">
    <h3>PayPal Pro Integration in PHP</h3>
    <div id="paymentSection">
        <form method="post" id="paymentForm">
            <h4>Payable amount: $10 USD</h4>
                    <label for="card_number">Card number</label>
                    <input type="text" placeholder="1234 5678 9012 3456" id="card_number" name="card_number">
                <li class="vertical">
                            <label for="expiry_month">Expiry month</label>
                            <input type="text" placeholder="MM" maxlength="5" id="expiry_month" name="expiry_month">
                            <label for="expiry_year">Expiry year</label>
                            <input type="text" placeholder="YYYY" maxlength="5" id="expiry_year" name="expiry_year">
                            <label for="cvv">CVV</label>
                            <input type="text" placeholder="123" maxlength="3" id="cvv" name="cvv">
                    <label for="name_on_card">Name on card</label>
                    <input type="text" placeholder="Codex World" id="name_on_card" name="name_on_card">
                    <input type="hidden" name="card_type" id="card_type" value=""/>
                    <input type="button" name="card_submit" id="cardSubmitBtn" value="Proceed" class="payment-btn" disabled="true" >
    <div id="orderInfo" style="display: none;"></div>

PaypalPro Class

PaypalPro class helps to make the API call using API credentials and process the card payment using PayPal Payments Pro. You will get all the library files in our source code, you don’t need to download it separately.

Validate and Process Payment (payment_process.php)

In this file, the submitted card details are validated and the charge is processed using PaypalPro PHP library.

  • Include the PayPalPro PHP library.
  • Specify product details, buyer information, and card details.
  • Create an instance of PaypalPro class.
  • Set your $apiUsername, $apiPassword, and $apiSignature as per the API credentials of your PayPal Business Pro account.
  • Call paypalCall() function of PaypalPro class and pass the item, buyer, and card details ($paypalParams).
  • If the charge is successful, the transaction details will be inserted in the MySQL database.
  • The transaction status will be returned to the Ajax success function.
//include PayPalPro PHP library

//product details
$itemName "Premium Project Purchase";
$itemNumber "PPP123456";
$payableAmount 10;
$currency "USD";
//buyer information
$name $_POST['name_on_card'];
$nameArr explode(' '$name);
$firstName $nameArr[0];
$lastName $nameArr[1];
$city 'Charleston';
$zipcode '25301';
$countryCode 'US';
//card details
$creditCardNumber trim(str_replace(" ","",$_POST['card_number']));
$creditCardType $_POST['card_type'];
$expMonth $_POST['expiry_month'];
$expYear $_POST['expiry_year'];
$cvv $_POST['cvv'];
//Create an instance of PaypalPro class
$config = array(
'apiUsername' => 'Your_API_Username',
'apiPassword' => 'Your_API_Password',
'apiSignature' => 'Your_API_Signature'
$paypal = new PaypalPro($config);
//Payment details
$paypalParams = array(
'paymentAction' => 'Sale',
'itemName' => $itemName,
'itemNumber' => $itemNumber,
'amount' => $payableAmount,
'currencyCode' => $currency,
'creditCardType' => $creditCardType,
'creditCardNumber' => $creditCardNumber,
'expMonth' => $expMonth,
'expYear' => $expYear,
'cvv' => $cvv,
'firstName' => $firstName,
'lastName' => $lastName,
'city' => $city,
'zip'    => $zipcode,
'countryCode' => $countryCode,
$response $paypal->paypalCall($paypalParams);
$paymentStatus strtoupper($response["ACK"]);
$paymentStatus == "SUCCESS"){
//transaction info
$transactionID $response['TRANSACTIONID'];
$amount $response['AMT'];
$date date("Y-m-d H:i:s");
//include database config file
include_once 'dbConfig.php';
//insert tansaction data into the database
$sql "INSERT INTO orders(name,email,card_num,card_exp_month,card_exp_year,card_cvc,item_name,item_number,item_price,item_price_currency,paid_amount,paid_amount_currency,txn_id,payment_status,created,modified) VALUES('".$name."','','".$creditCardNumber."','".$expMonth."','".$expYear."','".$cvv."','".$itemName."','".$itemNumber."','".$payableAmount."','".$currency."','".$amount."','".$currency."','".$transactionID."','".$paymentStatus."','".$date."','".$date."')";
$insert $db->query($sql);
$last_insert_id $db->insert_id;
$data['status'] = 1;
$data['orderID'] = $last_insert_id;
$data['status'] = 0;
//transaction status
echo json_encode($data);

If you want the recurring transaction, insert recurring key into the $paypalParams array.

//Create an instance of PaypalPro class
$config = array(
'apiUsername' => 'Your_API_Username',
'apiPassword' => 'Your_API_Password',
'apiSignature' => 'Your_API_Signature',
'live' => 1
$paypal = new PaypalPro($config);

Make PayPal Pro Payment Gateway Live

Once the testing is done and the payment process working properly, do the following changes to make PayPal Pro payment gateway live.

  • In the payment_process.php file, change the Test API credentials ($apiUsername, $apiPassword and $apiSignature) with the Live API credentials and set live => 1.

Related Articles

Comments 2