【问题标题】:PayPal API & MVC5: Get Price from another controllerPayPal API 和 MVC 5:从另一个控制器获取价格
【发布时间】:2017-07-02 23:34:29
【问题描述】:

我正在尝试设置 PayPal 以接受来自我的网站的付款,该网站根据他们上传的照片数量计算费用。关注tutorial,但我想传递我在另一个控制器中计算的价格。

我的 PayPal 控制器:

public ActionResult PaymentWithPaypal()
    {
        APIContext apiContext = PayPalConfig.GetAPIContext();

        try
        {
            string payerId = Request.Params["PayerID"];

            if (string.IsNullOrEmpty(payerId))
            {
                string baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/Paypal/PaymentWithPayPal?";
                var guid = Convert.ToString((new Random()).Next(100000));                    
                var createdPayment = this.CreatePayment(apiContext, baseURI + "guid=" + guid);
                var links = createdPayment.links.GetEnumerator();
                string paypalRedirectUrl = null;
                while (links.MoveNext())
                {
                    Links lnk = links.Current;
                    if (lnk.rel.ToLower().Trim().Equals("approval_url"))
                    {                            
                        paypalRedirectUrl = lnk.href;
                    }
                }

                Session.Add(guid, createdPayment.id);
                return Redirect(paypalRedirectUrl);
            }
            else
            {               
                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");
    }

    private PayPal.Api.Payment payment;

    private PayPal.Api.Payment ExecutePayment(APIContext apiContext, string payerId, string paymentId)
    {
        var paymentExecution = new PaymentExecution() { payer_id = payerId };
        this.payment = new PayPal.Api.Payment() { id = paymentId };
        return this.payment.Execute(apiContext, paymentExecution);
    }

    private PayPal.Api.Payment CreatePayment(APIContext apiContext, string redirectUrl)
    {
        var itemList = new ItemList() { items = new List<Item>() };
        itemList.items.Add(new Item()
        {
            name = "Participation Fee",
            currency = "USD",
            price = "5",
            quantity = "1",
            sku = "sku"
        });

        var payer = new Payer() { payment_method = "paypal" };
        var redirUrls = new RedirectUrls()
        {
            cancel_url = redirectUrl,
            return_url = redirectUrl
        };            
        var details = new Details()
        {
            tax = "1",
            shipping = "1",
            subtotal = "5"
        };            
        var amount = new Amount()
        {
            currency = "USD",
            total = "7", 
            details = details
        };

        var transactionList = new List<Transaction>();
        transactionList.Add(new Transaction()
        {
            description = "Transaction description.",
            invoice_number = "your invoice number",
            amount = amount,
            item_list = itemList
        });

        this.payment = new PayPal.Api.Payment()
        {
            intent = "sale",
            payer = payer,
            transactions = transactionList,
            redirect_urls = redirUrls
        };
        return this.payment.Create(apiContext);

    }

计算我的价格的控制器:

        int Asection;
        int Bsection;
        int Csection;
        int Dsection;

        if (viewPhotos.GetA1.Any() || viewPhotos.GetA2.Any() || viewPhotos.GetA3.Any() || viewPhotos.GetA4.Any())
        {
            Asection = 1; 
        }
        else
        {
            Asection = 0;
        }

        if (viewPhotos.GetB1.Any() || viewPhotos.GetB2.Any() || viewPhotos.GetB3.Any() || viewPhotos.GetB4.Any())
        {
            Bsection = 1;
        }
        else
        {
            Bsection = 0;
        }

        if (viewPhotos.GetC1.Any() || viewPhotos.GetC2.Any() || viewPhotos.GetC3.Any() || viewPhotos.GetC4.Any())
        {
            Csection = 1;
        }
        else
        {
            Csection = 0;
        }

        if (viewPhotos.GetD1.Any() || viewPhotos.GetD2.Any() || viewPhotos.GetD3.Any() || viewPhotos.GetD4.Any())
        {
            Dsection = 1;
        }
        else
        {
            Dsection = 0;
        }

        int TotalSection = Asection + Bsection + Csection + Dsection;

        viewPhotos.MoneyValue = TotalSection;

        int RequiredMoney;
        if (TotalSection == 1)
        {
            RequiredMoney = 20;
        }
        else if (TotalSection == 2)
        {
            RequiredMoney = 25;
        }
        else if (TotalSection == 3)
        {
            RequiredMoney = 30;
        }
        else
        {
            RequiredMoney = 36;
        }

        viewPhotos.RequiredMoney = RequiredMoney;

        return View(viewPhotos);

我向用户显示价格的视图:

<p>You will need to pay participation fees USD @Model.RequiredMoney.</p>
<h3>Total: USD @Model.RequiredMoney</h3>
@Html.ActionLink("Make Payment with PayPal", "PaymentWithPaypal", "Paypal")

到目前为止,上述代码适用于网站上的默认测试项目价格和详细信息。如果有人能帮助说明我如何将 PayPal 收取的金额设置为我的计算价格,我将不胜感激,无需任何运费或税费。提前致谢。

【问题讨论】:

  • sample 正在其CreatePayment 函数中为“items”创建硬编码数据。您必须将用户选择的项目连接到它。换句话说,相应地替换CreatePayment 中的硬编码项。 Hth.
  • 嗨@EdSF,我明白你在说什么,但我不知道如何实现它。你会这么好心地演示或分享一个相关的教程吗?谢谢。
  • 请永远不要像您正在做的那样内联new Random(),因为您很容易遇到结果不是随机的情况。您应该始终为 Random 创建一个静态变量,并在需要的地方简单地重复使用它。
  • 感谢@Enigmativity 的评论。我对这一切都很陌生,我的项目仍在运行的原因完全是由于我遵循的教程,所以我不知道如果不是 Random() 可以替换什么。但我也有点担心你提到的内容,因此我添加了当前用户 ID,后跟 Random() 作为指导,以减少重复的可能性。我希望这会降低出错的风险。
  • @Eva - 不,它不会。您需要将new Random() 移出到字段级变量,即private static Random rnd = new Random();。然后,只要您使用 new Random(),您只需使用 rnd

标签: c# asp.net-mvc paypal


【解决方案1】:

在搜索和查看日志一段时间后,这是我解决问题的方法:

在我计算价格的控制器上,我使用 TempData 来存储我的价格:

TempData["ParticipationFee"] = RequiredMoney;

然后在 PaypalController,CreatePayment 函数下,

var itemList = new ItemList() { items = new List<Item>() };

string FeeAmount = TempData["ParticipationFee"].ToString();

itemList.items.Add(new Item()
{
    name = "Participation Fee",
    currency = "USD",
    price = FeeAmount,
    quantity = "1",
    sku = "sku"
 });

按 F5 并获得 Paypal Sandbox 的成功响应。哇!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-15
    • 2016-08-22
    • 1970-01-01
    • 2017-10-14
    • 2015-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多