首页 > 解决方案 > ASP.NET Web 窗体中的 Paypal IPN 事件侦听器未正确处理请求

问题描述

Paypal 的文档有 ASP.NET MVC 的说明,但是在 web 表单中,几乎没有指导。

关键点,我不得不改变HttpRequestBase ipnRequestHttpRequest ipnRequest因为...

无法从 HttpRequestBase 转换为 HttpRequest

这阻止Request了我的代码工作。我猜这是我从 MVC 到网络表单的翻译的问题?

我对工作 MVC 代码的翻译...

protected void Page_Load(object sender, EventArgs e)
{
    //Store the IPN received from PayPal
    LogRequest(Request);

    //Fire and forget verification task
    Task.Run(() => VerifyTask(Request));

    //Reply back a 200 code
    Response.StatusCode = 200;
}

这是 MVC 版本,来自 Paypal 的文档:

[HttpPost]
        public HttpStatusCodeResult Receive()
        {
            //Store the IPN received from PayPal
            LogRequest(Request);

            //Fire and forget verification task
            Task.Run(() =>  VerifyTask(Request));

            //Reply back a 200 code
            return new HttpStatusCodeResult(HttpStatusCode.OK);
        }

这就是 MVC 版本正在执行的内容,也是我试图通过我的网络表单翻译来执行的内容。

private void VerifyTask(HttpRequest ipnRequest) // would be HttpRequestBase following official docs / mvc
{
   var verificationResponse = string.Empty;

    try
    {

        var verificationRequest = (HttpWebRequest)WebRequest.Create("https://www.sandbox.paypal.com/cgi-bin/webscr");

        var Request = HttpContext.Current.Request;

        //Set values for the verification request
        verificationRequest.Method = "POST";
        verificationRequest.ContentType = "application/x-www-form-urlencoded";
        var param = Request.BinaryRead(ipnRequest.ContentLength);
        strRequest = Encoding.ASCII.GetString(param);

        //Add cmd=_notify-validate to the payload
        strRequest = "cmd=_notify-validate&" + strRequest;
        verificationRequest.ContentLength = strRequest.Length;

        //Attach payload to the verification request
        var streamOut = new StreamWriter(verificationRequest.GetRequestStream(), Encoding.ASCII);
        streamOut.Write(strRequest);
        streamOut.Close();

        //Send the request to PayPal and get the response
        var streamIn = new StreamReader(verificationRequest.GetResponse().GetResponseStream());
        verificationResponse = streamIn.ReadToEnd();
        streamIn.Close();
    }
    catch (Exception exception)
    {
        var hehe = exception;
        //Capture exception for manual investigation
    }

    ProcessVerificationResponse(verificationResponse);
}

使用我的网络表单版本,由于以下原因而失败:

HttpContext.Current.Request = 'HttpContext.Current.Request' 引发了“System.NullReferenceException”类型的异常

感觉就像我正在严重失败,我不确定我是否走在正确的轨道上或错过了一些完全明显的东西。我知道我在这个问题上并没有很清楚,我的脑袋很模糊,而且我已经被困在 Paypal Ipn 的东西上三天了。如果我可以添加任何可以帮助解决任何问题的内容,请发表评论,我会尽我所能。非常感谢!

标签: asp.netasp.net-mvcwebformspaypal-ipn

解决方案


如果您正在寻找一种可靠的方式来获得成功的 PayPal 付款通知(比等待异步 IPN 消息传递更可靠和更强大),只需直接从您的服务器捕获它们。

您将需要两条新路线,一条用于“设置交易”,一条用于“捕获交易”,在此处记录。 如果 Checkout-Net-SDK 不适用于您的环境,请使用直接 HTTPS(无 SDK)调用 PayPal REST API。

一旦你有了这两条路线,将它们与这个前端配对:https ://developer.paypal.com/demo/checkout/#/pattern/server


推荐阅读