Step 1 - Setup Paypal Account

You might also like

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 10

PayPal is the most popular payment service on the web so being able to integrate your website with PayPals

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.

Step 1 Setup PayPal Account


Sign up for a PayPal account if you dont already have one. Select an appropriate account type, either Personal or Business. Once you have a registered PayPal account your account must be setup correctly to use IPN. Select edit profile from your PayPal account and check the following settings.

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

Step 2 Simple HTML Form


Your website must now send all the required values to PayPal so that the payment can be processed. The following code example demonstrates a basic form that we will use to send the values:

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.

Step 3 Payments.php (The Request)


The payment.php page will be used to handle the outgoing request to PayPal and also to handle the incoming response after the payment has been processed. The following sample code shows the querystring being constructed before it is posted to PayPal. Here you can specify the following values:

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.

view source print?


1 // Database variables 2 $host = "localhost"; //database location 3 $user = ""; //database username 4 $pass = ""; //database password 5 $db_name = ""; //database name 6 7 // PayPal settings 8 $paypal_email = 'paypal@example.com'; 9 $return_url = 'http://example.com/payment-successful.htm'; 10 $cancel_url = 'http://example.com/payment-cancelled.htm'; 11 $notify_url = 'http://example.com/paypal/payments.php'; 12 13 $item_name = 'Test Item'; 14 $item_amount = 5.00; 15 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 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

// Redirect to paypal IPN

header('location:https://www.sandbox.paypal.com/cgi-bin/webscr'. $querystring); 51 exit(); 52 53 }else{ 54 55 } // Response from PayPal

Step 4 Payments.php (The Response)


The next part of the payments.php page handles the response from PayPal. The response is re-assigned to variables and then posted back to PayPal for verification using fsockopen. If the response is VERIFIED then a validation check can be performed. The check_txnid and check_price functions are called to check that the correct Transaction ID and Price have been returned. The updatePayments function can finally be called to store the details of the payment in the payments table (Step 6). view source print?
1 // Database variables 2 $host = "localhost"; //database location 3 $user = ""; //database username 4 $pass = ""; //database password 5 $db_name = ""; //database name 6 7 // PayPal settings 8 $paypal_email = 'paypal@example.com'; 9 $return_url = 'http://example.com/payment-successful.htm'; 10 $cancel_url = 'http://example.com/payment-cancelled.htm'; 11 $notify_url = 'http://example.com/paypal/payments.php'; 12 13 $item_name = 'Test Item'; 14 $item_amount = 5.00; 15

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

$fp = fsockopen ('ssl://www.sandbox.paypal.com', 443, $errno,$errstr,

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 }

}else if (strcmp ($res, "INVALID") == 0) {

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

if so uncomment the below code

$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); }

Step 6 Setting Up The Payments Table

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

9 ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

You might also like