天天看點

paypal支付代碼-PHP

aypal支付原理

首先根據paypal的要求構造出一個表單,然後送出到paypal去處理,paypal處理後會以隐藏方式post資料到商家網站指定的頁面,在商家網站指定的頁面,我們先要把payapal的post到該頁面上的值進行處理,然後再投遞到paypal上去驗證,如果是正确的,則paypal會傳回VERIFIED,否則傳回INVALID.

看不懂原理沒有關系,直接看代碼。

下面是構造的送出到PAYPAL得表單。

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0Transitional//EN”“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>

<htmlxmlns=”http://www.w3.org/1999/xhtml”>

<head>

<meta http-equiv=”Content-Type” content=”text/html;charset=utf-8″ />

<title>無标題文檔</title>

</head>

<body>

<form style=”text-align:center;”action=”https://www.sandbox.paypal.com/cgi-bin/webscr”method=”post”>

<input type=’hidden’ name=’cmd’value=’_xclick’>

<input type=’hidden’ name=’business’value=’[email protected]’>

<input type=’hidden’ name=’item_name’value=’201001114262121′>

<input type=’hidden’ name=’amount’value=’1.00′>

<input type=’hidden’ name=’currency_code’value=’USD’>

<input type=’hidden’ name=’return’value=’http://www.xxx.com/return.php’>

<input type=’hidden’ name=’invoice’value=’82′>

<input type=’hidden’ name=’charset’value=’utf-8′>

<input type=’hidden’ name=’no_shipping’value=’1′>

<input type=’hidden’ name=’no_note’value=”>

<input type=’hidden’ name=’notify_url’value=’http://www.xxx.com/return.php’>

<input type=’hidden’ name=’rm’value=’82′>

<input type=’hidden’ name=’cancel_return’value=’http://www.xxx.com/index.html’>

<input type=’submit’ value=’立即使用 paypal支付’>

</form>

</body>

</html>

下面是處理代碼:

<?php

$merchant_id = ’[email protected]’; ///擷取商戶paypal賬戶

// read the post from PayPal system and add ‘cmd’

$req = ‘cmd=_notify-validate’;

foreach ($_POST as $key => $value)

{

$value = urlencode(stripslashes($value));

$req .= “&$key=$value”;

}

// post back to PayPal system to validate

$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 (‘www.sandbox.paypal.com’, 80, $errno, $errstr,30); //如果是測試賬戶,則投遞到www.sandbox.paypal.com,否則投遞到www.paypal.com

// assign posted variables to local variables

$item_name = $_POST['item_name'];

$item_number = $_POST['item_number'];

$payment_status = $_POST['payment_status'];

$payment_amount = $_POST['mc_gross'];

$payment_currency = $_POST['mc_currency'];

$txn_id = $_POST['txn_id'];

$receiver_email = $_POST['receiver_email'];

$payer_email = $_POST['payer_email'];

$order_sn = $_POST['invoice'];

$memo = !empty($_POST['memo']) ? $_POST['memo'] : ”;

//$action_note = $txn_id . ‘(’ . $GLOBALS['_LANG']['paypal_txn_id']. ‘)’ . $memo;

if (!$fp)

{

fclose($fp);

return false;

}

else

{

fputs($fp, $header . $req);

while (!feof($fp))

{

$res = fgets($fp, 1024);

if (strcmp($res, ‘VERIFIED’) == 0)

{

//付款成功的代碼

}

elseif (strcmp($res, ‘INVALID’) == 0)

{

//付款失敗的代碼

fclose($fp);

return false;

}

}

}

需要注意的是上面是用的paypal的sandbox.

原文位址:http://paypal999.blog.163.com/blog/static/13737488320107306370292/