簡單整理一下PHP項目整合PayPal支付功能。
一、表單的構建:
<form method="post" name="form" action="https://www.paypal.com/cgi-bin/webscr"> <input type="hidden" name="rm" value="2"/> <input type="hidden" name="cmd" value="_xclick"/> <input type="hidden" name="business" value="商家賬號"/> <input type="hidden" name="return" value="返回網址"/> <input type="hidden" name="cancel_return" value="取消返回網址"/> <input type="hidden" name="notify_url" value="用於接收PayPal發送的即時付款通知的URL,必須是有效的URL"/> <input type="hidden" name="item_name" value="物品名稱"/> <input type="hidden" name="item_number" value="可用於跟蹤購買或捐贈的傳遞變量,在付款完成時傳回給您"/> <input type="hidden" name="amount" value="物品的價格(購物車中所有物品的總價格"/> <input type="hidden" name="currency_code" value="幣種"/> </form>
二、IPN驗證部分
<?php
class paypal {
var $ipn_data = array(); // array contains the POST values for IPN
var $fields = array(); // PayPal接受到客戶的付款後,Paypal會向網站POST回客戶提交的表單信息,
// 必須將收到的POST信息對原樣返回給PayPal進行驗證,
// 內容有:item_name=iPhone 6,quantity=1,amount=499,currency_code=USD等所有表單信息,
// 在調用驗證IPN之前事先需要初始化好
var $paypal_url = 'https://www.paypal.com/cgi-bin/webscr';//sandbox:https://www.sandbox.paypal.com/cgi-bin/webscr
function validate_ipn() {//驗證IPN
// parse the paypal URL
$url_par=parse_url($this->paypal_url);
// generate the post string from the _POST vars aswell as load the
// _POST vars into an arry so we can play with them from the calling
// script.
$post_str = '';
foreach ($_POST as $field=>$value) {
$this->ipn_data["$field"] = $value;
$post_str .= $field.'='.urlencode(stripslashes($value)).'&';
}
$post_str.="cmd=_notify-validate"; // append ipn command
// open the connection to paypal
$fp = fsockopen($url_par[host],"80",$errnum,$errstr,30);
if(!$fp) {
// could not open the connection.
return false;
} else {
// Post the data back to paypal
fputs($fp, "POST ".$url_par[path]." HTTP/1.1\r\n");
fputs($fp, "Host: ".$url_par[host]."\r\n");
fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
fputs($fp, "Content-length: ".strlen($post_str)."\r\n");
fputs($fp, "Connection: close\r\n\r\n");
fputs($fp, $post_str . "\r\n\r\n");
// loop through the response from the server and append to variable
while(!feof($fp)) {
$this->validate_ipn_response .= fgets($fp, 1024);
}
fclose($fp); // close connection
}
if (eregi("VERIFIED",$this->validate_ipn_response)) {
return true;
} else {
return false;
}
}
}
?>
即時付款通知(IPN)示意圖如下:

1) 客戶點擊“付款”按鈕向您的賬戶付款;
2) PayPal 接受到客戶的付款後,向您的服務器指定的 URL 通過 POST 方式發送 IPN;
3) 在您的服務器收到 IPN 之後,您必須將收到的 POST 信息對原樣返回給 PayPal 進行驗證,PayPal 通過此方法幫您防范欺騙或“中間人”攻擊;(對IPN信息的驗證過程我們稱之為通知確認)
4) PayPal 返回驗證信息,通過驗證為 VERIFIED,不通過則為 INVALD;
5) 根據驗證信息處理付款明細。
相關資料:
開發者:https://developer.paypal.com/
即時付款通知:https://www.paypal-biz.com/development/documentation/PayPal_IPN&PDT_Guide_V1.0.pdf
paypal標准版:https://www.paypal-biz.com/development/documentation/PayPal_WPS_Guide_CN_V2.0.pdf