我在这里: 首页 » paypal经验 » 浏览文章: Paypal付款功能网站集成简明教程 示例代码
« PAYPAL - 集成API接口教程(转载)招行香港:暂停接收两地一卡通新开户申请 »

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
 
 

<%@LANGUAGE="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 $paypal_url = "https://$paypal_server/cgi-bin/webscr";

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

?>

 

如果你还没有paypal账户,你可以点击这里申请注册!


原创文章如转载,请注明:转载自Paypal贝宝使用指南 [ http://www.51paypal.com/ ]
  • 相关文章
  • quote 3.linda
  • 能否给提供一个关于ipn 的 返回处理代码,就是可以把处理的数据自动插入到订单数据库和用户数据库,因为自己要统计一些信息
  • 2009-6-5 14:19:19 回复该留言
  • quote 2.asd
  • http://arlene145.ecrater.com


  • The world's most effective diet capsules-Japan lingzhi product wholesale! 100% real

    products!Feel and look better, and never have to worry about having a serious weight problem

    again!we offer:
    2 day diet japan lingzhi ;2 SLIM FAST JAPAN LINGZHI 2/Day Diet ;3 day fit japan lingzhi; 3X

    Slimming Power; imelda perfect slim pills; Weight Loss Japan Lingzhi; Cleaned Slim Tea ;Fat

    Belly Eliminator Slim Capsule; Health Slimming Coffee ;japan lingzhi slim express tea ;New 7

    day Diet;Power Slim Tea ;Weight loss Body Slimming diet pills .

    http://arlene145.ecrater.com/product.php?pid=4346453
    http://arlene145.ecrater.com/product.php?pid=4346504
    http://arlene145.ecrater.com/product.php?pid=4334341
    http://arlene145.ecrater.com/product.php?pid=4346504
    http://arlene145.ecrater.com/product.php?pid=4345511
    http://arlene145.ecrater.com/product.php?pid=4345613
  • 2009-5-15 11:53:20 回复该留言
  • quote 1.Jason
  • Paypal接口和Taobao接口有点想传,不过Paypal在接收页那安全验证没有弄明白。
    roy 于 2008-11-26 11:21:26 回复
    每个paypal账户的authToken 都是不一样的。安全验证的作用还是很重要的。
  • 2008-11-26 11:21:26 回复该留言

发表评论

为了防止SPAM,含链接的评论需要审核后才能显示。

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。