Paypal付款功能网站集成简明教程 示例代码

随着 paypal 的业务在国内的发展,越来越多的网站希望能将 paypal 集成到自己的购物网站中去。但开始做的时候,很多朋友发现, paypal 的接口比想象中的要麻烦的多。以前做过 taobao 接口、做过网银在线接口,也许是 taobao 和网银提供的接口参数和范例比较简单易懂,或者说写的教程比较本地化,所以基本上有点程序基础朋友的都能做完。遇上了 paypal ,脑袋就大了,调试比较麻烦那。
Paypal 专门开发了 Sandbox 给开发人员进行开发测试,首先到 https://developer.paypal.com/ 注册一个开发帐号,再进入 Sandbox 建立测试用的 Paypal 虚拟帐号(至少应该建立一个高级账户的和一个个人账户),这种账号注册方法和 Paypal 的流程一样,信息可以是假的,包括银行帐号、信用卡(其实 Paypal Sandbox 会自动生成一些随机的号码)。

接着激活 Paypal Sandbox 的虚拟帐号,注意,这里不管你在 Paypal Sanbox 注册时填什么邮件地址,有任何发送到虚拟帐号所填邮箱的邮件都存会在开发帐号的管理界面中的 Email 页(导航栏上有)中。登录 Sandbox 的虚拟 Paypal 环境,还需要验证虚拟帐号的银行,这里可以随便填,然后通过 Add Funds 来给账户充值(想填多少填多少)。

然后,还需要激活 IPN 的选项,在高级账户的 Profile 设置页面中,点击,然后点击 Edit 按钮,打开 IPN ,这里如果你使用的是固定的 IPN Handle ,可以直接将地址填入。
接下来,我们测试的时候,应该将 Paypal 接口的地址设置为 https://www.sandbox.paypal.com/cgi-bin/webscr
最后基本的流程为:
用户在我们的网站上选择商品、放入购物车,然后检查准备支付网站根据购物车中的商品,生成 Paypal 的支付表单(也是提交到上面 IPN 用的 Paypal 接口地址),包含了此次交易的一些信息。并在自己的数据库中生成一张订单记录。
Paypal Session 中记录下这些交易信息,用户用 Paypal 账户登录 Paypal Sandbox Sandbox 的虚拟帐号),复查明细,点击 Pay 按钮, Paypal 进行交易处理,如果我们的 Paypal 收款帐号在接受帐款上没有什么问题(没有特别的需要 Accept 的地方),交易完成,那么 Paypal 会发送一个 IPN ,并发送提示邮件。 我们 IPN Handler 接受到信息,首先向 Paypal 进行校验,如果信息正确,然后根据信息和自己数据库中进行比对,如果无误,可以将支付信息保存,并修改订单状态。
然后 Paypal 会显示一个界面表示交易完成,此时如果用户点击 “Return” 按钮, Paypal 会将用户送回我们网站指定地点。
网站迎接用户回来,向用户表示感谢,并进行提醒,给出订单号等等。
别忘了,还需要在 paypal 里设置一大堆的参数 . 比较麻烦。
附上网站主流的集中程序开发语言范例:
ASP/VBScript
 
 
Dim authToken, txToken
Dim query
Dim objHttp
Dim sQuerystring
Dim sParts, iParts, aParts
Dim sResults, sKey, sValue
Dim i, result
Dim firstName, lastName, itemName, mcGross, mcCurrency
authToken = "Dc7P6f0ZadXW-U1X8oxf8_vUK09EHBMD7_53IiTT-CfTpfzkN0nipFKUPYy"
txToken = Request.Querystring("tx")
query = "cmd=_notify-synch&tx=" & txToken &
"&at=" & authToken
set objHttp = Server.CreateObject("Microsoft.XMLHTTP")
' set objHttp = Server.CreateObject("Msxml2.ServerXMLHTTP")
objHttp.open "POST", "http://www.paypal.com/cgi-bin/webscr", false
objHttp.setRequestHeader "Content-type", "application/x-www-form-urlencoded"
objHttp.Send query
sQuerystring = objHttp.responseText
If Mid(sQuerystring,1,7) = "SUCCESS" Then
sQuerystring = Mid(sQuerystring,9)
sParts = Split(sQuerystring, vbLf)
iParts = UBound(sParts) - 1
ReDim sResults(iParts, 1)
For i = 0 To iParts
aParts = Split(sParts(i), "=")
sKey = aParts(0)
sValue = aParts(1)
sResults(i, 0) = sKey
sResults(i, 1) = sValue
Select Case sKey
Case "first_name"
firstName = sValue
Case "last_name"
lastName = sValue
Case "item_name"
itemName = sValue
Case "mc_gross"
mcGross = sValue
Case "mc_currency"
mcCurrency = sValue
End Select
Next
Response.Write("<p><h3>Your order has been received.</h3></p>")
Response.Write("<b>Details</b><br>")
Response.Write("<li>Name: " & firstName & " " & lastName & "</li>")
Response.Write("<li>Description: " & itemName & "</li>")
Response.Write("<li>Amount: " & mcCurrency & " " & mcGross & "</li>")
Response.Write("<hr>")
Else
'log for manual investigation
Response.Write("ERROR")
End If
%>
 
 

 
Cold Fusion
 
 
<cfset
authToken="Dc7P6f0ZadXW-U1X8oxf8_vUK09EHBMD7_53IiTT-CfTpfzkN0nipFKUPYy">
<cfset txToken = url.tx>
<cfset query="cmd=_notify-synch&tx=" & txToken &
"&at=" & authToken>
<CFHTTP url="https://www.paypal.com/cgi-bin/webscr?#query#"
method="GET"
resolveurl="false">
</CFHTTP>
<cfif left(#cfhttp.FileContent#,7) is "SUCCESS">
<cfloop list="#cfhttp.FileContent#"
index="curLine"
delimiters="#chr(10)#">
<cfif listGetAt(curLine,1,"=") is "first_name">
<cfset firstName=listGetAt(curLine,2,"=")>
</cfif>
<cfif listGetAt(curLine,1,"=") is "last_name">
<cfset lastName=listGetAt(curLine,2,"=")>
</cfif>
<cfif listGetAt(curLine,1,"=") is "item_name">
<cfset itemName=listGetAt(curLine,2,"=")>
</cfif>
<cfif listGetAt(curLine,1,"=") is "mc_gross">
<cfset mcGross=listGetAt(curLine,2,"=")>
</cfif>
<cfif listGetAt(curLine,1,"=") is "mc_currency">
<cfset mcCurrency=listGetAt(curLine,2,"=")>
</cfif>
</cfloop>
<cfoutput>
<p><h3>Your order has been received.</h3></p>
<b>Details</b><br>
<li>Name: #firstName# #lastName#</li>
<li>Description: #itemName#</li>
<li>Amount: #mcCurrency# #mcGross#</li>
<hr>
</cfoutput>
<cfelse>
ERROR
</cfif>
 
 

 
PERL
 
 
 
#!/usr/bin/perl -w

###
#
# PayPal PDT (Payment Data Transfer) CGI
#
###

use strict;
use CGI qw(:all unescape);
use CGI::Carp qw(fatalsToBrowser);

# These modules are required to make the secure HTTP request to PayPal.
use LWP::UserAgent;
use Crypt::SSLeay;

###
# CUSTOMIZE THIS: This is the seller's Payment Data Transfer authorization token.
#                  Replace this with the PDT token in "Website Payment Preferences"
under your account.
###

my $auth_token = "VUDGCF2EA5huqlEqbSLPbg0JY3F-Pokyf-99r2sZWPR4x7GkWZEa-zIG49O";

sub done_text {
    return (p('Your transaction has been completed, and a receipt for your purchase has been
emailed to you. You may log into your account at <a
href="https://www.paypal.com/">www.paypal.com</a> to view details of this transaction.'),
end_html());
}

print header(), start_html("Thank you for your purchase!");

# Set up the secure request to the PayPal server to fetch the transaction info
my $paypal_server = "www.paypal.com";

my $transaction = param("tx");

if (not $transaction) {
    print (h2("The transaction ID was not found."), done_text());

    exit();
}
my $query = join("&", "cmd=_notify-synch", "tx=$transaction", "at=$auth_token");

my $user_agent = new LWP::UserAgent;
my $request = new HTTP::Request("POST", $paypal_url);

$request->content_type("application/x-www-form-urlencoded");
$request->content($query);
# Make the request

my $result = $user_agent->request($request);

if ($result->is_error) {
    print(h1("An error was encountered"), br(), p("An error was encountered contacting the PayPal
server:"),
        $result->error_as_HTML, done_text());
    exit();
}

# Decode the response into individual lines and unescape any HTML escapes
my @response = split("\n", unescape($result->content));

# The status is always the first line of the response.
my $status = shift @response;

if ($status eq "SUCCESS") {
    # success
    my %transaction;

    foreach my $response_line (@response) {
      my ($key, $value) = split "=", $response_line;
      $transaction{$key} = $value;
    }
    # These are only some of the transaction details available; there are others.
    # You should print all the transaction details appropriate.
    print(h2("Here are the details of your purchase:"),
      ul(li("Customer Name: " . $transaction{'first_name'} . " " . $transaction{'last_name'}),
          li("Item: " . $transaction{'item_name'}),
          li("Amount: " . $transaction{'payment_gross'})));

} elsif ($status eq "FAIL") {
    print(h2("Unable to retrieve transaction details."));
    # failure
} else {
    # unknown error
    print(h2("Error retrieving transaction details."));
}

print done_text();
 
 

 
 

PHP
 
 
<?php
// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-synch';
$tx_token = $_GET['tx'];
$auth_token = "GX_sTf5bW3wxRfFEbgofs88nQxvMQ7nsI8m21rzNESnl_79ccFTWj2aPgQ0";
$req .= "&tx=$tx_token&at=$auth_token";
// 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.paypal.com', 80, $errno, $errstr, 30);
// If possible, securely post back to paypal using HTTPS
// Your PHP server will need to be SSL enabled
// $fp = fsockopen ('ssl://www.paypal.com', 443, $errno, $errstr, 30);
if (!$fp) {
// HTTP ERROR
} else {
fputs ($fp, $header . $req);
// read the body data
$res = '';
$headerdone = false;
while (!feof($fp)) {
$line = fgets ($fp, 1024);
if (strcmp($line, "\r\n") == 0) {
// read the header
$headerdone = true;
}
else if ($headerdone)
{
// header has been read. now read the contents
$res .= $line;
}
}
// parse the data
$lines = explode("\n", $res);
$keyarray = array();
if (strcmp ($lines[0], "SUCCESS") == 0) {
for ($i=1; $i<count($lines);$i++){
list($key,$val) = explode("=", $lines[$i]);
$keyarray[urldecode($key)] = urldecode($val);
}
// check the payment_status is Completed
// check that txn_id has not been previously processed
// check that receiver_email is your Primary PayPal email
// check that payment_amount/payment_currency are correct
// process payment
$firstname = $keyarray['first_name'];
$lastname = $keyarray['last_name'];
$itemname = $keyarray['item_name'];
$amount = $keyarray['payment_gross'];
echo ("<p><h3>Thank you for your purchase!</h3></p>");
echo ("<b>Payment Details</b><br>\n");
echo ("<li>Name: $firstname $lastname</li>\n");
echo ("<li>Item: $itemname</li>\n");
echo ("<li>Amount: $amount</li>\n");
echo ("");
}
else if (strcmp ($lines[0], "FAIL") == 0) {
// log for manual investigation
}
}
fclose ($fp);
?>


原文地址:http://www.51ctoall.cn/post/88.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值