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

转载 2012年03月21日 10:23:06
随着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接口地址),包含了此次交易的一些信息。并在自己的数据库中生成一张订单记录。
PaypalSession中记录下这些交易信息,用户用Paypal账户登录PaypalSandboxSandbox的虚拟帐号),复查明细,点击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);
?>


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

相关文章推荐

2016 PayPal商家账户界面 如何集成支付按钮

1. 登入PayPal账户https://www.paypal.com 2. 点击用户信息,选择用户信息与设置 3. 点击销售工具,PayPal按钮,更新 4. 创建新按钮 5...

经验总结15--Paypal支付,测试sandbox

Paypal支付,测试sandbox

PayPal Sandbox 在线支付开发测试环境

paypal ipn(Instant PaymentNotification),就是Paypal开发的一种能主动通知第三方卖家系统交易状态的一种机制。IPN的原理很简单,就是当产生了一个交易之后,交易...
  • lee576
  • lee576
  • 2008年11月05日 21:43
  • 8519

paypal 主要的html 表格变量的含义

1 no_shipping                                            2 cmd的值             描述         ...

算是目前PAYPAL最全最完整的开发方式了

PAYPAL 完整开发API支付实例!PAYPAL支付的提交和接收都分为2种方式!即:和淘宝的一样,使用appkey、apptoken的方式)申请这个比较麻烦,需要填写很多的资料,而且审批也需要周期很...

Delphi7高级应用开发随书源码

  • 2003年04月30日 00:00
  • 676KB
  • 下载

paypal express 教程和例子

http://www.sanwebe.com/2012/07/paypal-expresscheckout-with-php

Rest API 开发 学习笔记

概述 REST 从资源的角度来观察整个网络,分布在各处的资源由URI确定,而客户端的应用通过URI来获取资源的表示方式。获得这些表徵致使这些应用程序转变了其状态。随着不断获取资源的表示方式,客户...

php_paypal接口开发!

"> >"> ...

Android简明开发教程二十四篇及示例代码下载

Android简明开发教程一:概述Android简明开发教程二:安装开发环境Android简明开发教程三:第一个应用Hello WorldAndroid简明开发教程四:Android应用基本概念And...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Paypal付款功能网站集成简明教程 示例代码
举报原因:
原因补充:

(最多只允许输入30个字)