Sie sind auf Seite 1von 8

How to integrate PayPal using PHP Overview

The idea behind PayPal is using encryption software to allow users to make financial transactions between computers. Now a day this has turned into one of the world's primary methods of e-payment. PayPal is an e-payment service that allows individuals, businesses to transfer funds electronically. We can use it to pay for online auctions, purchase goods and services, or to make donations. We can even use it to send cash.

How PayPal Works?


Using Website Payments Standard, HTML coding and PHP we can integrate PayPal in the website or eCommerce application. With Website Payments Standard, need to add buttons for different kinds of payments to the webpages. Users click the payment buttons to pay for their purchases.

What is IPN in PayPal?


IPN - InstanPaymentNotification notifies you when an event occurs that affects a transaction. Typically, these events represent various kinds of payments; however, the events may also represent authorizations, Fraud Management Filter actions and other actions, such as refunds, disputes, and charge backs. IPN is a message service that PayPal uses to notify you about events.

Note: just create two files with given code and it works.

How to integrate PayPal


Create one class file "paypal.class.php". (copy this code in file)
<?php /********* PayPal with IPN in PHP **********/ class paypal_class { var $error; // holds the error encountered var $ipn_log; // log IPN results var $ipn_log_file; // filename of the IPN log var $ipn_response; // holds the IPN response from PayPal var $ipn_data = array(); // contains the POST values for IPN var $fields = array(); // holds the fields to submit to PayPal

function paypal_class() { // constructor. $this->paypal_url = 'https://www.paypal.com/cgi-bin/webscr'; $this->error = ''; $this->ipn_log_file = '.ipn_results.log'; $this->ipn_log = true; $this->ipn_response = ''; $this->add_field('rm','2'); // Return method = POST $this->add_field('cmd','_xclick'); } function add_field($field, $value) { // adds a key=>value pair to the fields array $this->fields["$field"] = $value; } function submit_paypal_post() { // generates an HTML page consisting of // a form with hidden elements which is submitted to PayPal echo "<html>\n"; echo "<head><title>Processing...</title></head>\n"; echo "<body onLoad=\"document.forms['paypal_form'].submit();\">\n"; echo "<center><h2>Please wait, your order is being processed and you"; echo " will be redirected to the paypal website.....</h2></center>\n"; echo "<form method=\"post\" name=\"paypal_form\" "; echo "action=\"".$this->paypal_url."\">\n"; foreach ($this->fields as $name => $value) { echo "<input type=\"hidden\" name=\"$name\" value=\"$value\"/>\n"; } echo "<center><br/><br/>If you are not automatically redirected to "; echo "paypal within 5 seconds...<br/><br/>\n"; echo "<input type=\"submit\" value=\"Click Here\"></center>\n"; echo "</form>\n"; echo "</body></html>\n"; } function validate_ipn() { // parse the paypal URL $url_parsed=parse_url($this->paypal_url); // generate the post string from the _POST vars $post_string = ''; foreach ($_POST as $field=>$value) { $this->ipn_data["$field"] = $value; $post_string .= $field.'='.urlencode (stripslashes ($value)).'&'; } $post_string.="cmd=_notify-validate"; // open the connection to paypal $fp = fsockopen($url_parsed[host],"80",$err_num,$err_str,30); if(!$fp) { // Print the error if not able to open the connection. $this->error = "Error no. $errnum: $errstr";

$this->log_ipn_results(false); return false; } else { // Post data back to paypal fputs($fp, "POST $url_parsed[path] HTTP/1.1\r\n"); fputs($fp, "Host: $url_parsed[host]\r\n"); fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n"); fputs($fp, "Content-length: ".strlen($post_string)."\r\n"); fputs($fp, "Connection: close\r\n\r\n"); fputs($fp, $post_string . "\r\n\r\n"); // loop through the response from the server and append to variable while(!feof($fp)) { $this->ipn_response .= fgets($fp, 1024); } fclose($fp); // close connection } if (eregi("VERIFIED",$this->ipn_response)) { // Valid IPN. $this->log_ipn_results(true); return true; } else { // Invalid IPN. $this->error = 'IPN Validation Failed.'; $this->log_ipn_results(false); return false; } } function log_ipn_results($success) { if (!$this->ipn_log) return; // Timestamp $text = '['.date('m/d/Y g:i A').'] - '; // Success or failure if ($success) $text .= "SUCCESS!\n"; else $text .= 'FAIL: '.$this->error."\n"; // Log the POST variables $text .= "IPN POST Values from Paypal:\n"; foreach ($this->ipn_data as $key=>$value) { $text .= "$key=$value, "; } // response from the paypal server $text .= "\nIPN Response from Paypal Server:\n ".$this->ipn_response; // Write to log $fp=fopen($this->ipn_log_file,'a'); fwrite($fp, $text . "\n\n"); fclose($fp); // close file } } ?> <?php

/********* PayPal with IPN in PHP **********/ class paypal_class { var $error; // holds the error encountered var $ipn_log; // log IPN results var $ipn_log_file; // filename of the IPN log var $ipn_response; // holds the IPN response from PayPal var $ipn_data = array(); // contains the POST values for IPN var $fields = array(); // holds the fields to submit to PayPal function paypal_class() { // constructor. $this->paypal_url = 'https://www.paypal.com/cgi-bin/webscr'; $this->error = ''; $this->ipn_log_file = '.ipn_results.log'; $this->ipn_log = true; $this->ipn_response = ''; $this->add_field('rm','2'); // Return method = POST $this->add_field('cmd','_xclick'); } function add_field($field, $value) { // adds a key=>value pair to the fields array $this->fields["$field"] = $value; } function submit_paypal_post() { // generates an HTML page consisting of // a form with hidden elements which is submitted to PayPal echo "<html>\n"; echo "<head><title>Processing...</title></head>\n"; echo "<body onLoad=\"document.forms['paypal_form'].submit();\">\n"; echo "<center><h2>Please wait, your order is being processed and you"; echo " will be redirected to the paypal website.....</h2></center>\n"; echo "<form method=\"post\" name=\"paypal_form\" "; echo "action=\"".$this->paypal_url."\">\n"; foreach ($this->fields as $name => $value) { echo "<input type=\"hidden\" name=\"$name\" value=\"$value\"/>\n"; } echo "<center><br/><br/>If you are not automatically redirected to "; echo "paypal within 5 seconds...<br/><br/>\n"; echo "<input type=\"submit\" value=\"Click Here\"></center>\n"; echo "</form>\n"; echo "</body></html>\n"; } function validate_ipn() { // parse the paypal URL $url_parsed=parse_url($this->paypal_url); // generate the post string from the _POST vars $post_string = ''; foreach ($_POST as $field=>$value) { $this->ipn_data["$field"] = $value;

$post_string .= $field.'='.urlencode (stripslashes ($value)).'&'; } $post_string.="cmd=_notify-validate"; // open the connection to paypal $fp = fsockopen($url_parsed[host],"80",$err_num,$err_str,30); if(!$fp) { // Print the error if not able to open the connection. $this->error = "Error no. $errnum: $errstr"; $this->log_ipn_results(false); return false; } else { // Post data back to paypal fputs($fp, "POST $url_parsed[path] HTTP/1.1\r\n"); fputs($fp, "Host: $url_parsed[host]\r\n"); fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n"); fputs($fp, "Content-length: ".strlen($post_string)."\r\n"); fputs($fp, "Connection: close\r\n\r\n"); fputs($fp, $post_string . "\r\n\r\n"); // loop through the response from the server and append to variable while(!feof($fp)) { $this->ipn_response .= fgets($fp, 1024); } fclose($fp); // close connection } if (eregi("VERIFIED",$this->ipn_response)) { // Valid IPN. $this->log_ipn_results(true); return true; } else { // Invalid IPN. $this->error = 'IPN Validation Failed.'; $this->log_ipn_results(false); return false; } } function log_ipn_results($success) { if (!$this->ipn_log) return; // Timestamp $text = '['.date('m/d/Y g:i A').'] - '; // Success or failure if ($success) $text .= "SUCCESS!\n"; else $text .= 'FAIL: '.$this->error."\n"; // Log the POST variables $text .= "IPN POST Values from Paypal:\n"; foreach ($this->ipn_data as $key=>$value) { $text .= "$key=$value, "; } // response from the paypal server

$text .= "\nIPN Response from Paypal Server:\n ".$this->ipn_response; // Write to log $fp=fopen($this->ipn_log_file,'a'); fwrite($fp, $text . "\n\n"); fclose($fp); // close file } } ?>

Include this class file into paypal.php. code of paypal.php is as follows


<?php require_once('paypal.class.php'); // include the class file $p = new paypal_class; // initiate an instance $p->paypal_url = "https://www.sandbox.paypal.com/cgi-bin/webscr"; //test url //'https://www.paypal.com/cgi-bin/webscr'; // paypal url $this_script = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']; // if no action variable, set 'process' as default action if (empty($_GET['action'])) $_GET['action'] = 'process'; switch ($_GET['action']) { case 'process': // Process and order... $p->add_field('business', 'PAYPAL EMAIL ADDRESS'); $p->add_field('return', $this_script.'?action=success'); $p->add_field('cancel_return', $this_script.'?action=cancel'); $p->add_field('notify_url', $this_script.'?action=ipn'); $p->add_field('item_name', 'PAYPAL TEST'); // 'ITEM NAME' $p->add_field('amount', '100'); // 'ITEM AMOUNT' $p->add_field('currency_code', 'USD');//CURRENCY VALUE USD/EUR $p->submit_paypal_post(); // submit the fields to paypal break; case 'success': // successful order... echo "<html> <head><title>Success....</title></head> <body> <h2>Thank you for your order!</h2>"; foreach ($_POST as $key => $value) { echo "$key: $value<br>"; } echo "</body></html>"; break; case 'cancel': // Canceled Order... echo "<html> <head><title>Canceled</title></head> <body><h2>The order was canceled.</h2>"; echo "</body></html>";

break; case 'ipn': // For IPN validation... if ($p->validate_ipn()) { $subject = 'Instant Payment Notification - Recieved Payment'; $to = 'EMAIL ADDRESS'; $body="An instant payment notification was successfully recieved\n"; $body .= "from ".$p->ipn_data['payer_email']." on ".date('m/d/Y'); $body .= "\n\nDetails:\n"; foreach ($p->ipn_data as $key => $value) { $body .= "\n$key: $value"; } @mail($to, $subject, $body); } break; } ?>

Call paypal.php file on payment button of your web application

Source of this tutorial: http://techforum4u.com/content.php/222-How-to-integrate-PayPal-using-PHP It will only redirect your customers to paypal site.

Das könnte Ihnen auch gefallen