How to Integration PayPal Payment Gateway in PHP?

Today, We want to share with you paypal integration in php.In this post we will show you paypal integration in php with sandbox, hear for payment gateway in php and mysql we will give you demo and example for implement.In this post, we will learn about paypal integration in php laravel with an example.

paypal integration in php

There are the Following The simple About paypal integration in php codeigniter Full Information With Example and source code.

As I will cover this Post with live Working example to develop paypal integration in php step by step pdf, so the paypal integration in php is used for this example is following below.

Step 1: Create a Database And Table

subscription.sql
Table structure for table `subscription`

--
-- Table structure for table `subscription`
--

CREATE TABLE IF NOT EXISTS `subscription` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `product_number` varchar(255) NOT NULL,
  `product_name` varchar(255) NOT NULL,
  `subscription_status` varchar(255) NOT NULL,
  `subscription_amount` double(10,2) NOT NULL,
  `subscription_currency` varchar(255) NOT NULL,
  `txn_id` varchar(255) NOT NULL,
  `create_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
);

Step 2: Create a Landing Page

index.php

<html>
<title>Paypal subscription Gateway Integration in PHP</title>
<head>
<style>
body {
    font-family: Arial;
    line-height: 30px;
    color: #333;
}

#subscription-box {
    padding: 40px;
    margin: 20px;
    border: #E4E4E4 1px solid;
    display: inline-block;
    text-align: center;
    border-radius: 3px;
}

#pay_now {
    padding: 10px 30px;
    background: #09f;
    border: #038fec 1px solid;
    border-radius: 3px;
    color: #FFF;
    width: 100%;
    cursor: pointer;
}

.txt-title {
    margin: 25px 0px 0px 0px;
    color: #4e4e4e;
}

.txt-price {
    margin-bottom: 20px;
    color: #08926c;
    font-size: 1.1em;
}
</style>
</head>
<body>
    <div id="subscription-box">
        <img src="images/camera.jpg" />
        <h4 class="txt-title">Lenova Z570</h4>
        <div class="txt-price">$28789.61</div>
        <form action="https://www.sandbox.paypal.com/cgi-bin/webscr"
            method="post" target="_top">
            <input type='hidden' name='business'
                value='PayPal Business Email'> <input type='hidden'
                name='product_name' value='Camera'> <input type='hidden'
                name='product_number' value='CAM#N1'> <input type='hidden'
                name='amount' value='10'> <input type='hidden'
                name='no_shipping' value='1'> <input type='hidden'
                name='currency_code' value='USD'> <input type='hidden'
                name='notify_url'
                value='http://sitename/paypal-subscription-gateway-integration-in-php/notify.php'>
            <input type='hidden' name='cancel_return'
                value='http://sitename/paypal-subscription-gateway-integration-in-php/cancel.php'>
            <input type='hidden' name='return'
                value='http://sitename/paypal-subscription-gateway-integration-in-php/return.php'>
            <input type="hidden" name="cmd" value="_xclick"> <input
                type="submit" name="pay_now" id="pay_now"
                Value="Pay Now">
        </form>
    </div>
</body>
</html>

Step 3: Create a DBController File

DBController.php

<?php

class DBController
{

    private $host = "host";
    private $user = "username";
    private $password = "password";
    private $database = "dbname";
    private $conn;

    function __construct()
    {
        $this->conn = $this->connectDB();
    }

    function connectDB()
    {
        $conn = mysqli_connect($this->host, $this->user, $this->password, $this->database);
        return $conn;
    }

    function runQuery($query, $param_type, $param_value_array)
    {
        $sql = $this->conn->prepare($query);
        $this->bindQueryParams($sql, $param_type, $param_value_array);
        $sql->execute();
        $result = $sql->get_result();
        
        if ($result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                $resultset[] = $row;
            }
        }
        
        if (! empty($resultset)) {
            return $resultset;
        }
    }

    function bindQueryParams($sql, $param_type, $param_value_array)
    {
        $param_value_reference[] = & $param_type;
        for ($i = 0; $i < count($param_value_array); $i ++) {
            $param_value_reference[] = & $param_value_array[$i];
        }
        call_user_func_array(array(
            $sql,
            'bind_param'
        ), $param_value_reference);
    }

    function insert($query, $param_type, $param_value_array)
    {
        $sql = $this->conn->prepare($query);
        $this->bindQueryParams($sql, $param_type, $param_value_array);
        $sql->execute();
    }
}
?>

Step 5 : Creating a Notify Page

notify.php

<?php

define("DEBUG", 1);

define("USE_SANDBOX", 1);
define("LOG_FILE", "ipn.log");

$raw_post_data = file_get_contents('php://input');
$raw_post_array = explode('&', $raw_post_data);
$myPost = array();
foreach ($raw_post_array as $keyval) {
	$keyval = explode ('=', $keyval);
	if (count($keyval) == 2)
		$myPost[$keyval[0]] = urldecode($keyval[1]);
}
// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-validate';
if(function_exists('get_magic_quotes_gpc')) {
	$get_magic_quotes_exists = true;
}
foreach ($myPost as $key => $value) {
	if($get_magic_quotes_exists == true && get_magic_quotes_gpc() == 1) {
		$value = urlencode(stripslashes($value));
	} else {
		$value = urlencode($value);
	}
	$req .= "&$key=$value";
}

if(USE_SANDBOX == true) {
	$paypal_url = "https://www.sandbox.paypal.com/cgi-bin/webscr";
} else {
	$paypal_url = "https://www.paypal.com/cgi-bin/webscr";
}
$ch = curl_init($paypal_url);
if ($ch == FALSE) {
	return FALSE;
}
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_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
if(DEBUG == true) {
	curl_setopt($ch, CURLOPT_HEADER, 1);
	curl_setopt($ch, CURLINFO_HEADER_OUT, 1);
}

curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));

$res = curl_exec($ch);
if (curl_errno($ch) != 0) 
	{
	if(DEBUG == true) {	
		error_log(date('[Y-m-d H:i e] '). "Can't connect to PayPal to validate IPN message: " . curl_error($ch) . PHP_EOL, 3, LOG_FILE);
	}
	curl_close($ch);
	exit;
} else {

		if(DEBUG == true) {
			error_log(date('[Y-m-d H:i e] '). "HTTP request of validation request:". curl_getinfo($ch, CURLINFO_HEADER_OUT) ." for IPN payload: $req" . PHP_EOL, 3, LOG_FILE);
			error_log(date('[Y-m-d H:i e] '). "HTTP response of validation request: $res" . PHP_EOL, 3, LOG_FILE);
		}
		curl_close($ch);
}

$tokens = explode("\r\n\r\n", trim($res));
$res = trim(end($tokens));
if (strcmp ($res, "VERIFIED") == 0) {

	$product_name = $_POST['product_name'];
	$product_number = $_POST['product_number'];
	$subscription_status = $_POST['subscription_status'];
	$subscription_amount = $_POST['mc_gross'];
	$subscription_currency = $_POST['mc_currency'];
	$txn_id = $_POST['txn_id'];
	$receiver_email = $_POST['receiver_email'];
	$payer_email = $_POST['payer_email'];
	
	include("DBController.php");
	$db = new DBController();
	

	$issubscriptionCompleted = false;
	if($subscription_status == "Completed") {
		$issubscriptionCompleted = true;
	}

	$isUniqueTxnId = false; 
	$param_type="s";
	$param_value_array = array($txn_id);
	$result = $db->runQuery("SELECT * FROM subscription WHERE txn_id = ?",$param_type,$param_value_array);
	if(empty($result)) {
        $isUniqueTxnId = true;
	}	

	if($issubscriptionCompleted) {
	    $param_type = "sssdss";
	    $param_value_array = array($product_number, $product_name, $subscription_status, $subscription_amount, $subscription_currency, $txn_id);
	    $subscription_id = $db->insert("INSERT INTO subscription(product_number, product_name, subscription_status, subscription_amount, subscription_currency, txn_id) VALUES(?, ?, ?, ?, ?, ?)", $param_type, $param_value_array);
	    error_log(date('[Y-m-d H:i e] '). "Verified IPN: $req ". PHP_EOL, 3, LOG_FILE);
	} 
	
	
	if(DEBUG == true) {
		error_log(date('[Y-m-d H:i e] '). "Verified IPN: $req ". PHP_EOL, 3, LOG_FILE);
	}
	
} else if (strcmp ($res, "INVALID") == 0) {
	if(DEBUG == true) {
		error_log(date('[Y-m-d H:i e] '). "Invalid IPN: $req" . PHP_EOL, 3, LOG_FILE);
	}
}
?>

Step 6: Create a Return Page

return.php

<html>
<head>
<title>Order Placed</title>
<style>
.response-text {
    display: inline-block;
    max-width: 550px;
    margin: 0 auto;
    font-size: 1.5em;
    text-align: center;
    background: #fff3de;
    padding: 42px;
    border-radius: 3px;
    border: #f5e9d4 1px solid;
    font-family: arial;
    line-height: 34px;
}
</style>
</head>
<body>
    <div class="response-text">
        You have placed your order successfully.<br> Thank you for
        shopping with us!
    </div>
</body>
</html>

Step 7: Create a Cancel Page

cancel.php

Sorry! subscription Cancelled.

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about paypal integration in php.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.


Related FAQ

Here are some more FAQ related to this Article:

  1.   jQuery Ajax Call to Laravel Script with JSON Return
  2.   Ajax Dynamic Dependent Dropdown using Laravel Example
  3.   jQuery trigger function viewport Example
  4.   Laravel Eloquent Useful Tips and Tricks
  5.   laravel print last query | Executed | Sql | php | tutorials
  6.   Laravel Form Automatic model validation Example
  7.   Add Edit Delete Table Row Example using JQuery
  8.   PHP Secure Token Generator Authentication tutorial
  9.   javascript validation registration form
  10.   Laravel Eloquent Get Last Inserted Id
Tags:, , , , , , , , ,