Paypal standard integration script using PHP

Hello friends, today I will show you paypal standard integration using PHP. PayPal is an international e-commerce business that allow payments and money transfers to be made through the Internet. We are using payPal to transfer money from one account to another. If we want to buy some products from an online shop, we can make the payment through paypal if there is any option for paypal. In this application I am creating a form where user will submit his/her information, after clicking submit it will be redirected to paypal site where user put their username, password and buy the item or they can pay with credit card also. After making a payment paypal will silently post user information to our site, we will validate the data and save this into our database. At last user will see a success page if all are ok.

Step 1: Create a database table for saving user information and payment related status.





DROP TABLE IF EXISTS `payment_history`;
CREATE TABLE IF NOT EXISTS `payment_history` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`order_id` varchar(255) NOT NULL,
`first_name` varchar(255) NOT NULL,
`last_name` varchar(255) NOT NULL,
`email_address` varchar(255) NOT NULL,
`product_price` varchar(255) NOT NULL,
`status` varchar(255) NOT NULL,
`response` varchar(255) NOT NULL,
`all_data` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;

Step 2: Now create a payment form for user where they put their information. I name it index.php.

<!DOCTYPE HTML>
<html lang="en-US">
<head>
	<meta charset="UTF-8">
	<title></title>
</head>
<body>
	<h5>Suppose you have $10 in your cart, you want to buy this product using paypal. Please fill all the fields then you will be redirected to paypal site. In paypal website choose "Pay with my PayPal account" because I do not have "Pay with my debit or credit card" data like credit card no etc. But for you this is not an issue. If you and sandbox account with credit card no or other value you can choose any of them. My sandbox email id is abhijit@technokrats.in, Password:pola@1991. If you do not have sandbox account try with my email address and password. If you have own sandbox account so put your email & password.</h5>
	<?php
		if(isset($_GET['text']))
		echo $_GET['text'];
	?>
	<?php
		$characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
		$string = '';
		$random_string_length = 6;
		for ($i = 0; $i < $random_string_length; $i++) {
			  $string .= $characters[rand(0, strlen($characters) - 1)];
		}
	?>
	<form action="form.php" method="POST">
		<p>First Name: <input type="text" name="first_name" value=""/></p>
		<p>Last Name: <input type="text" name="last_name" value=""/></p>
		<p>Email address: <input type="text" name="email" value="abhijit@technokrats.in"/>(I am using my paypal sandbox account.)</p>
		<p>Address: <input type="text" name="address1" value="" ></p>
		<p>Country: <input type="text" name="country" value="" ></p>
		<p>City: <input type="text" name="city" value="" ></p>
		<p>Zip Code: <input type="text" name="zip" value="" ></p>
		<br/>
		<input type="hidden" name="order_no" value="<?php echo $string;  ?>"/>
		<input type="submit" name="submit" value="Pay With Paypal"/>
	</form>
</body>
</html>

Step 3: In this step I create a form.php where submitted user data will be taken and then post to paypal site.

I make it simple for understand but you can validate user information here.

<?php
session_start();
if(isset($_POST['submit']) && ($_POST['submit'] == 'Pay With Paypal'))
{
	$_SESSION['order_id'] = trim($_POST['order_no']);
	$_SESSION['all_product_price'] = '10.00';
	$_SESSION['first_name'] = (trim($_POST['first_name'])) ? trim($_POST['first_name']) : 'Abhijit';
	$_SESSION['last_name'] = (trim($_POST['last_name'])) ? trim($_POST['last_name']) : 'Pal';
	$_SESSION['email'] = (trim($_POST['email'])) ? trim($_POST['email']) : 'abhijit@technokrats.in';
	$_SESSION['business_email'] = 'abhijitscom@gmail.com';
?>

<form name="pay_with_paypal" method="post" action="https://www.sandbox.paypal.com/cgi-bin/webscr">
	<input type="hidden" value="abhijitscom@gmail.com" name="business">
 
	<input type="hidden" value="HP LP3065" name="item_name_1">
	<input type="hidden" value="Product 21" name="item_number_1">
	<input type="hidden" value="5.00" name="amount_1">
	<input type="hidden" value="1" name="quantity_1">
	<input type="hidden" value="1" name="weight_1">
    <input type="hidden" value="Delivery Date" name="on0_1">
	<input type="hidden" value="2011-04-22" name="os0_1">
	
	<input type="hidden" value="Shipping, Handling, Discounts &amp; Taxes" name="item_name_2">
	<input type="hidden" value="" name="item_number_2">
	<input type="hidden" value="5" name="amount_2">
	<input type="hidden" value="1" name="quantity_2">
	<input type="hidden" value="0" name="weight_2">
	<input type="hidden" value="5.00" name="amount">
	<input type="hidden" value="USD" name="currency_code">
	<input type="hidden" value="<?php if(isset($_POST['first_name'])) {echo trim($_POST['first_name']);} else echo 'Abhijit'; ?>" name="first_name">
	<input type="hidden" value="<?php if(isset($_POST['last_name'])) {echo trim($_POST['last_name']);} else echo 'Pal'; ?>" name="last_name">
	<input type="hidden" value="<?php if(isset($_POST['address1'])) {echo trim($_POST['address1']);} else echo '43 N K Guin Lane, Srerampur'; ?>" name="address1">
	<input type="hidden" value="<?php if(isset($_POST['city'])) {echo trim($_POST['city']);} else echo 'Kolkata'; ?>" name="city">
	<input type="hidden" value="<?php if(isset($_POST['zip'])) {echo trim($_POST['zip']);} else echo '712409'; ?>" name="zip">
	<input type="hidden" value="<?php if(isset($_POST['country'])) {echo trim($_POST['country']);} else echo 'India'; ?>" name="country">
	<input type="hidden" value="<?php if(isset($_POST['email'])) {echo trim($_POST['email']);} else echo 'abhijit@technokrats.in'; ?>" name="email">
	
	<input type="hidden" value="http://abhijitpal.in/paypal_standard/success.php" name="return">
	<input type="hidden" value="http://abhijitpal.in/paypal_standard/callback.php?item_price=<?php echo $_SESSION['all_product_price']; ?>&email=<?php echo $_SESSION['business_email']; ?>&first_name=<?php echo $_SESSION['first_name']; ?>&last_name=<?php echo $_SESSION['last_name']; ?>&order_id=<?php echo $_SESSION['order_id'];?>" name="notify_url">
	<input type="hidden" value="http://abhijitpal.in/paypal_standard/cancle.php" name="cancel_return">
	<input type="hidden" name="cmd" value="_cart" />
	<input type="hidden" name="upload" value="1" />
	<input type="hidden" name="no_note" value="1" />
	<input type="hidden" name="charset" value="utf-8" />
	<!--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"-->
    <!--input type="submit" name="submit" value="Confirm Order"-->
   
</form>
<?php
}
else
{
	echo 'Please go to index.php page and fill the form';
}
?>
<script type="text/javascript">
window.onload = function(){
  document.forms['pay_with_paypal'].submit()

}
</script>

Step 4: Now you are in paypal website. Pay with your paypal account information and make payment.

After hitting Pay Now button payment will send user info and all payment related information to your notify_url. For me it is callback.php

<?php
mysql_connect('localhost','root',''); /* Put you database information */
mysql_select_db('paypal');
$request = 'cmd=_notify-validate';
		
foreach ($_POST as $key => $value) {
	$request .= '&' . $key . '=' . urlencode(html_entity_decode($value, ENT_QUOTES, 'UTF-8'));
}
$curl = curl_init('https://www.paypal.com/cgi-bin/webscr'); /* This is for live transcation */
$curl = curl_init('https://www.sandbox.paypal.com/cgi-bin/webscr');  /* This is for sandbox transcation */
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $request);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($curl);
/* $fp = fopen('data.txt', 'w');
fwrite($fp, $request); */			
if (!$response) {
	$fp1 = fopen('error.txt', 'w');
	fwrite($fp1, 'PP_STANDARD :: CURL failed ' . curl_error($curl) . '(' . curl_errno($curl) . ')');
}	
if ((strcmp($response, 'VERIFIED') == 0 || strcmp($response, 'UNVERIFIED') == 0) && isset($_POST['payment_status']) && ((float)$_POST['mc_gross'] == $_GET['item_price'])) {
	switch($_POST['payment_status']) {
		case 'Canceled_Reversal':
			$status = $_POST['payment_status'];
			break;
		case 'Completed':
			if ((strtolower($_POST['receiver_email']) == strtolower($_GET['email'])) && ((float)$_POST['mc_gross'] == $_GET['item_price'])) {
				$status = $_POST['payment_status'];
			} else {
				fwrite($fp1, 'PP_STANDARD :: RECEIVER EMAIL MISMATCH! ' . strtolower($_GET['email']));
			}
			break;
		case 'Denied':
			$status = $_POST['payment_status'];
			break;
		case 'Expired':
			$status = $_POST['payment_status'];
			break;
		case 'Failed':
			$status = $_POST['payment_status'];
			break;
		case 'Pending':
			$status = $_POST['payment_status'];
			break;
		case 'Processed':
			$status = $_POST['payment_status'];
			break;
		case 'Refunded':
			$status = $_POST['payment_status'];
			break;
		case 'Reversed':
			$status = $_POST['payment_status'];
			break;	 
		case 'Voided':
			$status = $_POST['payment_status'];
			break;								
	}
	
	if ($status) {
		confirm($_GET['order_id'], $status, $response, $request, $_POST['payer_email']);
                /* You can send mail to you customer here */
	} 
}
			
curl_close($curl);
function confirm($order_id, $status, $response, $request, $email)
{
	/* Insert Into database table  */ 
	$sql = 'INSERT INTO payment_history SET order_id="'.$order_id.'", first_name="'.$_GET['first_name'].'", last_name ="'.$_GET['last_name'].'", email_address = "'.$email.'", product_price = "'.$_GET['item_price'].'", status ="'.$status.'", response = "'.$response.'", all_data = "'.$request.'"';
	
	mysql_query($sql) or die(mysql_error());
}
?>

Step 5: Create success.php where user will be redirected by paypal after successful paypal.

<?php
echo 'Success';
?>

Step 6: Create cancle.php

If user click on “Cancel and return to abhijit pal’s Test Store.” before payment they will be redirected to this page.

<?php
header('Location: index.php?text=Your transaction is failed');
?>

So now you can easily do paypal standard integration using PHP
Demo
Download

Spread the love
  •  
  •  
  •  
  • 2
  •  
  •  
  •  
  •  
  •  
  •  
    2
    Shares