Paypal 以折扣方式将多个商品添加到购物车

Posted

技术标签:

【中文标题】Paypal 以折扣方式将多个商品添加到购物车【英文标题】:Paypal add to cart multiple items form with discount 【发布时间】:2011-12-12 00:58:44 【问题描述】:

我正在尝试使用 paypal 添加到购物车表单根据买家的购买金额提供折扣。基本上我会提供折扣码 Disc1、Disc2、Disc3、Disc4,它们将打折 5 美元、10 美元、20 美元、50 美元。但只有当购买金额分别超过 25 美元、50 美元、100 美元、250 美元时,它们才能起作用。

我正在尝试通过调用 javascript 文件来执行此操作,如果满足最低价格条件,该文件将应用折扣。

问题是表单用于多个项目。所以“金额”的变量不存在,但每个选项都有不同的金额,所以 option_amount0、option_amount1、option_amount2 ......等等。如果有一个“金额”,我可以使代码工作,但不像这里多个项目/价格。

html 代码如下所示:

    <head>
<script language="JavaScript" type="text/javascript" src="coupon.js"></script>
</head>
        <form target="_blank" action="https://www.paypal.com/cgi-bin/webscr" method="post">
    <input type="hidden" name="cmd" value="_cart">
    <input type="hidden" name="business" value="email@email.com">
    <input type="hidden" name="lc" value="US">
    <input type="hidden" name="item_name" value="Products">
    <input type="hidden" name="button_subtype" value="">
    <input type="hidden" name="no_shipping" value="1">
    <input type="hidden" name="undefined_quantity" value="1">
    <input type="hidden" name="rm" value="1">
    <input type="hidden" name="return" value="www.website.com">
    <input type="hidden" name="cancel_return" value="www.website.com">
    <input type="hidden" name="currency_code" value="USD">
    <input type="hidden" name="tax_rate" value="0.000">
    <input type="hidden" name="shipping" value="0.00">
    <input type="hidden" name="add" value="1">
    <input type="hidden" name="bn" value="PP-ShopCartBF:btn_cart_LG.gif:NonHosted">
    <table>
    <tr><td><br /><h4>
    <center><input type="hidden" name="on0" value="Products">Choose a Product</center></h4></td></tr><tr><td><center>
    <select name="os0" style="width: 230px"></center>
        <option value="item1">Product 1 : $15</option>
            <option value="item2">Product 2 : $25</option>
        <option value="item3">Product 3 : $75</option>
        <option value="item4">Product 4 : $150</option>
        <option value="item5">Product 5 : $300</option>

    </select> </td></tr>
    </table>
    <input type="hidden" name="currency_code" value="USD">

    <input type="hidden" name="option_select0" value="item1">
    <input type="hidden" name="option_amount0" value="15.00">
    <input type="hidden" name="option_select1" value="item2">
    <input type="hidden" name="option_amount1" value="25.00">
    <input type="hidden" name="option_select2" value="item3">
    <input type="hidden" name="option_amount2" value="75.00">
    <input type="hidden" name="option_select3" value="item4">
    <input type="hidden" name="option_amount3" value="150.00">
    <input type="hidden" name="option_select4" value="item4">
    <input type="hidden" name="option_amount4" value="300.00">
    <input type="hidden" name="option_index" value="0">


    <input type="hidden" name="discount_amount">

    <br />
    <!--  Enter Coupon  --> 
    <center>Coupon Code:</span> <br />
    <input type="text" name="text1" /> </center>
    <br />
    <!--  End Coupon  --> 

    <input type="image" src="images/btn_cart.gif" border="0" onclick=CalculateOrder(this.form) name="submit" >
    <img  border="0" src="images/btn_cart.gif"  >
    </form>

Javascript 文件是:

var coup1="Disc1";
var coup2="Disc2";
var coup3="Disc3";
var coup4="Disc4";



function CalculateOrder(form) 

if (form.text1.value == coup1 && ((form.option_amount.value>=25)))



form.discount_amount.value = "5";



if (form.text1.value == coup2 && ((form.option_amount.value>=50)))



form.discount_amount.value = "10";





if (form.text1.value == coup3 && ((form.option_amount.value>=100)))



form.discount_amount.value = "20";




if (form.text1.value == coup4) && ((form.option_amount.value>=250)))



form.discount_amount.value = "50";




如何从 HTML 表单中创建 option_amount 的脚本帐户? 任何帮助将不胜感激!

【问题讨论】:

【参考方案1】:

我正在使用 PayPalMerchantSDK 进行购物车集成。

对于您的回答,我采用这种情况,因为我需要使用快速结帐按钮将购物篮发送到贝宝。我的篮子里还有一张可以申请总金额的折扣券。我正在使用 Asp.Net MVC 解决方案

请按照贝宝支付集成的代码和说明进行操作。

第一步:下载并参考 PayPal_Merchant_SDK.dll

第 2 步:将所需的设置添加到您的 PayPal_Merchant_SDK 服务的 web.config 文件中

第 3 步:在您的购物篮控制器付款操作中添加以下代码

    [HttpPost]
    public ActionResult Payment()
    
        var basketForPayment = GetBasket();
        if (basketForPayment.Order == null || basketForPayment.OrderItem.Count <= 0 || basketForPayment.Order.DVEcomOrderStatus.ID != (int)DvEcomOrderStatusEnum.Initiated)  return View("basket-empty", new DvClientViewModel(UrlBasketEmptyPage, Languages.English)); 


        //Paypal Expresscheckout Integration===============================

        // Step 1: Create the paypal request object
        var request = new SetExpressCheckoutRequestType();
        PopulatePaypalRequestObject(request, basketForPayment);

        // Step 2: Invoke the API
        SetExpressCheckoutReq getTockenWrapper = new SetExpressCheckoutReq();
        getTockenWrapper.SetExpressCheckoutRequest = request;
        PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService();
        SetExpressCheckoutResponseType setEcResponse = service.SetExpressCheckout(getTockenWrapper);

        // Step 3: Check for API return status and get the payment tocken
        HttpContext currContext = System.Web.HttpContext.Current;
        currContext.Items.Add("paymentDetails", request.SetExpressCheckoutRequestDetails.PaymentDetails);
        var currResponseContext = SetPayPalKeyResponseObjects(service, setEcResponse);

        var responseobject = (Dictionary<string, string>) currResponseContext.Items["Response_keyResponseObject"];
        if (responseobject["API Status"] != "SUCCESS")
        
            return View("Invalid-basket", new DvClientViewModel(UrlBasketEmptyPage, Languages.English));
        

        //Step 4: Make Payment with the tocken
        var tocken = responseobject["EC token"];
        string queryString = "https://www.sandbox.paypal.com/webscr?cmd=_express-checkout";
        if(!string.IsNullOrEmpty(tocken))
        

            //Update Order with the transaction token
            _orderRepository.UpdateOrder(model.Order.OrderNumber, tocken);

            queryString += string.Format("&token=0", tocken);
            Response.Redirect(queryString);
        

        return RedirectToAction("Payment");
    

第 4 步:您的付款响应操作

    public ActionResult PaymentResponse()
    
        // If we have a SECURE_SECRET then validate the incoming data using the MD5 hash
        //included in the incoming data
        if (Request.QueryString["token"].Length > 0 && Request.QueryString["PayerID"].Length > 0 )
        
            var token = Request.QueryString["token"];
            var payerId = Request.QueryString["PayerID"];
            var order = _orderRepository.GetOrderTransaction(token);

            if(order !=null)
            
                //Update Order with the transaction token
                _orderRepository.UpdateOrderSuccess(order.OrderNumber, token, payerId);
            

            PaymentResponseClearSessionAndCookie();
            Response.Redirect("/");

        

        return View("Invalid-basket", new DvClientViewModel(UrlBasketEmptyPage, Languages.English));

    

第 5 步:为 paypal 准备购物篮

   private void PopulatePaypalRequestObject(SetExpressCheckoutRequestType request, DvEcomOrderViewModel basket)
    
        var ecDetails = new SetExpressCheckoutRequestDetailsType();
        ecDetails.ReturnURL = ConfigurationManager.AppSettings["PayPalReturnUrl"];            ecDetails.CancelURL = ConfigurationManager.AppSettings["PayPalCancelUrl"];            ecDetails.BuyerEmail = basket.Order.CustomerEmailAddress;

        //Fix for release
        ecDetails.AddressOverride = "0";
        ecDetails.NoShipping = "1";

        /* Populate payment requestDetails. 
         * SetExpressCheckout allows parallel payments of upto 10 payments. 
         * This samples shows just one payment.
         */
        var paymentDetails = new PaymentDetailsType();
        ecDetails.PaymentDetails.Add(paymentDetails);
        double orderTotal = 0.0;
        double itemTotal = 0.0;
        var currency = (CurrencyCodeType)
            Enum.Parse(typeof(CurrencyCodeType), ConfigurationManager.AppSettings["PayPalCurrency"]);


        paymentDetails.OrderTotal = new BasicAmountType(currency, orderTotal.ToString(CultureInfo.InvariantCulture));
        orderTotal += Double.Parse(basket.Order.SubTotal.ToString(CultureInfo.InvariantCulture)); // Subtotal

        paymentDetails.ShippingTotal = new BasicAmountType(currency, basket.Order.DeliveryAmount.ToString(CultureInfo.InvariantCulture)); // Add delivery charge
        orderTotal += Double.Parse(basket.Order.DeliveryAmount.ToString(CultureInfo.InvariantCulture));

        paymentDetails.TaxTotal = new BasicAmountType(currency, basket.Order.VAT.ToString(CultureInfo.InvariantCulture)); //Add Vat Tax
        orderTotal += Double.Parse(basket.Order.VAT.ToString(CultureInfo.InvariantCulture));

        //paymentDetails.ShippingDiscount = new BasicAmountType(currency, basket.Order.DiscountAmount.ToString(CultureInfo.InvariantCulture)); // Subtract discount
        orderTotal -= Double.Parse(basket.Order.DiscountAmount.ToString(CultureInfo.InvariantCulture));


        paymentDetails.OrderDescription = string.Format("Payment for the basket order 0", basket.Order.OrderNumber);

        paymentDetails.PaymentAction = (PaymentActionCodeType)
            Enum.Parse(typeof(PaymentActionCodeType), "SALE");


        AddressType shipAddress = new AddressType();
        shipAddress.Name = string.Format("0 1", basket.Order.DeliveryFirstName, basket.Order.DeliverySurname);
        shipAddress.Street1 = basket.Order.BillingAddress1;
        shipAddress.Street2 = basket.Order.BillingAddress2 ?? "-";
        shipAddress.CityName = basket.Order.DeliveryTown ?? "-";
        shipAddress.StateOrProvince = basket.Order.DeliveryCounty;
        shipAddress.Country = (CountryCodeType)
            Enum.Parse(typeof(CountryCodeType), "GB");
        shipAddress.PostalCode = basket.Order.DeliveryPostcode;

        //Fix for release
        shipAddress.Phone = basket.Order.DeliveryTelePhone;

        ecDetails.PaymentDetails[0].ShipToAddress = shipAddress;


        // Each payment can include requestDetails about multiple items
        // This example shows just one payment item

        //ApplyDiscount
        if (basket.Order.DiscountAmount > 0)
        
            decimal disAmt = basket.Order.DiscountAmount -
                             (basket.Order.DiscountAmount + basket.Order.DiscountAmount);
            PaymentDetailsItemType discount = new PaymentDetailsItemType();
            discount.Amount = new BasicAmountType(currency, disAmt.ToString(CultureInfo.InvariantCulture));
            discount.Description = "Discount Applied";
            discount.Name = "Voucher Code";
            paymentDetails.PaymentDetailsItem.Add(discount);
        

        var itemDetails = new PaymentDetailsItemType();
        foreach (var item in basket.OrderItem)
                        
            itemDetails.Name = item.ProductName;
            itemDetails.Amount = new BasicAmountType(currency, item.UnitPrice.ToString(CultureInfo.InvariantCulture));
            itemDetails.Quantity = Int32.Parse(item.Quantity.ToString(CultureInfo.InvariantCulture));
            itemDetails.ItemCategory = (ItemCategoryType)
            Enum.Parse(typeof(ItemCategoryType), "0");
            itemTotal += Double.Parse(item.UnitPrice.ToString(CultureInfo.InvariantCulture)) * itemDetails.Quantity.Value;

            itemDetails.Tax = new BasicAmountType(currency, item.VAT.ToString(CultureInfo.InvariantCulture));

            itemDetails.Description = item.ProductName;


            paymentDetails.PaymentDetailsItem.Add(itemDetails);
        

        itemTotal -= Double.Parse(basket.Order.DiscountAmount.ToString(CultureInfo.InvariantCulture));
        paymentDetails.ItemTotal = new BasicAmountType(currency, itemTotal.ToString(CultureInfo.InvariantCulture));
        paymentDetails.OrderTotal = new BasicAmountType(currency, orderTotal.ToString(CultureInfo.InvariantCulture));

        request.SetExpressCheckoutRequestDetails = ecDetails;
    

第 6 步:您无需再开始...

第 7 步:以上步骤将带您到 paypal 成功交易。接下来,您需要通过另一个 Paypal Authorize api 函数调用通过 Post 方法来授权真实的交易。过程同上。

【讨论】:

我正在尝试您的方法,但我不明白何时“PaymentResponse()”以及如何调用“PaymentResponse()”。你能澄清一下吗?我的流程是使用 Ajax 到付款方法,然后获取 Redirect_URL 并在客户端提示新的付款窗口。但是我怎么知道付款是否完成。用户可以在不离开页面的情况下进行交易吗?谢谢。 +1 感谢您提供此代码摘录。这与当今世界(即 2017 年)应该使用的工作流程相同吗?和/或是否有任何改变???【参考方案2】:

我找到了一个解决方案,虽然有点长,但它仍然可以达到目的。

我对 js 代码做了类似的事情:

var coup1="Disc1";
var coup2="Disc2";
var coup3="Disc3";
var coup4="Disc4";



function CalculateOrder(form) 

if (form.text1.value == coup1 && (form.os0.value == "item2" || form.os0.value == "item3" || form.os0.value == "item4" || form.os0.value == "item5"))



form.discount_amount.value = "5";



if (form.text1.value == coup2 && (form.os0.value == "item3" || form.os0.value == "item4" || form.os0.value == "item5"))



form.discount_amount.value = "10";





if (form.text1.value == coup3 && (form.os0.value == "item4" || form.os0.value == "item5"))



form.discount_amount.value = "20";




if (form.text1.value == coup4 && (form.os0.value == "item5"))



form.discount_amount.value = "50";




【讨论】:

以上是关于Paypal 以折扣方式将多个商品添加到购物车的主要内容,如果未能解决你的问题,请参考以下文章

检测到 Paypal 购物车错误

如何将折扣代码添加到我的购物车并将其发送到贝宝结帐?

将购物车商品数据发送到 PayPal WooCommerce

无法添加多个项目以快速结帐贝宝

如何将项目添加到 PayPal API 中的项目列表

Paypal 整合到现有的购物车