61763

Paypal add to cart multiple items form with discount

Question:

I'm trying to offer a discount based on the purchase amount of the buyer using a paypal Add to Cart form. Basically I'm giving out for discount codes Disc1, Disc2, Disc3, Disc4, which will discount $5, $10, $20, $50. But each can work only if the purchase amount exceeds the $25, $50, $100, $250 respectively.

I'm trying to do this by calling a Javascript file which will apply the discount if the minimum price conditions are met.

The PROBLEM is that the form is for multiple items. So the variable for "amount" is not there, but there's different amounts for each option, so option_amount0, option_amount1, option_amount2.... etc. I can make the code work if there was one "amount", but not like here with multiple items/prices.

The HTML code looks like this:

<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" alt="PayPal - The safer, easier way to pay online!"> <img alt="" border="0" src="images/btn_cart.gif" width="1" height="1"> </form>

The Javascript file is:

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"; } }

How can I make the script account for the option_amount from the HTML form? Any help would be greatly appreciated!

Answer1:

I am using PayPalMerchantSDK for the cart integration.

For your answer, I take this scenario as I need to send the basket to paypal with express checkout button. Also my basket has a discount voucher that can apply for the total amount. I am using Asp.Net MVC solutions

Please follow the code and instructions for the paypal payment integration.

<strong>Step1 :</strong> Download and Refer the PayPal_Merchant_SDK.dll

<strong>Step2 :</strong> Add the required setting to your web.config file for the PayPal_Merchant_SDK Servicess

<strong>Step 3:</strong> In your basket controller Payment action add the following code

[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"); }

<strong>Step 4:</strong> Your Payment response action

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)); }

<strong>Step 5:</strong> Prepare the basket for 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; }

<strong>Step 6:</strong> Nothing more for you to start with...

Step 7 : The above steps will take you up to the paypal successfull transation. Next you need to authorise the real tansaction through another Paypal Authorise api function call through a Post method. The process is same as the above procedure.

Answer2:

i found a solution, although a bit long, it still does the purpose.

I did to the js code, somthing like:

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"; } }

Recommend

  • Magento get coupon description
  • Java JDK - possible lossy conversion from double to int
  • Excel Min Date in a given range
  • Stacked Bar Chart with percentage composition inside the Bar and total above the Bar in JFreeChart
  • jParallax trouble
  • How to get a table cell value using jQuery
  • How can I make a 100% stacked chart with nvd3?
  • PHP file_exists() anomaly
  • Small video playback
  • window.onbeforeunload in javascript
  • Nodejs bluebird promise fails while processing image
  • Adding independent aspx/asmx pages into DotNetNuke
  • Passing information to server-side function in a Google Docs Add On
  • File loader changed image file name but not the file name in HTML file
  • Send data from edittext to listview
  • How to apply a custom handlers to only specific folder
  • Streaming screenshots over WebRTC as a video stream from iOS
  • Is it possible to get the word under the mouse cursor in a ``?
  • Jquery Mobile pageLoading() Method how does it work?
  • Outputting SharePoint Hyperlink Column as URL
  • Simulate click Geckofx vb,net
  • Button click event not firing in jQuery
  • Moving Android View and preventing onDraw to be called over and over again
  • how to display data from 1st point on words on y axis for line chart in d3.js
  • chrome.tabs.executeScript only fires when the Developer Console is open
  • HTTP/2 streams vs HTTP/1.1 connections
  • JSON response opens as a file, but I can't access it with JavaScript
  • Syntax for setting draggablecursor property in google maps api
  • Repeat a vertical line on every page in Report Builder / SSRS
  • Change JButton Shape while respecting Look And Feel
  • Insert into database using onclick function
  • req.body is undefined - nodejs
  • jquery mobile loadPage not working
  • Web-crawler for facebook in python
  • GridView Sorting works once only
  • How to get icons for entities from eclipse?
  • How to CLICK on IE download dialog box i.e.(Open, Save, Save As…)
  • How can I remove ASP.NET Designer.cs files?
  • failed to connect to specific WiFi in android programmatically
  • java string with new operator and a literal