如何使用 REST API c# .net 调用PayPal IPN



我在调用PayPal IPN时遇到问题。我不知道该提供哪个 URL 或我应该提供哪个 URL。我已经在互联网上寻找帮助,但似乎没有任何可用的东西,因此我为什么来这里。

所以首先,我有Paypal付款行动

public ActionResult PaymentWithPaypal(int? id, Page page)
    {  
        //getting the apiContext as earlier
        APIContext apiContext = Models.Configuration.GetAPIContext();
        try
        {        
            string payerId = Request.Params["PayerID"];
            if (string.IsNullOrEmpty(payerId))
            {
                string baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/ControllerName/PaymentWithPayPal?";

                var guid = Guid.NewGuid().ToString();
                //CreatePayment function gives us the payment approval url
                //on which payer is redirected for paypal acccount payment
                var createdPayment = this.CreatePayment(apiContext, baseURI + "guid=" + guid);
                //get links returned from paypal in response to Create function call
                var links = createdPayment.links.GetEnumerator();
                string paypalRedirectUrl = null;
                while (links.MoveNext())
                {
                    Links lnk = links.Current;
                    if (lnk.rel.ToLower().Trim().Equals("approval_url"))
                    {
                        //saving the payapalredirect URL to which user will be redirected for payment
                        paypalRedirectUrl = lnk.href;
                    }
                }
                // saving the paymentID in the key guid
                Session.Add(guid, createdPayment.id);
                return Redirect(paypalRedirectUrl);
            }
            else
            {
                // This section is executed when we have received all the payments parameters
                // from the previous call to the function Create
                // Executing a payment
                var guid = Request.Params["guid"];
                var executedPayment = ExecutePayment(apiContext, payerId, Session[guid] as string);
                if (executedPayment.state.ToLower() != "approved")
                {
                    return View("FailureView");
                }
            }
        }
        catch (Exception ex)
        {
            Logger.Log("Error" + ex.Message);
            return View("FailureView");
        }
        return View("SuccessView");
    }

这是 IPN 的代码。

[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);
    }
    private void VerifyTask(HttpRequestBase ipnRequest)
    {
        var verificationResponse = string.Empty;
        try
        {
            var verificationRequest = (HttpWebRequest)WebRequest.Create("https://www.sandbox.paypal.com/cgi-bin/webscr");
            //Set values for the verification request
            verificationRequest.Method = "POST";
            verificationRequest.ContentType = "application/x-www-form-urlencoded";
            var param = Request.BinaryRead(ipnRequest.ContentLength);
            var 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)
        {
            Logger.Log("Error" + exception.Message);
            //Capture exception for manual investigation
        }
        ProcessVerificationResponse(verificationResponse);
    }

    private void LogRequest(HttpRequestBase request)
    {
        // Persist the request values into a database or temporary data store
    }
    private void ProcessVerificationResponse(string verificationResponse)
    {
        if (verificationResponse.Equals("VERIFIED"))
        {
            Logger.Log("Verified");
            // 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
        }
        else if (verificationResponse.Equals("INVALID"))
        {
            Logger.Log(verificationResponse);
        }
        else
        {
            //Log error
        }
    }

现在来澄清一下。我对IPN的理解是,当客户购买商品时,卖方会收到一封电子邮件,告诉他们他们已经出售了产品,然后您可以从中访问transactionId等。

所以在我看来,我有一个带有如下所示的按钮的表单。

@Html.ActionLink("Buy Now", "PaymentWithPaypal", new { Id = Model.Id, @class = "" })

这就是将客户带到PayPal他们可以购买的地方的原因,但这就是我陷入困境的地方,因为我不确定如何调用 IPN 或它是否需要自己的视图。

此时此刻,任何澄清都会有很大帮助。

一种方法是将其放在PayPal帐户设置下。单击"应用程序"后,在其下方会看到重定向URL选项。只需将其添加到此处即可。PayPal .NET SDK 没有传递notify_url的选项。所有其他模式都有。因为,paypal.net sdk 接受return_url,这通常是代码中提到的相同操作方法。

检查这个:https://developer.paypal.com/docs/classic/ipn/integration-guide/IPNSetup/#

如果你想实现实时事件,你现在需要使用网络钩子。以下文档:https://github.com/paypal/PayPal-NET-SDK/wiki/Webhook-Event-Validation

最新更新