Professional Documents
Culture Documents
Step 1 - Setup Paypal Account
Step 1 - Setup Paypal Account
Step 1 - Setup Paypal Account
Instant Payment Notification Service (IPN) is essential if you need to process payments through your website. There are 3 main parts to the PayPal IPN system. 1. A webpage that initiates a request to PayPal to make a payment. 2. A PHP page on your webserver that PayPal calls to notify you that payment has been made. 3. A webpage that confirms the above payment and continues on to the next phase of your web application, such as a Thank You page. Parts 1 and 3 are accessible by customers on your website. Part 2 is only visible to PayPal. The diagram below illustrates the interaction between your customer, PayPal and your website.
Under Selling Preferences >> Instant Payment Notification Preferences o Set the IPN value to On o Set the IPN URL to the PHP page containing the IPN code shown in steps 3 & 4 of this tutorial. (http://www.example.com/payment.php) Under Selling Preferences >> payment receiving preferences o Block payments from users who pay with echeck. (This is because these will not be instant payments) Under account information >> email o Note down your primary email address. This email will be visible to users so make it a professional one. Users may feel apprehensive about sending money to an e-mail address with the domain hotmail.com or Yahoo.com etc
1 <form id="paypal_form" class="paypal" action="payments.php"method="post"> 2 3 4 5 6 7 8 9 10 11 <input name="cmd" type="hidden" value="_xclick" /> <input name="no_note" type="hidden" value="1" /> <input name="lc" type="hidden" value="UK" /> <input name="currency_code" type="hidden" value="GBP" /> <input name="bn" type="hidden" value="PPBuyNowBF:btn_buynow_LG.gif:NonHostedGuest" /> <input name="first_name" type="hidden" value="Customer's First Name" /> <input name="last_name" type="hidden" value="Customer's Last Name" /> <input name="payer_email" type="hidden"value="customer@example.com" /> <input name="item_number" type="hidden" value="123456" /> <input type="submit" value="Submit Payment" />
12 </form>
The business name, price, submit type, notify URL and other sensitive values will be sent during the next step.
A full list of the values to send can be found at the PayPal website under the title A Sample IPN Message and Response.
Business ($paypal_email) Enter the email address of your PayPal account. Item name ($item_name) The name of the item being purchased. Amount ($item_amount) The price of the item. Return ($return_url) The address to return to after a successful payment. Cancel Return ($cancel_url) the address to return to after a cancelled payment. Notify URL ($notify_url) The address of the payments.php page on your website. Custom Any other data to be sent and returned with the PayPal request.
17 include("functions.php"); 18 19 //Database Connection 20 $link = mysql_connect($host, $user, $pass); 21 mysql_select_db($db_name); 22 23 // Check if paypal request or response 24 if (!isset($_POST["txn_id"]) && !isset($_POST["txn_type"])){ 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 // Append querystring with custom field //$querystring .= "&custom=".USERID; ; // Append paypal return addresses $querystring .="return=".urlencode(stripslashes($return_url))."&"; $querystring .="cancel_return=".urlencode(stripslashes($cancel_url))."&" $querystring .= "notify_url=".urlencode($notify_url); } //loop for posted values and append to querystring foreach($_POST as $key => $value){ $value = urlencode(stripslashes($value)); $querystring .= "$key=$value&"; //The item name and amount can be brought in dynamically by querying the $_POST['item_number'] variable. $querystring .= "item_name=".urlencode($item_name)."&"; $querystring .= "amount=".urlencode($item_amount)."&"; html // Append amount& currency () to quersytring so it cannot be edited in // Firstly Append paypal account to querystring $querystring .= "?business=".urlencode($paypal_email)."&";
49 50
16 // Include Functions 17 include("functions.php"); 18 19 //Database Connection 20 $link = mysql_connect($host, $user, $pass); 21 mysql_select_db($db_name); 22 23 // Check if paypal request or response 24 if (!isset($_POST["txn_id"]) && !isset($_POST["txn_type"])){ 25 // Request from step 3 26 }else{ 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 // post back to PayPal system to validate // assign posted variables to local variables $data['item_name'] $data['item_number'] $data['payment_status'] $data['payment_amount'] $data['payment_currency'] $data['txn_id'] $data['receiver_email'] $data['payer_email'] $data['custom'] = $_POST['item_name']; = $_POST['item_number']; = $_POST['payment_status']; = $_POST['mc_gross']; = $_POST['mc_currency']; = $_POST['txn_id']; = $_POST['receiver_email']; = $_POST['payer_email']; = $_POST['custom']; } // read the post from PayPal system and add 'cmd' $req = 'cmd=_notify-validate'; foreach ($_POST as $key => $value) { $value = urlencode(stripslashes($value)); $value = preg_replace('/(.*[^%^0^D])(%0A)(.*)/i','${1}%0D%0A${3}', $value);// IPN fix $req .= "&$key=$value"; // Response from Paypal
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 30);
$header = "POST /cgi-bin/webscr HTTP/1.0\r\n"; $header .= "Content-Type: application/x-www-form-urlencoded\r\n"; $header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
if (!$fp) { // HTTP ERROR } else { mail('ash@evoluted.net', '0', '0'); fputs ($fp, $header . $req); while (!feof($fp)) { $res = fgets ($fp, 1024); if (strcmp ($res, "VERIFIED") == 0) { // Validate payment (Check unique txnid & correct price) $valid_txnid = check_txnid($data['txn_id']); $valid_price = check_price($data['payment_amount'], $data['item_number']); // PAYMENT VALIDATED & VERIFIED! if($valid_txnid && $valid_price){ $orderid = updatePayments($data); if($orderid){ // Payment has been made & successfully inserted into the Database }else{ // Error inserting into DB // E-mail admin or alert user } }else{ // Payment made but data has been changed // E-mail admin or alert user }
83 84 85 86 87 88 89 90 } } fclose ($fp); } } // PAYMENT INVALID & INVESTIGATE MANUALY! // E-mail admin or alert user
Step 5 Functions.php
The payments.php page calls upon a number of functions used to validate the returned data and store the response in the database. view source print?
1 // functions.php 2 function check_txnid($tnxid){ 3 global $link; 4 5 6 7 8 9 10 11 12 } 13 14 function check_price($price, $id){ 15 $valid_price = false; 16 17 /* you could use the below to check whether the correct price has been paid for the product } return $valid_txnid; return true; $valid_txnid = true; //get result set $sql = mysql_query("SELECT * FROM `payments` WHERE txnid = '$tnxid'", $link); if($row = mysql_fetch_array($sql)) { $valid_txnid = false;
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 } 33
$sql = mysql_query("SELECT amount FROM `products` WHERE id = '$id'"); if (mysql_numrows($sql) != 0) { while ($row = mysql_fetch_array($sql)) { $num = (float)$row['amount']; if($num == $price){ $valid_price = true; } } } return $valid_price; */ return true;
34 function updatePayments($data){ 35 36 37 38 39 40 41 42 43 44 45 46 } global $link; if(is_array($data)){ $sql = mysql_query("INSERT INTO `payments` (txnid, payment_amount, payment_status, itemid, createdtime) VALUES ( '".$data['txn_id']."' , '".$data['payment_amount']."' , '".$data['payment_status']."' , '".$data['item_number']."' , '".date("Y-m-d H:i:s")."' )", $link); return mysql_insert_id($link); }
To store payment details in the database a payments table must be created in your database. The following MYSQL code will create a payments table. view source print?
1 CREATE TABLE IF NOT EXISTS `payments` ( 2 3 4 5 6 7 8 `id` int(6) NOT NULL AUTO_INCREMENT, `txnid` varchar(20) NOT NULL, `payment_amount` decimal(7,2) NOT NULL, `payment_status` varchar(25) NOT NULL, `itemid` varchar(25) NOT NULL, `createdtime` datetime NOT NULL, PRIMARY KEY (`id`)