如何使用REST API c#.net

时间:2017-04-05 22:17:41

标签: c# .net paypal-ipn paypal-rest-sdk

我在调用PayPal IPN时遇到问题。我不知道要提供哪个URL或我打算给出哪个URL。我已经在互联网上寻求帮助,但似乎没有什么可用,因此我来到这里的原因。

首先,我有PaymentWithPaypal动作

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 = "" })

这就是客户在他们可以购买的地方付款,但这就是我被困的地方,因为我不知道如何调用IPN或者是否需要自己的视图。

任何清晰度都会在这个时刻得到很多帮助。

1 个答案:

答案 0 :(得分:0)

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

检查以下内容: https://developer.paypal.com/docs/classic/ipn/integration-guide/IPNSetup/#

如果您想获得实时事件,则需要立即使用webhooks。以下文档: https://github.com/paypal/PayPal-NET-SDK/wiki/Webhook-Event-Validation