C# Paypal IPN侦听器未返回值
我试图在C#MVC网站上创建一个IPN侦听器。在网上查看之后,我成功地创建了下面的ActionResult 监听器收到一个“已验证”的响应,但不幸的是,它似乎没有收到任何关于付款的其他信息C# Paypal IPN侦听器未返回值,c#,asp.net,asp.net-mvc,paypal,paypal-ipn,C#,Asp.net,Asp.net Mvc,Paypal,Paypal Ipn,我试图在C#MVC网站上创建一个IPN侦听器。在网上查看之后,我成功地创建了下面的ActionResult 监听器收到一个“已验证”的响应,但不幸的是,它似乎没有收到任何关于付款的其他信息 [HttpPost] public ActionResult IPN() { var log = new LogMessage(); log.LogMessageToFile("IPN recieved!"); var formVals
[HttpPost]
public ActionResult IPN()
{
var log = new LogMessage();
log.LogMessageToFile("IPN recieved!");
var formVals = new Dictionary<string, string>();
formVals.Add("cmd", "_notify-validate");
string response = GetPayPalResponse(formVals, true);
if (response == "VERIFIED")
{
log.LogMessageToFile("IPN VERIFIED!");
//validate the order
string sAmountPaid = Request.QueryString["amt"];
string sPayment = ConfigurationManager.AppSettings["amount"].ToString();
Decimal amountPaid = 0;
Decimal Payment = 0;
Decimal.TryParse(sAmountPaid, out amountPaid);
Decimal.TryParse(sPayment, out Payment);
if (Payment <= amountPaid)
{
log.LogMessageToFile("IPN Correct amount");
//process it
try
{
string GUID = Request.QueryString["cm"];
string strGatewayResponse = Request.QueryString["tx"];
var data = new Datalayer();
data.AddPayment(GUID, amountPaid, strGatewayResponse, true);
log.LogMessageToFile("IPN Commplete");
return Redirect("/Payment/Success");
}
catch
{
log.LogMessageToFile("IPN Error");
return Redirect("/Payment/Error");
}
}
else
{
log.LogMessageToFile("IPN Incorrect amount!");
log.LogMessageToFile("IPN amount:" + Request.QueryString["payment_gross"]);
log.LogMessageToFile("IPN GUID:" + Request.QueryString["custom"]);
log.LogMessageToFile("IPN ID:" + Request.QueryString["txn_id"]);
return Redirect("/Payment/Error");
}
}
log.LogMessageToFile("IPN not verified!");
return View("/Payment/Error");
}
string GetPayPalResponse(Dictionary<string, string> formVals, bool useSandbox)
{
string paypalUrl = useSandbox ? "https://www.sandbox.paypal.com/cgi-bin/webscr"
: "https://www.paypal.com/cgi-bin/webscr";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(paypalUrl);
// Set values for the request back
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
byte[] param = Request.BinaryRead(Request.ContentLength);
string strRequest = Encoding.ASCII.GetString(param);
StringBuilder sb = new StringBuilder();
sb.Append(strRequest);
foreach (string key in formVals.Keys)
{
sb.AppendFormat("&{0}={1}", key, formVals[key]);
}
strRequest += sb.ToString();
req.ContentLength = strRequest.Length;
string response = "";
using (StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII))
{
streamOut.Write(strRequest);
streamOut.Close();
using (StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream()))
{
response = streamIn.ReadToEnd();
}
}
return response;
}
[HttpPost]
公共行动结果IPN()
{
var log=new LogMessage();
LogMessageToFile(“已接收IPN!”);
var formVals=新字典();
formVals.Add(“cmd”和“notify-validate”);
字符串响应=GetPayPalResponse(formVals,true);
如果(响应=“已验证”)
{
LogMessageToFile(“IPN已验证!”);
//确认订单
字符串sAmountPaid=Request.QueryString[“amt”];
字符串sPayment=ConfigurationManager.AppSettings[“金额”].ToString();
十进制支付金额=0;
十进制付款=0;
十进制.特里帕尔斯(sAmountPaid,OutAmountPaid);
十进制.特里帕色(付款、付款);
if(Payment我必须做同样的事情,但是在Web表单中。它应该同样适用,因为我们都在处理HttpWebRequest
对象。看下面的代码-这是我的Page\u Load()
我的侦听器URL(listener.aspx.cs)的方法。注意if(strResponse==“VERIFIED”)部分
并查看其中的string[]responseArray=strRequest.Split('&');
-这是获取所有响应变量的地方。您必须稍微追溯一下用于获取值(由符号分隔)的strRequest
的定义
另外,请查看您的PayPal帐户上的IPN响应。响应将是一个由符号分隔的长字符串-这将与strequest
的值相同。这是您提取有关付款的其他信息的字符串:
protected void Page_Load(object sender, EventArgs e)
{
//string strSandbox = "https://www.sandbox.paypal.com/cgi-bin/webscr";
//string strLive = "https://www.paypal.com/cgi-bin/webscr";
string url = ConfigurationManager.AppSettings["PayPalUrl"];
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
//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;
//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")
{
// strRequest is a long string delimited by '&'
string[] responseArray = strRequest.Split('&');
List<KeyValuePair<string, string>> lkvp = new List<KeyValuePair<string, string>>();
string[] temp;
// for each key value pair
foreach (string i in responseArray)
{
temp = i.Split('=');
lkvp.Add(new KeyValuePair<string, string>(temp[0], temp[1]));
}
// now we have a list of key value pairs
string firstName = string.Empty;
string lastName = string.Empty;
string address = string.Empty;
string city = string.Empty;
string state = string.Empty;
string zip = string.Empty;
string payerEmail = string.Empty;
string contactPhone = string.Empty;
foreach (KeyValuePair<string, string> kvp in lkvp)
{
switch (kvp.Key)
{
case "payer_email":
payerEmail = kvp.Value.Replace("%40", "@");
break;
case "first_name":
firstName = kvp.Value;
break;
case "last_name":
lastName = kvp.Value;
break;
case "address_city":
city = kvp.Value.Replace("+", " ");
break;
case "address_state":
state = kvp.Value.Replace("+", " ");
break;
case "address_street":
address = kvp.Value.Replace("+", " ");
break;
case "address_zip":
zip = kvp.Value;
break;
case "contact_phone":
contactPhone = kvp.Value;
break;
default:
break;
}
}
string userName = payerEmail;
string password = Membership.GeneratePassword(8, 0);
MembershipCreateStatus status = new MembershipCreateStatus();
MembershipUser newUser = Membership.CreateUser(userName, password, userName, null, null, true, out status);
ProfileCommon pc = ProfileCommon.Create(userName) as ProfileCommon;
pc.Address.PostalCode = zip;
pc.Address.Address = address;
pc.Address.City = city;
pc.Address.State = state;
pc.Personal.FirstName = firstName;
pc.Personal.LastName = lastName;
pc.Contacts.DayPhone = contactPhone;
pc.Save();
if (status == MembershipCreateStatus.Success)
{
Roles.AddUserToRole(userName, "User");
//send email to user indicating username and password
SendEmailToUser(userName, password, firstName, lastName, payerEmail);
}
// need to figure out a way to catch unwanted responses here... redirect somehow
}
else if (strResponse == "INVALID")
{
//log for manual investigation
}
else
{
//log response/ipn data for manual investigation
}
}
受保护的无效页面加载(对象发送方,事件参数e)
{
//字符串strSandbox=”https://www.sandbox.paypal.com/cgi-bin/webscr";
//字符串strLive=”https://www.paypal.com/cgi-bin/webscr";
字符串url=ConfigurationManager.AppSettings[“PayPalUrl”];
HttpWebRequest req=(HttpWebRequest)WebRequest.Create(url);
//设置请求返回的值
请求方法=“POST”;
req.ContentType=“应用程序/x-www-form-urlencoded”;
byte[]param=Request.BinaryRead(HttpContext.Current.Request.ContentLength);
string strequest=Encoding.ASCII.GetString(param);
strRequest+=“&cmd=_notify-validate”;
请求内容长度=请求长度;
//将请求发送到PayPal并获得响应
StreamWriter streamOut=新的StreamWriter(req.GetRequestStream(),System.Text.Encoding.ASCII);
streamOut.Write(strRequest);
streamOut.Close();
StreamReader streamIn=新的StreamReader(req.GetResponse().GetResponseStream());
字符串strResponse=streamIn.ReadToEnd();
streamIn.Close();
如果(strResponse==“已验证”)
{
//strRequest是由“&”分隔的长字符串
字符串[]responseArray=strRequest.Split('&');
List lkvp=新列表();
字符串[]温度;
//对于每个键值对
foreach(响应数组中的字符串i)
{
temp=i.Split('=');
lkvp.Add(新的KeyValuePair(临时[0],临时[1]);
}
//现在我们有一个键值对列表
string firstName=string.Empty;
string lastName=string.Empty;
字符串地址=string.Empty;
string city=string.Empty;
字符串状态=string.Empty;
string zip=string.Empty;
string payerEmail=string.Empty;
string contactPhone=string.Empty;
foreach(lkvp中的KeyValuePair kvp)
{
开关(kvp.键)
{
案例“付款人电子邮件”:
payerEmail=kvp.Value.Replace(“%40”和“@”);
打破
案例“名字”:
firstName=kvp.Value;
打破
案例“姓氏”:
lastName=kvp.Value;
打破
案例“地址城市”:
city=kvp.Value.Replace(“+”,”);
打破
案例“地址州”:
state=kvp.Value.Replace(“+”,”);
打破
案例“地址街”:
地址=kvp.Value.Replace(“+”,”);
打破
案例“地址邮政编码”:
zip=kvp.Value;
打破
案例“联系电话”:
contactPhone=kvp.值;
打破
违约:
打破
}
}
字符串用户名=payerEmail;
字符串密码=成员身份。GeneratePassword(8,0);
MembershipCreateStatus状态=新建MembershipCreateStatus();
MembershipUser newUser=Membership.CreateUser(用户名、密码、用户名、null、null、true、out状态);
ProfileCommon pc=ProfileCommon。创建(用户名)作为ProfileCommon;
pc.Address.PostalCode=zip;
pc.Address.Address=地址;
pc.Address.City=城市;
pc.Address.State=状态;
pc.Personal.FirstName=FirstName;
pc.Personal.LastName=LastName;
pc.Contacts.DayPhone=contactPhone;
pc.Save();
if(status==MembershipCreateStatus.Success)
{
Roles.AddUserToRole(用户名,“用户”);