我正在尝试在 C# MVC 网站中创建一个 IPN 侦听器。在网上查看后,我设法在下面创建了 ActionResult。
侦听器收到“已验证”响应,但不幸的是,它似乎没有收到有关付款的任何其他信息。
[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;
}
我很可能错过了一些非常简单的东西。
任何帮助都会很棒。