How To Paypal Payments Prointegration Php

How To Paypal Payments Prointegration Php

How To Paypal Payments Prointegration Php

0 Sales

Free

If you're working on an eCommerce project and you're worried about the payment gateway to accept credit card, then PayPal Payments Pro might be your best option. The PayPal Pro's main advantages are that customers don't have to leave your site to pay. Within your website and without any PayPal account, the customer can make credit card payment.

 

The PayPal Payments Pro offers an efficient and flexible solution in the web application to accept credit card payment. Website Payments Support API helps you to accept directly on the website credit and debit cards. We'll explain how to integrate PayPal Pro payment gateway with PayPal API in this tutorial. Using the credit card or debit card, you will be able to collect payment directly from the customer through the PayPal Pro payment gateway implementation.


 

The payment process must be tested before accepting payment via PayPal Pro payment gateway. A sandbox account must be created on the PayPal Developer account to test the transaction process with PayPal. You can test the transaction before making the payment gateway live on the production server with the PayPal sandbox account.

 

First, create a sandbox account for PayPal. You will receive your Business Account API credentials in your sandbox. Your business account must be Website Payments Pro account to incorporate the PayPal Pro gateway API. You should configure a sandbox Business account as a Website Payments Pro account if you want to use a credit card as a payment method in your trial transactions.

 

Once the development of the PayPal business pro account is complete, you will obtain the credentials of the NVP / SOAP Sandbox API under the API Credentials section.




 

When calling the PayPal Pro API, you need to specify the credentials of the API. Copy the credentials of the API (Username, Password, and Signature) for later use in the script.

 

Take a look at the files structure before you start implementing PayPal Pro payment gateway in PHP.


 

paypal_pro_integration_php/

├── config.php

├── dbConnect.php

├── index.php

├── payment_process.php

├── PaypalPro.class.php

├── js/

│   ├── jquery.min.js

│   └── creditCardValidator.js

└── css/

    └── style.css


 

Create Database Table

A table must be created in the database to store the transaction details. The following SQL creates a table of orders in the MySQL database with some basic fields.

 

CREATE TABLE `orders` (

 `id` int(11) NOT NULL AUTO_INCREMENT,

 `name` varchar(30) COLLATE utf8_unicode_ci NOT NULL,

 `email` varchar(25) COLLATE utf8_unicode_ci DEFAULT 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(50) COLLATE utf8_unicode_ci NOT NULL,

 `payment_status` varchar(25) COLLATE utf8_unicode_ci NOT NULL,

 `created` datetime NOT NULL,

 `modified` datetime NOT NULL,

 PRIMARY KEY (`id`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;



 

PaypalPro PHP Library


 

The PaypalPro class (PaypalPro.class.php) helps make the PayPal API call and process the payment of the card using PayPal Payments Pro and PHP. You don't have to download the PayPal Pro library file separately, the source code includes all the required files.

 

Site Settings and API Configuration (config.php)

Product details, PayPal API credentials, and constant variables for database settings are defined in the config.php file.

Product details:

 

  • $itemName–Enter the name of the product.

  • $itemNumber-Specify the number of the product.

  • $payableMount–Specify the price of the product.

  • $Money–Specify the code of the currency.

 

Constants of PayPal API: 

  • PAYPAL API USERNAME–Specify the PayPal Business Pro account username of the API.

  • PAYPAL API PASSWORD –Enter the PayPal Business Pro account password for the API.

  • PAYPAL API SIGNATURE–Specify the PayPal Business Pro account signature of the API.

  • PAYPAL SANDBOX–Specify if you are using the TRUE / FALSE environment.

Constants of the database: 

  • DB HOST-Specify the host of the database.

  • DB USERNAME – Enter the username of the database.

  • DB PASSWORD – Specify the password for the database.

  • DB NAME – Enter the name of the database.

 

<?php

/*

 * Basic Site Settings and API Configuration

 */

 

// Product details

$itemName   = "Premium Project Purchase";

$itemNumber = "P123456";

$payableAmount = 10;

$currency   = "USD";

 

 

// PayPal API configuration

define('PAYPAL_API_USERNAME', 'API_Username');

define('PAYPAL_API_PASSWORD', 'API_Password');

define('PAYPAL_API_SIGNATURE', 'API_Signature');

define('PAYPAL_SANDBOX', TRUE); //TRUE or FALSE

 

// Database configuration

define('DB_HOST', 'MySQL_Database_Host');

define('DB_USERNAME', 'MySQL_Database_Username');

define('DB_PASSWORD', 'MySQL_Database_Password');

define('DB_NAME', 'MySQL_Database_Name');



 

Database Connection (dbConnect.php)

The dbConnect.php file is used to connect the database using PHP and MySQL.

<?php

// Connect with the database

$db = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);

 

// Display error if failed to connect

if ($db->connect_errno) {

    printf("Connect failed: %s\n", $db->connect_error);

    exit();

}

PayPal Pro Checkout Form (index.php)

Credit Card Form:

 

The credit card information (Card Number, Expiration Date, CVC Number, and Card Holder Name) is initially presented with an HTML file. The name and price of the item are also shown at the top of the page.

 

<?php

// Include configuration file

include_once 'config.php';

?>


<div id="paymentSection">

    <form method="post" id="paymentForm">

        <h4>Item: <?php echo $itemName; ?></h4>

        <h4>Payable amount: $<?php echo $payableAmount.' '.$currency; ?></h4>

        <ul>

            <li>

                <label>Card number</label>

                <input type="text" placeholder="1234 5678 9012 3456" maxlength="20" id="card_number" name="card_number">

            </li>

            <li class="vertical">

                <ul>

                    <li>

                        <label>Expiry month</label>

                        <input type="text" placeholder="MM" maxlength="5" id="expiry_month" name="expiry_month">

                    </li>

                    <li>

                        <label>Expiry year</label>

                        <input type="text" placeholder="YYYY" maxlength="5" id="expiry_year" name="expiry_year">

                    </li>

                    <li>

                        <label>CVV</label>

                        <input type="text" placeholder="123" maxlength="3" id="cvv" name="cvv">

                    </li>

                </ul>

            </li>

            <li>

                <label>Name on card</label>

                <input type="text" placeholder="John Doe" id="name_on_card" name="name_on_card">

            </li>

            <li>

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

            </li>

        </ul>

    </form>

</div>



jQuery Library:

We'll use jQuery to process page-free refresh card payment. So, first include the library of jQuery.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Card Form Validation:

We will use the Credit Card Validator jQuery plugin to validate the credit card number, including the creditCardValidator library.

 

<script src="js/creditCardValidator.js"></script>

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)?'':result.card_type.name;

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

        }else{

            var backPosition = result.valid?'2px -121px, 260px -87px':'2px -121px, 260px -61px';

        }

        $('#card_number').css("background-position", backPosition);

        if(result.valid){

            $("#card_type").val(cardType);

            $("#card_number").removeClass('required');

            cardValid = 1;

        }else{

            $("#card_type").val('');

            $("#card_number").addClass('required');

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

        $("#card_number").addClass('required');

        $("#card_number").focus();

        return false;

    }else if(!regMonth.test(expMonth)){

        $("#card_number").removeClass('required');

        $("#expiry_month").addClass('required');

        $("#expiry_month").focus();

        return false;

    }else if(!regYear.test(expYear)){

        $("#card_number").removeClass('required');

        $("#expiry_month").removeClass('required');

        $("#expiry_year").addClass('required');

        $("#expiry_year").focus();

        return false;

    }else if(!regCVV.test(cvv)){

        $("#card_number").removeClass('required');

        $("#expiry_month").removeClass('required');

        $("#expiry_year").removeClass('required');

        $("#cvv").addClass('required');

        $("#cvv").focus();

        return false;

    }else if(!regName.test(cardName)){

        $("#card_number").removeClass('required');

        $("#expiry_month").removeClass('required');

        $("#expiry_year").removeClass('required');

        $("#cvv").removeClass('required');

        $("#name_on_card").addClass('required');

        $("#name_on_card").focus();

        return false;

    }else{

        $("#card_number").removeClass('required');

        $("#expiry_month").removeClass('required');

        $("#expiry_year").removeClass('required');

        $("#cvv").removeClass('required');

        $("#name_on_card").removeClass('required');

        $('#cardSubmitBtn').prop('disabled', false);  

        return true;

    }

}


Payment Process using jQuery and Ajax:

 

The Ajax request is initiated through the PayPal Pro API to validate and process the card transaction.

 

  • The information given by the card is sent via Ajax to the server-side script (payment process.php).

  • In the server-side script, the transaction is processed and the payment status is returned.

  • The order info or error message will be shown to the user based on the response.

 

$(document).ready(function(){

    // Initiate validation on input fields

    $('#paymentForm input[type=text]').on('keyup',function(){

        cardFormValidate();

    });

    

    // Submit card form

    $("#cardSubmitBtn").on('click',function(){

        $('.status-msg').remove();

        if(cardFormValidate()){

            var formData = $('#paymentForm').serialize();

            $.ajax({

                type:'POST',

                url:'payment_process.php',

                dataType: "json",

                data:formData,

                beforeSend: function(){

                    $("#cardSubmitBtn").prop('disabled', true);

                    $("#cardSubmitBtn").val('Processing....');

                },

                success:function(data){

                    if(data.status == 1){

                        $('#paymentSection').html('<p class="status-msg success">The transaction was successful. Order ID: <span>'+data.orderID+'</span></p>');

                    }else{

                        $("#cardSubmitBtn").prop('disabled', false);

                        $("#cardSubmitBtn").val('Proceed');

                        $('#paymentSection').prepend('<p class="status-msg error">Transaction has been failed, please try again.</p>');

                    }

                }

            });

        }

    });

});



Validate and Process Payment (payment_process.php)

 

The requested card details will be checked in the payment process.php file and the invoice will be processed using Paypal PHP library and PHP.

 

  • Include the library and configuration directory for PayPalPro PHP.

  • Get details of the item, information of the customer, and details of the ticket.

  • Create a Paypal class example.

  • Call PaypalPalPro class's paypalCall() function and transfer the product, purchaser and card details ($paypalParams).

  • The transaction details will be inserted into the MySQL database if the charge is successful.

  • The status of the transaction returns to the request of Ajax.

 

<?php


// Include configuration file

include_once 'config.php';


// Include database connection file

include_once 'dbConnect.php';


// Include PayPalPro PHP library

require_once 'PaypalPro.class.php';


if($_SERVER['REQUEST_METHOD'] == 'POST'){

    

    // Buyer information

    $name = $_POST['name_on_card'];

    $nameArr = explode(' ', $name);

    $firstName = !empty($nameArr[0])?$nameArr[0]:'';

    $lastName = !empty($nameArr[1])?$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

    $paypal = new PaypalPro();

    

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

    if($paymentStatus == "SUCCESS"){

        // Transaction info

        $transactionID = $response['TRANSACTIONID'];

        $paidAmount = $response['AMT'];

        

        // Insert tansaction data into the database

        $sql = "INSERT INTO orders(name,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."','".$paidAmount."','".$currency."','".$transactionID."','".$paymentStatus."',NOW(),NOW())";

        $insert = $db->query($sql);

        $last_insert_id = $db->insert_id;

        

        $data['status'] = 1;

        $data['orderID'] = $last_insert_id;

    }else{

         $data['status'] = 0;

    }

    

    // Transaction status

    echo json_encode($data);

}

?>




Recurring Payment:

Insert recurring key (recurring = Y) into the $paypalParams array if you want the recurring transaction.

$paypalParams = array( 

    ... 

    'recurring' => 'Y' 

); 

$response = $paypal->paypalCall($paypalParams);


 

Make PayPal Pro Payment Gateway Live

Once the test is complete and the payment process works properly on the Sandbox environment, make the following changes to make the payment gateway live for PayPal Pro.

 

  1. Change the credentials of the PayPal API (PAYPAL API USERNAME, PAYPAL API PASSWORD, PAYPAL API SIGNATURE) in the config.php file as per your PayPal Pro Business account.

  2. Set FALSE to PAYPAL SANDBOX.

LICENSE OF USE

You can use it for personal or commercial projects. You can't resell it partially or in this form.

PRODUCT INFO

Create Date : May 14, 2020

Updated Date : May 14, 2020

Ratings

Comments : 0

Downloads : 0