您的位置:首页 > 运维架构 > 网站架构

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

2012-03-21 10:23 603 查看
[align=left]随着paypal的业务在国内的发展,越来越多的网站希望能将paypal集成到自己的购物网站中去。但开始做的时候,很多朋友发现,paypal的接口比想象中的要麻烦的多。以前做过taobao接口、做过网银在线接口,也许是taobao和网银提供的接口参数和范例比较简单易懂,或者说写的教程比较本地化,所以基本上有点程序基础朋友的都能做完。遇上了paypal,脑袋就大了,调试比较麻烦那。[/align]
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,可以直接将地址填入。
[align=left]接下来,我们测试的时候,应该将Paypal接口的地址设置为https://www.sandbox.paypal.com/cgi-bin/webscr[/align]
[align=left]最后基本的流程为:[/align]
[align=left]用户在我们的网站上选择商品、放入购物车,然后检查准备支付网站根据购物车中的商品,生成Paypal的支付表单(也是提交到上面IPN用的Paypal接口地址),包含了此次交易的一些信息。并在自己的数据库中生成一张订单记录。[/align]
Paypal在Session中记录下这些交易信息,用户用Paypal账户登录Paypal(Sandbox用Sandbox的虚拟帐号),复查明细,点击Pay按钮,Paypal进行交易处理,如果我们的Paypal收款帐号在接受帐款上没有什么问题(没有特别的需要Accept的地方),交易完成,那么Paypal会发送一个IPN,并发送提示邮件。我们IPN
Handler接受到信息,首先向Paypal进行校验,如果信息正确,然后根据信息和自己数据库中进行比对,如果无误,可以将支付信息保存,并修改订单状态。
[align=left]然后Paypal会显示一个界面表示交易完成,此时如果用户点击“Return”按钮,Paypal会将用户送回我们网站指定地点。
网站迎接用户回来,向用户表示感谢,并进行提醒,给出订单号等等。[/align]
[align=left]别忘了,还需要在paypal里设置一大堆的参数.比较麻烦。[/align]
[align=left]附上网站主流的集中程序开发语言范例:[/align]
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
[align=left]sQuerystring = objHttp.responseText[/align]
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
%>

 
[align=left] [/align]

[align=left] [/align]
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>

 
[align=left] [/align]

[align=left] [/align]
PERL

 

 
[align=left] [/align]
[align=left]#!/usr/bin/perl -w[/align]

###
[align=left]#[/align]
[align=left]# PayPal PDT (Payment Data Transfer) CGI[/align]
[align=left]#[/align]
[align=left]###[/align]

use strict;
[align=left]use CGI qw(:all unescape);[/align]
[align=left]use CGI::Carp qw(fatalsToBrowser);[/align]

# These modules are required to make the secure HTTP request to PayPal.
[align=left]use LWP::UserAgent;[/align]
[align=left]use Crypt::SSLeay;[/align]

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

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());
[align=left]}[/align]

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

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

my $transaction = param("tx");

if (not $transaction) {
[align=left]    print (h2("The transaction ID was not found."), done_text());[/align]

    exit();
[align=left]}[/align]

my $paypal_url = "https://$paypal_server/cgi-bin/webscr";
[align=left]my $query = join("&", "cmd=_notify-synch", "tx=$transaction", "at=$auth_token");[/align]

my $user_agent = new LWP::UserAgent;
[align=left]my $request = new HTTP::Request("POST", $paypal_url);[/align]

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

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:"),
[align=left]        $result->error_as_HTML, done_text());[/align]
[align=left]    exit();[/align]
[align=left]}[/align]

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

# The status is always the first line of the response.
[align=left]my $status = shift @response;[/align]

if ($status eq "SUCCESS") {
[align=left]    # success[/align]
[align=left]    my %transaction;[/align]

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

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

print done_text();

 
[align=left] [/align]

[align=left] [/align]
[align=left] [/align]

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'];
[align=left]echo ("<p><h3>Thank you for your purchase!</h3></p>");[/align]
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

}
[align=left]}[/align]
[align=left]fclose ($fp);[/align]
[align=left]?>[/align]

原文地址:http://www.51ctoall.cn/post/88.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息