PHPTutorials

PayPal Payment Gateway Integration in PHP

Divi WordPress Theme

Paypal is the most popular payment gateway in the world and mostly used to send or received payments. See the tutorial and integrate the paypal to your php based website easily.

Creating a PayPal Sandbox Account

To test transaction process you need to create PayPal sandbox account.

  • Go to the PayPal Developer page and log in to your PayPal account. If you don’t have any PayPal account, sign up for a PayPal account first.
  • After logged in you would be redirected to the developer homepage. Now click on the Dashboard link from the top navigation menu.
  • Click on the Accounts link under the Sandbox label from the left menu panel.
  • Create buyer account and merchant account from the Create Account link. For buyer account, you need to select Personal radio button under the Account type section or select Business radio button for a merchant account.
Database Tables Creation
CREATE TABLE `products` (
     `id` int(11) NOT NULL AUTO_INCREMENT,
     `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL, 
     `image` varchar(255) COLLATE utf8_unicode_ci NOT NULL, 
     `price` float(10,2) NOT NULL, 
     `status` tinyint(1) NOT NULL DEFAULT '1', 
     PRIMARY KEY (`id`) 
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

CREATE TABLE `paypal-payments` (
         `payment_id` int(11) NOT NULL AUTO_INCREMENT, 
         `item_number` varchar(255) COLLATE utf8_unicode_ci NOT NULL, 
         `txn_id` varchar(255) COLLATE utf8_unicode_ci NOT NULL, 
         `payment_gross` float(10,2) NOT NULL, 
         `currency_code` varchar(5) COLLATE utf8_unicode_ci NOT NULL, 
         `payment_status` varchar(255) COLLATE utf8_unicode_ci NOT NULL, 
         PRIMARY KEY (`payment_id`) 
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Database Configuration (connect.php)

Change $dbHost, $dbUsername, $dbPassword, and $dbName variable’s value with your database credentials.

<?php
//Database credentials
$dbHost = 'localhost';
$dbUsername = 'root';
$dbPassword = '';
$dbName = 'creepes';

//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);
    exit();
}
?>
Products (products.php)

To use PayPal standard payment gateway, you need to submit a form with some predefined PayPal HTML form field variable.

<?php
//Include DB configuration file
include 'connect.php';

//Set useful variables for paypal form
$paypalURL = 'https://www.sandbox.paypal.com/cgi-bin/webscr'; //Test PayPal API URL
$paypalID = 'info@creepeslab.com'; //Business Email

?>

<?php
    //Fetch products from the database
    $results = $db->query("SELECT * FROM products");
    while($row = $results->fetch_assoc()){
?>

    <img src="images/<?php echo $row['image']; ?>"/>
    Name: <?php echo $row['name']; ?>
    Price: <?php echo $row['price']; ?>
    <form action="<?php echo $paypalURL; ?>" method="post">
       // Identify your business so that you can collect the payments.
        <input type="hidden" name="business" value="<?php echo $paypalID; ?>">

        // Specify a Buy Now button.
        <input type="hidden" name="cmd" value="_xclick">

        // Specify details about the item that buyers will purchase.
        <input type="hidden" name="item_name" value="<?php echo $row['name']; ?>">
        <input type="hidden" name="item_number" value="<?php echo $row['id']; ?>">
        <input type="hidden" name="amount" value="<?php echo $row['price']; ?>">
        <input type="hidden" name="currency_code" value="USD">

        // Specify URLs
        <input type='hidden' name='cancel_return' value='http://localhost/paypal_integration_php/cancel.php'>
        <input type='hidden' name='return' value='http://localhost/paypal_integration_php/success.php'>

        // Display the payment button.
        <input type="image" name="submit" border="0"
        src="https://www.paypalobjects.com/en_US/i/btn/btn_buynow_LG.gif" alt="PayPal - The safer, easier way to pay online">
        <img alt="" border="0" width="1" height="1" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" >
    </form>

<?php } ?>

Note: Don’t forget to change the cancel_return and return input field value with your desired URL in PayPal HTML form.

Payment Success (success.php)
<?php
include 'connect.php';

//Get payment information from PayPal
$item_number = $_GET['item_number']; 
$txn_id = $_GET['tx'];
$payment_gross = $_GET['amt'];
$currency_code = $_GET['cc'];
$payment_status = $_GET['st'];

//Get product price from database
$productResult = $db->query("SELECT price FROM products WHERE id = ".$item_number);
$productRow = $productResult->fetch_assoc();
$productPrice = $productRow['price'];

if(!empty($txn_id) && $payment_gross == $productPrice){
    //Check if payment data exists with the same TXN ID.
    $prevPaymentResult = $db->query("SELECT payment_id FROM payments WHERE txn_id = '".$txn_id."'");

    if($prevPaymentResult->num_rows > 0){
        $paymentRow = $prevPaymentResult->fetch_assoc();
        $last_insert_id = $paymentRow['payment_id'];
    }else{
        //Insert tansaction data into the database
        $insert = $db->query("INSERT INTO payments(item_number,txn_id,payment_gross,currency_code,payment_status) VALUES('".$item_number."','".$txn_id."','".$payment_gross."','".$currency_code."','".$payment_status."')");
        $last_insert_id = $db->insert_id;
    }
?>
    <h1>Your payment has been successful.</h1>
    <h1>Your Payment ID - <?php echo $last_insert_id; ?></h1>
<?php }else{ ?>
    <h1>Your payment has failed.</h1>
<?php } ?>
Payment Cancel (cancel.php)
<h1>Your PayPal transaction has been canceled.</h1>

Thank you for reading the article. Hope to share and comment if you like the article.

Khandoker Hirok

I'm an expert web developer over 6 years experience. I can fix bugs, customize and makes website and Software as per your requirements with Wordpress, PHP, Laravel and Codeigniter. My Fiverr: https://fiverr.com/hirokbd

Related Articles

Leave a Reply

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

Back to top button