paypal ipn java_【官方】Paypal的IPN示例

包括几个流行的网站开发环境的示范代码。尽管此代码已经过PayPal测试,但PayPal无法对其用途负责。

ASP.Net/C#

using System;

using System.IO;

using System.Text;

using System.Net;

using System.Web;

public partial class csIPNexample :System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

//Post back to either sandbox or live

string strSandbox =

"https://www.sandbox.paypal.com/cgi-bin/webscr";

string strLive = "https://www.paypal.com/cgi-bin/webscr";

HttpWebRequest req =

(HttpWebRequest)WebRequest.Create(strSandbox);

// Set values for the request back

req.Method = "POST";

req.ContentType = "application/x-www-form-urlencoded";

byte[] param =

Request.BinaryRead(HttpContext.Current.Request.ContentLength);

string strRequest = Encoding.ASCII.GetString(param);

strRequest += "&cmd=_notify-validate";

req.ContentLength = strRequest.Length;

//for proxy

//WebProxy proxy = new WebProxy(new Uri("http://url:port#"));

//req.Proxy = proxy;

//Send the request to PayPal and get the response

StreamWriter streamOut = new StreamWriter(req.GetRequestStream(),

System.Text.Encoding.ASCII);

streamOut.Write(strRequest);

streamOut.Close();

StreamReader streamIn = new

StreamReader(req.GetResponse().GetResponseStream());

string strResponse = streamIn.ReadToEnd();

streamIn.Close();

if (strResponse == "VERIFIED")

{

// 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

}

else if (strResponse == "INVALID")

{

// log for manual investigation

}

else

{

//log response/ipn data for manual investigation

}

}

}

ASP.Net/VB

Imports System.Net

Imports System.IO

Partial Class vbIPNexample

Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As

System.EventArgs) Handles Me.Load

'Post back to either sandbox or live

Dim strSandbox As String =

"https://www.sandbox.paypal.com/cgi-bin/webscr"

Dim strLive As String =

"https://www.paypal.com/cgi-bin/webscr"

Dim req As HttpWebRequest = CType(WebRequest.Create(strSandbox),

HttpWebRequest)

'Set values for the request back

req.Method = "POST"

req.ContentType = "application/x-www-form-urlencoded"

Dim Param() As Byte =

Request.BinaryRead(HttpContext.Current.Request.ContentLength)

Dim strRequest As String = Encoding.ASCII.GetString(Param)

strRequest = strRequest +

"&cmd=_notify-validate"

req.ContentLength = strRequest.Length

'for proxy

'Dim proxy As New WebProxy(New

System.Uri("http://url:port#"))

'req.Proxy = proxy

'Send the request to PayPal and get the response

Dim streamOut As StreamWriter = New

StreamWriter(req.GetRequestStream(), Encoding.ASCII)

streamOut.Write(strRequest)

streamOut.Close()

Dim streamIn As StreamReader = New

StreamReader(req.GetResponse().GetResponseStream())

Dim strResponse As String = streamIn.ReadToEnd()

streamIn.Close()

If strResponse = "VERIFIED" Then

'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

'处理付款

ElseIf strResponse = "INVALID" Then

'log for manual investigation

Else

'Response wasn't VERIFIED or INVALID, log for manual

investigation

End If

End Sub

End Class

ASP/VBScript

(requires MSXML)

Dim Item_name, Item_number, Payment_status, Payment_amount

Dim Txn_id, Receiver_email, Payer_email

Dim objHttp, str

' read post from PayPal system and add 'cmd'

str = Request.Form &

"&cmd=_notify-validate"

' post back to PayPal system to validate

set objHttp = Server.CreateObject("Msxml2.ServerXMLHTTP")

' set objHttp =

Server.CreateObject("Msxml2.ServerXMLHTTP.4.0")

' set objHttp = Server.CreateObject("Microsoft.XMLHTTP")

objHttp.open "POST", "https://www.paypal.com/cgi-bin/webscr",

false

objHttp.setRequestHeader "Content-type",

"application/x-www-form-urlencoded"

objHttp.Send str

' assign posted variables to local variables

Item_name = Request.Form("item_name")

Item_number = Request.Form("item_number")

Payment_status = Request.Form("payment_status")

Payment_amount = Request.Form("mc_gross")

Payment_currency = Request.Form("mc_currency")

Txn_id = Request.Form("txn_id")

Receiver_email = Request.Form("receiver_email")

Payer_email = Request.Form("payer_email")

' Check notification validation

if (objHttp.status <> 200 )

then

' HTTP error handling

elseif (objHttp.responseText = "VERIFIED") then

' check that Payment_status=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

elseif (objHttp.responseText = "INVALID") then

' log for manual investigation

else

' error

end if

set objHttp = nothing

%>

ColdFusion

str="cmd=_notify-validate">

list="#Form.FieldNames#">

"LCase(TheField)#=#URLEncodedFormat(Form[TheField])#">

IsDefined("FORM.payment_date")>

"&payment_date=#URLEncodedFormat(Form.payment_date)#">

IsDefined("FORM.subscr_date")>

"&subscr_date=#URLEncodedFormat(Form.subscr_date)#">

IsDefined("FORM.auction_closing_date")>

"&subscr_date=#URLEncodedFormat(Form.auction_closing_date)#">

URL="https://www.paypal.com/cgi-bin/webscr?#str#" METHOD="GET"

RESOLVEURL="false">

item_name=FORM.item_name>

payment_status=FORM.payment_status>

payment_amount=FORM.mc_gross>

payment_currency=FORM.mc_currency>

receiver_email=FORM.receiver_email>

payer_email=FORM.payer_email>

IsDefined("FORM.item_number")>

item_number=FORM.item_number>

"VERIFIED">

"INVALID">

Java/JSP

%>

// read post from PayPal system and add 'cmd'

Enumeration en = request.getParameterNames();

String str = "cmd=_notify-validate";

while(en.hasMoreElements()){

String paramName = (String)en.nextElement();

String paramValue = request.getParameter(paramName);

str = str + "&" + paramName + "=" +

URLEncoder.encode(paramValue);

}

// post back to PayPal system to validate

// NOTE: change http: to https: in the following URL to verify

using SSL (for increased security).

// using HTTPS requires either Java 1.4 or greater, or Java Secure

Socket Extension (JSSE)

// and configured for older versions.

URL u = new URL("https://www.paypal.com/cgi-bin/webscr");

URLConnection uc = u.openConnection();

uc.setDoOutput(true);

uc.setRequestProperty("Content-Type","application/x-www-form-urlencoded");

PrintWriter pw = new PrintWriter(uc.getOutputStream());

pw.println(str);

pw.close();

BufferedReader in = new BufferedReader(

new InputStreamReader(uc.getInputStream()));

String res = in.readLine();

in.close();

// assign posted variables to local variables

String itemName = request.getParameter("item_name");

String itemNumber = request.getParameter("item_number");

String paymentStatus =

request.getParameter("payment_status");

String paymentAmount = request.getParameter("mc_gross");

String paymentCurrency = request.getParameter("mc_currency");

String txnId = request.getParameter("txn_id");

String receiverEmail =

request.getParameter("receiver_email");

String payerEmail = request.getParameter("payer_email");

check notification validation

if(res.equals("VERIFIED")) {

// check that paymentStatus=Completed

// check that txnId has not been previously processed

// check that receiverEmail is your Primary PayPal email

// check that paymentAmount/paymentCurrency are correct

// process payment

}

else if(res.equals("INVALID")) {

// log for investigation

}

else {

// error

}

%>

PERL

(requires LWP::UserAgent)

#!/usr/bin/perl

# read post from PayPal system and add 'cmd'

read (STDIN, $query, $ENV{'CONTENT_LENGTH'});

$query .= '&cmd=_notify-validate';

# post back to PayPal system to validate

use LWP::UserAgent;

$ua = new LWP::UserAgent;

$req = new HTTP::Request

'POST','https://www.paypal.com/cgi-bin/webscr';

$req->content_type('application/x-www-form-urlencoded');

$req->content($query);

$res = $ua->request($req);

# split posted variables into pairs

@pairs = split(/&/, $query);

$count = 0;

foreach $pair (@pairs) {

($name, $value) = split(/=/, $pair);

$value =~ tr/+/ /;

$value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;

$variable{$name} = $value;

$count++;

}

# assign posted variables to local variables

$item_name = $variable{'item_name'};

$item_number = $variable{'item_number'};

$payment_status = $variable{'payment_status'};

$payment_amount = $variable{'mc_gross'};

$payment_currency = $variable{'mc_currency'};

$txn_id = $variable{'txn_id'};

$receiver_email = $variable{'receiver_email'};

$payer_email = $variable{'payer_email'};

if ($res->is_error) {

# HTTP error

}

elsif ($res->content eq 'VERIFIED') {

# check the $payment_status=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

}

elsif ($res->content eq 'INVALID') {

# log for manual investigation

}

else {

# error

}

print "content-type: text/plain\n\n";

PHP 4.1

// 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 ('ssl://www.paypal.com', 443, $errno, $errstr,

30);

// 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'];

if (!$fp) {

// HTTP ERROR

else {

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

while (!feof($fp)) {

$res = fgets ($fp, 1024);

if (strcmp ($res, "VERIFIED") == 0) {

// 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

}

else if (strcmp ($res, "INVALID") == 0) {

// log for manual investigation

}

}

fclose ($fp);

}

?>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值