Ejemplo n.º 1
0
        /// <summary>
        /// Manually adjusts the net prices for cart items to avoid rounding differences with the PayPal API.
        /// </summary>
        /// <param name="paypalItems">PayPal line items</param>
        /// <param name="postProcessPaymentRequest">Post process paymenmt request object</param>
        /// <remarks>
        /// In detail: We add what we have thrown away in the checkout when we rounded prices to two decimal places.
        /// It's a workaround. Better solution would be to store the thrown away decimal places for each OrderItem in the database.
        /// More details: http://magento.xonu.de/magento-extensions/empfehlungen/magento-paypal-rounding-error-fix/
        /// </remarks>
        public void AdjustLineItemAmounts(List<PayPalLineItem> paypalItems, PostProcessPaymentRequest postProcessPaymentRequest)
        {
            try
            {
                var cartItems = paypalItems.Where(x => x.Type == PayPalItemType.CartItem);

                if (cartItems.Count() <= 0)
                    return;

                decimal totalSmartStore = Math.Round(postProcessPaymentRequest.Order.OrderSubtotalExclTax, 2);
                decimal totalPayPal = decimal.Zero;
                decimal delta, portion, rest;

                // calculate what PayPal calculates
                cartItems.Each(x => totalPayPal += (x.AmountRounded * x.Quantity));
                totalPayPal = Math.Round(totalPayPal, 2, MidpointRounding.AwayFromZero);

                // calculate difference
                delta = Math.Round(totalSmartStore - totalPayPal, 2);
                if (delta == decimal.Zero)
                    return;

                // prepare lines... only lines with quantity = 1 are adjustable. if there is no one, create one.
                if (!cartItems.Any(x => x.Quantity == 1))
                {
                    var item = cartItems.First(x => x.Quantity > 1);
                    item.Quantity -= 1;
                    var newItem = item.Clone();
                    newItem.Quantity = 1;
                    paypalItems.Insert(paypalItems.IndexOf(item) + 1, newItem);
                }

                var cartItemsOneQuantity = paypalItems.Where(x => x.Type == PayPalItemType.CartItem && x.Quantity == 1);
                Debug.Assert(cartItemsOneQuantity.Count() > 0);

                SplitDifference(delta, cartItemsOneQuantity.Count(), out portion, out rest);

                if (portion != decimal.Zero)
                {
                    cartItems
                        .Where(x => x.Quantity == 1)
                        .Each(x => x.Amount = x.Amount + portion);
                }

                if (rest != decimal.Zero)
                {
                    var restItem = cartItems.First(x => x.Quantity == 1);
                    restItem.Amount = restItem.Amount + rest;
                }

                //"SM: {0}, PP: {1}, delta: {2} (portion: {3}, rest: {4})".FormatWith(totalSmartStore, totalPayPal, delta, portion, rest).Dump();
            }
            catch (Exception exc)
            {
                _logger.Error(exc.Message, exc);
            }
        }
		/// <summary>
		/// Post process payment (used by payment gateways that require redirecting to a third-party URL)
		/// </summary>
		/// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
		public override void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
		{
			if (postProcessPaymentRequest.Order.PaymentStatus == PaymentStatus.Paid)
				return;
			var settings = _services.Settings.LoadSetting<PayUMeaStandardPaymentSettings>(postProcessPaymentRequest.Order.StoreId);
			if (_payUApiComms == null)
			{

				_payUApiComms = new RunPayUComms(settings.Username, settings.Password, settings.ApiUrl, settings.SafeKey, "ONE_ZERO");
			}
			string cancelReturnUrl = _services.WebHelper.GetStoreLocation(false) + "Plugins/PaymentPayUPayUMeaStandard/CancelOrder";
			var orderid = postProcessPaymentRequest.Order.GetOrderNumber();
			string returnUrl = string.Format("{0}Plugins/PaymentPayUMeaStandard/PDTHandler?orderId={1}", _services.WebHelper.GetStoreLocation(false), orderid);
			var setTransactionResult = _payUApiComms.SetTransaction(new SetTransactionRequest
			{
				AmountInCents = Math.Truncate(postProcessPaymentRequest.Order.OrderTotal * 100).ToString(CultureInfo.InvariantCulture),
				CancelUrl = cancelReturnUrl,
				CustomerEmail = postProcessPaymentRequest.Order.BillingAddress.Email,
				CustomerLastname = postProcessPaymentRequest.Order.BillingAddress.LastName,
				CustomerMobile = postProcessPaymentRequest.Order.BillingAddress.PhoneNumber,
				CustomerName = postProcessPaymentRequest.Order.BillingAddress.FirstName,
				CustomerUsername = postProcessPaymentRequest.Order.Customer.Username,
				LineItems = postProcessPaymentRequest.Order.OrderItems.Select(x => new LineItem
				{
					Amount = Math.Truncate(x.PriceInclTax * 100).ToString(CultureInfo.InvariantCulture),
					Description = x.Product.Name,
					ProductCode = x.Product.Sku,
					Quantity = x.Quantity.ToString()
				}).ToList(),
				OrderNumber =  postProcessPaymentRequest.Order.OrderGuid.ToString(),
				PaymentTypes = null,
				ReturnUrl = returnUrl,
				Stage = false
			});
			if (!setTransactionResult.IsTransactionSet)
				throw new Exception(string.Format("Failed to Preprocess transaction with PayU ### {0} ###>> {1}:{2}:{3}", setTransactionResult.ErrorMessage, postProcessPaymentRequest.Order.BillingAddress.Email, postProcessPaymentRequest.Order.OrderNumber, postProcessPaymentRequest.Order.OrderGuid));
			_httpContext.Response.Redirect(string.Format("{0}?PayUReference={1}", settings.RedirectUrl, setTransactionResult.PayUReference));
		}
		/// <summary>
		/// Get all PayU line items
		/// </summary>
		/// <param name="postProcessPaymentRequest">Post process paymenmt request object</param>
		/// <param name="checkoutAttributeValues">List with checkout attribute values</param>
		/// <param name="cartTotal">Receives the calculated cart total amount</param>
		/// <returns>All items for PayU Standard API</returns>
		public List<PayUMeaLineItem> GetLineItems(PostProcessPaymentRequest postProcessPaymentRequest, out decimal cartTotal)
		{
			cartTotal = decimal.Zero;

			var order = postProcessPaymentRequest.Order;
			var lst = new List<PayUMeaLineItem>();

			// order items
			foreach (var orderItem in order.OrderItems)
			{
				var item = new PayUMeaLineItem()
				{
					Type = PayUMeaItemType.CartItem,
					Name = orderItem.Product.GetLocalized(x => x.Name),
					Quantity = orderItem.Quantity,
					Amount = orderItem.UnitPriceExclTax
				};
				lst.Add(item);

				cartTotal += orderItem.PriceExclTax;
			}
			if (order.OrderShippingExclTax > decimal.Zero)
			{
				var item = new PayUMeaLineItem()
				{
					Type = PayUMeaItemType.Shipping,
					Name = T("Plugins.Payments.PayUStandard.ShippingFee").Text,
					Quantity = 1,
					Amount = order.OrderShippingExclTax
				};
				lst.Add(item);

				cartTotal += order.OrderShippingExclTax;
			}

			// payment fee
			if (order.PaymentMethodAdditionalFeeExclTax > decimal.Zero)
			{
				var item = new PayUMeaLineItem()
				{
					Type = PayUMeaItemType.PaymentFee,
					Name = T("Plugins.Payments.PayUStandard.PaymentMethodFee").Text,
					Quantity = 1,
					Amount = order.PaymentMethodAdditionalFeeExclTax
				};
				lst.Add(item);

				cartTotal += order.PaymentMethodAdditionalFeeExclTax;
			}

			// tax
			if (order.OrderTax > decimal.Zero)
			{
				var item = new PayUMeaLineItem()
				{
					Type = PayUMeaItemType.Tax,
					Name = T("Plugins.Payments.PayUStandard.SalesTax").Text,
					Quantity = 1,
					Amount = order.OrderTax
				};
				lst.Add(item);

				cartTotal += order.OrderTax;
			}

			return lst;
		}
        public ActionResult RePostPayment(int id)
        {
            var order = _orderService.GetOrderById(id);

			if (IsNonExistentOrder(order))
				return HttpNotFound();

			if (IsUnauthorizedOrder(order))
				return new HttpUnauthorizedResult();

            if (!_paymentService.CanRePostProcessPayment(order))
				return RedirectToAction("Details", "Order", new { id = order.Id });

            var postProcessPaymentRequest = new PostProcessPaymentRequest()
            {
                Order = order,
				IsRePostProcessPayment = true
            };
            _paymentService.PostProcessPayment(postProcessPaymentRequest);

            if (_services.WebHelper.IsRequestBeingRedirected || _services.WebHelper.IsPostBeingDone)
            {
                //redirection or POST has been done in PostProcessPayment
                return Content("Redirected");
            }
            else
            {
                //if no redirection has been done (to a third-party payment page)
                //theoretically it's not possible
				return RedirectToAction("Details", "Order", new { id = order.Id });
            }
        }
		/// <summary>
		/// Post process payment (used by payment gateways that require redirecting to a third-party URL)
		/// </summary>
		/// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
		public virtual void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
		{
			// NoImpl
		}
        public ActionResult ConfirmOrder(FormCollection form)
        {
            //validation
			var cart = _workContext.CurrentCustomer.GetCartItems(ShoppingCartType.ShoppingCart, _storeContext.CurrentStore.Id);

			if (cart.Count == 0)
                return RedirectToRoute("ShoppingCart");

            if ((_workContext.CurrentCustomer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed))
                return new HttpUnauthorizedResult();


            //model
            var model = new CheckoutConfirmModel();
            try
            {
                var processPaymentRequest = _httpContext.Session["OrderPaymentInfo"] as ProcessPaymentRequest;
                if (processPaymentRequest == null)
                {
                    //Check whether payment workflow is required
					if (IsPaymentWorkflowRequired(cart))
						return RedirectToAction("PaymentMethod");

					processPaymentRequest = new ProcessPaymentRequest();
                }
                
                //prevent 2 orders being placed within an X seconds time frame
                if (!IsMinimumOrderPlacementIntervalValid(_workContext.CurrentCustomer))
                    throw new Exception(_localizationService.GetResource("Checkout.MinOrderPlacementInterval"));

                //place order
				processPaymentRequest.StoreId = _storeContext.CurrentStore.Id;
                processPaymentRequest.CustomerId = _workContext.CurrentCustomer.Id;
				processPaymentRequest.PaymentMethodSystemName = _workContext.CurrentCustomer.GetAttribute<string>(
					 SystemCustomerAttributeNames.SelectedPaymentMethod, _genericAttributeService, _storeContext.CurrentStore.Id);

                var placeOrderExtraData = new Dictionary<string, string>();
                placeOrderExtraData["CustomerComment"] = form["customercommenthidden"];

                var placeOrderResult = _orderProcessingService.PlaceOrder(processPaymentRequest, placeOrderExtraData);

                if (placeOrderResult.Success)
                {
					var postProcessPaymentRequest = new PostProcessPaymentRequest
					{
						Order = placeOrderResult.PlacedOrder
					};
					_paymentService.PostProcessPayment(postProcessPaymentRequest);

					_httpContext.Session["PaymentData"] = null;
					_httpContext.Session["OrderPaymentInfo"] = null;
					_httpContext.RemoveCheckoutState();

                    if (_webHelper.IsRequestBeingRedirected || _webHelper.IsPostBeingDone)
                    {
                        //redirection or POST has been done in PostProcessPayment
                        return Content("Redirected");
                    }
                    else
                    {
                        //if no redirection has been done (to a third-party payment page)
                        //theoretically it's not possible
                        return RedirectToAction("Completed");
                    }
                }
                else
                {
                    foreach (var error in placeOrderResult.Errors)
                        model.Warnings.Add(error);
                }
            }
            catch (Exception exc)
            {
				Logger.Warning(exc.Message, exc);
                model.Warnings.Add(exc.Message);
            }

            //If we got this far, something failed, redisplay form

			//if (model.Warnings.Count > 0)
			//	TempData["ConfirmOrderWarnings"] = model.Warnings;

			//return RedirectToRoute("CheckoutConfirm");
            return View(model);
        }
        public ActionResult OpcCompleteRedirectionPayment()
        {
            try
            {
                //validation
                if (!UseOnePageCheckout())
                    return RedirectToRoute("HomePage");

                if ((_workContext.CurrentCustomer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed))
                    return new HttpUnauthorizedResult();

                //get the order
				var order = _orderService.SearchOrders(_storeContext.CurrentStore.Id, _workContext.CurrentCustomer.Id,
					null, null, null, null, null, null, null, null, 0, 1)
					.FirstOrDefault();
				if (order == null)
                    return RedirectToRoute("HomePage");


                var paymentMethod = _paymentService.LoadPaymentMethodBySystemName(order.PaymentMethodSystemName);
                if (paymentMethod == null)
                    return RedirectToRoute("HomePage");
                if (paymentMethod.PaymentMethodType != PaymentMethodType.Redirection)
                    return RedirectToRoute("HomePage");

                //ensure that order has been just placed
                if ((DateTime.UtcNow - order.CreatedOnUtc).TotalMinutes > 3)
                    return RedirectToRoute("HomePage");


                //Redirection will not work on one page checkout page because it's AJAX request.
                //That's why we process it here
                var postProcessPaymentRequest = new PostProcessPaymentRequest()
                {
                    Order = order
                };

                _paymentService.PostProcessPayment(postProcessPaymentRequest);

                if (_webHelper.IsRequestBeingRedirected || _webHelper.IsPostBeingDone)
                {
                    //redirection or POST has been done in PostProcessPayment
                    return Content("Redirected");
                }
                else
                {
                    //if no redirection has been done (to a third-party payment page)
                    //theoretically it's not possible
                    return RedirectToRoute("CheckoutCompleted");
                }
            }
            catch (Exception exc)
            {
				Logger.Warning(exc.Message, exc, _workContext.CurrentCustomer);
                return Content(exc.Message);
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Post process payment (used by payment gateways that require redirecting to a third-party URL)
        /// </summary>
        /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
        public virtual void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
        {
            //already paid or order.OrderTotal == decimal.Zero
            if (postProcessPaymentRequest.Order.PaymentStatus == PaymentStatus.Paid)
                return;

            var paymentMethod = LoadPaymentMethodBySystemName(postProcessPaymentRequest.Order.PaymentMethodSystemName);
            if (paymentMethod == null)
                throw new SmartException("Payment method couldn't be loaded");
            paymentMethod.PostProcessPayment(postProcessPaymentRequest);
        }
Ejemplo n.º 9
0
        public ActionResult ConfirmOrder(FormCollection form)
        {
            //validation
            var cart = _workContext.CurrentCustomer.GetCartItems(ShoppingCartType.ShoppingCart, _storeContext.CurrentStore.Id);

            if (cart.Count == 0)
                return RedirectToRoute("ShoppingCart");

            if ((_workContext.CurrentCustomer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed))
                return new HttpUnauthorizedResult();

            //model
            var model = new CheckoutConfirmModel();
            try
            {
                var processPaymentRequest = _httpContext.Session["OrderPaymentInfo"] as ProcessPaymentRequest;
                if (processPaymentRequest == null)
                {
                    //Check whether payment workflow is required
                    if (IsPaymentWorkflowRequired(cart))
                        return RedirectToAction("PaymentMethod");

                    processPaymentRequest = new ProcessPaymentRequest();
                }

                //prevent 2 orders being placed within an X seconds time frame
                if (!IsMinimumOrderPlacementIntervalValid(_workContext.CurrentCustomer))
                    throw new Exception(_localizationService.GetResource("Checkout.MinOrderPlacementInterval"));

                //place order
                processPaymentRequest.StoreId = _storeContext.CurrentStore.Id;
                processPaymentRequest.CustomerId = _workContext.CurrentCustomer.Id;
                processPaymentRequest.PaymentMethodSystemName = _workContext.CurrentCustomer.GetAttribute<string>(
                     SystemCustomerAttributeNames.SelectedPaymentMethod, _genericAttributeService, _storeContext.CurrentStore.Id);

                var placeOrderExtraData = new Dictionary<string, string>();
                placeOrderExtraData["CustomerComment"] = form["customercommenthidden"];

                var placeOrderResult = _orderProcessingService.PlaceOrder(processPaymentRequest, placeOrderExtraData);
                // _httpContext.Session["Cart"] = processPaymentRequest;
                _httpContext.Session["PlaceOrderId"] = placeOrderResult.PlacedOrder.Id;
                _httpContext.Session["Total"] = placeOrderResult.PlacedOrder.OrderTotal;
                if (placeOrderResult.Success)
                {
                    var postProcessPaymentRequest = new PostProcessPaymentRequest
                    {
                        Order = placeOrderResult.PlacedOrder
                    };

                    _paymentService.PostProcessPayment(postProcessPaymentRequest);

                    _httpContext.Session["PaymentData"] = null;
                    _httpContext.Session["OrderPaymentInfo"] = null;
                    _httpContext.RemoveCheckoutState();

                    if (postProcessPaymentRequest.RedirectUrl.HasValue())
                    {
                        return Redirect(postProcessPaymentRequest.RedirectUrl);
                    }

                    return RedirectToAction("Completed");
                }
                else
                {
                    model.Warnings.AddRange(placeOrderResult.Errors);
                }
            }
            catch (Exception exc)
            {
                Logger.Warning(exc.Message, exc);
                model.Warnings.Add(exc.Message);
            }

            return View(model);
        }
        /// <summary>
        /// Post process payment (used by payment gateways that require redirecting to a third-party URL)
        /// </summary>
        /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
        public override void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
        {
            if (postProcessPaymentRequest.Order.PaymentStatus == PaymentStatus.Paid)
                return;

            var settings = _commonServices.Settings.LoadSetting<PayPalStandardPaymentSettings>(postProcessPaymentRequest.Order.StoreId);

            var builder = new StringBuilder();
            builder.Append(PayPalHelper.GetPaypalUrl(settings));

            string orderNumber = postProcessPaymentRequest.Order.GetOrderNumber();
            string cmd = (settings.PassProductNamesAndTotals ? "_cart" : "_xclick");

            builder.AppendFormat("?cmd={0}&business={1}", cmd, HttpUtility.UrlEncode(settings.BusinessEmail));

            if (settings.PassProductNamesAndTotals)
            {
                builder.AppendFormat("&upload=1");

                int index = 0;
                decimal cartTotal = decimal.Zero;
                //var caValues = _checkoutAttributeParser.ParseCheckoutAttributeValues(postProcessPaymentRequest.Order.CheckoutAttributesXml);

                var lineItems = GetLineItems(postProcessPaymentRequest, out cartTotal);

                AdjustLineItemAmounts(lineItems, postProcessPaymentRequest);

                foreach (var item in lineItems.OrderBy(x => (int)x.Type))
                {
                    ++index;
                    builder.AppendFormat("&item_name_" + index + "={0}", HttpUtility.UrlEncode(item.Name));
                    builder.AppendFormat("&amount_" + index + "={0}", item.AmountRounded.ToString("0.00", CultureInfo.InvariantCulture));
                    builder.AppendFormat("&quantity_" + index + "={0}", item.Quantity);
                }

                #region old code

                //var cartItems = postProcessPaymentRequest.Order.OrderItems;
                //int x = 1;
                //foreach (var item in cartItems)
                //{
                //	var unitPriceExclTax = item.UnitPriceExclTax;
                //	var priceExclTax = item.PriceExclTax;
                //	//round
                //	var unitPriceExclTaxRounded = Math.Round(unitPriceExclTax, 2);

                //	builder.AppendFormat("&item_name_" + x + "={0}", HttpUtility.UrlEncode(item.Product.Name));
                //	builder.AppendFormat("&amount_" + x + "={0}", unitPriceExclTaxRounded.ToString("0.00", CultureInfo.InvariantCulture));
                //	builder.AppendFormat("&quantity_" + x + "={0}", item.Quantity);
                //	x++;
                //	cartTotal += priceExclTax;
                //}

                ////the checkout attributes that have a dollar value and send them to Paypal as items to be paid for
                //foreach (var val in caValues)
                //{
                //	var attPrice = _taxService.GetCheckoutAttributePrice(val, false, postProcessPaymentRequest.Order.Customer);
                //	//round
                //	var attPriceRounded = Math.Round(attPrice, 2);
                //	if (attPrice > decimal.Zero) //if it has a price
                //	{
                //		var ca = val.CheckoutAttribute;
                //		if (ca != null)
                //		{
                //			var attName = ca.Name; //set the name
                //			builder.AppendFormat("&item_name_" + x + "={0}", HttpUtility.UrlEncode(attName)); //name
                //			builder.AppendFormat("&amount_" + x + "={0}", attPriceRounded.ToString("0.00", CultureInfo.InvariantCulture)); //amount
                //			builder.AppendFormat("&quantity_" + x + "={0}", 1); //quantity
                //			x++;
                //			cartTotal += attPrice;
                //		}
                //	}
                //}

                ////order totals

                ////shipping
                //var orderShippingExclTax = postProcessPaymentRequest.Order.OrderShippingExclTax;
                //var orderShippingExclTaxRounded = Math.Round(orderShippingExclTax, 2);
                //if (orderShippingExclTax > decimal.Zero)
                //{
                //	builder.AppendFormat("&item_name_" + x + "={0}", HttpUtility.UrlEncode(_localizationService.GetResource("Plugins.Payments.PayPalStandard.ShippingFee")));
                //	builder.AppendFormat("&amount_" + x + "={0}", orderShippingExclTaxRounded.ToString("0.00", CultureInfo.InvariantCulture));
                //	builder.AppendFormat("&quantity_" + x + "={0}", 1);
                //	x++;
                //	cartTotal += orderShippingExclTax;
                //}

                ////payment method additional fee
                //var paymentMethodAdditionalFeeExclTax = postProcessPaymentRequest.Order.PaymentMethodAdditionalFeeExclTax;
                //var paymentMethodAdditionalFeeExclTaxRounded = Math.Round(paymentMethodAdditionalFeeExclTax, 2);
                //if (paymentMethodAdditionalFeeExclTax > decimal.Zero)
                //{
                //	builder.AppendFormat("&item_name_" + x + "={0}", HttpUtility.UrlEncode(_localizationService.GetResource("Plugins.Payments.PayPalStandard.PaymentMethodFee")));
                //	builder.AppendFormat("&amount_" + x + "={0}", paymentMethodAdditionalFeeExclTaxRounded.ToString("0.00", CultureInfo.InvariantCulture));
                //	builder.AppendFormat("&quantity_" + x + "={0}", 1);
                //	x++;
                //	cartTotal += paymentMethodAdditionalFeeExclTax;
                //}

                ////tax
                //var orderTax = postProcessPaymentRequest.Order.OrderTax;
                //var orderTaxRounded = Math.Round(orderTax, 2);
                //if (orderTax > decimal.Zero)
                //{
                //	//builder.AppendFormat("&tax_1={0}", orderTax.ToString("0.00", CultureInfo.InvariantCulture));

                //	//add tax as item
                //	builder.AppendFormat("&item_name_" + x + "={0}", HttpUtility.UrlEncode(_localizationService.GetResource("Plugins.Payments.PayPalStandard.SalesTax")));
                //	builder.AppendFormat("&amount_" + x + "={0}", orderTaxRounded.ToString("0.00", CultureInfo.InvariantCulture)); //amount
                //	builder.AppendFormat("&quantity_" + x + "={0}", 1); //quantity

                //	cartTotal += orderTax;
                //	x++;
                //}

                #endregion

                if (cartTotal > postProcessPaymentRequest.Order.OrderTotal)
                {
                    /* Take the difference between what the order total is and what it should be and use that as the "discount".
                     * The difference equals the amount of the gift card and/or reward points used.
                     */
                    decimal discountTotal = cartTotal - postProcessPaymentRequest.Order.OrderTotal;
                    discountTotal = Math.Round(discountTotal, 2);
                    //gift card or rewared point amount applied to cart in SmartStore.NET - shows in Paypal as "discount"
                    builder.AppendFormat("&discount_amount_cart={0}", discountTotal.ToString("0.00", CultureInfo.InvariantCulture));
                }
            }
            else
            {
                //pass order total
                string totalItemName = "{0} {1}".FormatWith(T("Checkout.OrderNumber"), orderNumber);
                builder.AppendFormat("&item_name={0}", HttpUtility.UrlEncode(totalItemName));
                var orderTotal = Math.Round(postProcessPaymentRequest.Order.OrderTotal, 2);
                builder.AppendFormat("&amount={0}", orderTotal.ToString("0.00", CultureInfo.InvariantCulture));
            }

            builder.AppendFormat("&custom={0}", postProcessPaymentRequest.Order.OrderGuid);
            builder.AppendFormat("&charset={0}", "utf-8");
            builder.Append(string.Format("&no_note=1&currency_code={0}", HttpUtility.UrlEncode(_currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId).CurrencyCode)));
            builder.AppendFormat("&invoice={0}", HttpUtility.UrlEncode(orderNumber));
            builder.AppendFormat("&rm=2", new object[0]);

            Address address = null;

            if (postProcessPaymentRequest.Order.ShippingStatus != ShippingStatus.ShippingNotRequired)
            {
                address = postProcessPaymentRequest.Order.ShippingAddress ?? postProcessPaymentRequest.Order.BillingAddress;

                builder.AppendFormat("&no_shipping=2", new object[0]);
            }
            else
            {
                address = postProcessPaymentRequest.Order.BillingAddress;

                builder.AppendFormat("&no_shipping=1", new object[0]);
            }

            string returnUrl = _commonServices.WebHelper.GetStoreLocation(false) + "Plugins/PaymentPayPalStandard/PDTHandler";
            string cancelReturnUrl = _commonServices.WebHelper.GetStoreLocation(false) + "Plugins/PaymentPayPalStandard/CancelOrder";
            builder.AppendFormat("&return={0}&cancel_return={1}", HttpUtility.UrlEncode(returnUrl), HttpUtility.UrlEncode(cancelReturnUrl));

            //Instant Payment Notification (server to server message)
            if (settings.EnableIpn)
            {
                string ipnUrl;
                if (String.IsNullOrWhiteSpace(settings.IpnUrl))
                    ipnUrl = _commonServices.WebHelper.GetStoreLocation(false) + "Plugins/PaymentPayPalStandard/IPNHandler";
                else
                    ipnUrl = settings.IpnUrl;
                builder.AppendFormat("&notify_url={0}", ipnUrl);
            }

            //address
            builder.AppendFormat("&address_override=1");
            builder.AppendFormat("&first_name={0}", HttpUtility.UrlEncode(address.FirstName));
            builder.AppendFormat("&last_name={0}", HttpUtility.UrlEncode(address.LastName));
            builder.AppendFormat("&address1={0}", HttpUtility.UrlEncode(address.Address1));
            builder.AppendFormat("&address2={0}", HttpUtility.UrlEncode(address.Address2));
            builder.AppendFormat("&city={0}", HttpUtility.UrlEncode(address.City));
            //if (!String.IsNullOrEmpty(address.PhoneNumber))
            //{
            //    //strip out all non-digit characters from phone number;
            //    string billingPhoneNumber = System.Text.RegularExpressions.Regex.Replace(address.PhoneNumber, @"\D", string.Empty);
            //    if (billingPhoneNumber.Length >= 10)
            //    {
            //        builder.AppendFormat("&night_phone_a={0}", HttpUtility.UrlEncode(billingPhoneNumber.Substring(0, 3)));
            //        builder.AppendFormat("&night_phone_b={0}", HttpUtility.UrlEncode(billingPhoneNumber.Substring(3, 3)));
            //        builder.AppendFormat("&night_phone_c={0}", HttpUtility.UrlEncode(billingPhoneNumber.Substring(6, 4)));
            //    }
            //}
            if (address.StateProvince != null)
                builder.AppendFormat("&state={0}", HttpUtility.UrlEncode(address.StateProvince.Abbreviation));
            else
                builder.AppendFormat("&state={0}", "");

            if (address.Country != null)
                builder.AppendFormat("&country={0}", HttpUtility.UrlEncode(address.Country.TwoLetterIsoCode));
            else
                builder.AppendFormat("&country={0}", "");

            builder.AppendFormat("&zip={0}", HttpUtility.UrlEncode(address.ZipPostalCode));
            builder.AppendFormat("&email={0}", HttpUtility.UrlEncode(address.Email));

            _httpContext.Response.Redirect(builder.ToString());
        }
        /// <summary>
        /// Get all PayPal line items
        /// </summary>
        /// <param name="postProcessPaymentRequest">Post process paymenmt request object</param>
        /// <param name="checkoutAttributeValues">List with checkout attribute values</param>
        /// <param name="cartTotal">Receives the calculated cart total amount</param>
        /// <returns>All items for PayPal Standard API</returns>
        public List<PayPalLineItem> GetLineItems(PostProcessPaymentRequest postProcessPaymentRequest, out decimal cartTotal)
        {
            cartTotal = decimal.Zero;

            var order = postProcessPaymentRequest.Order;
            var lst = new List<PayPalLineItem>();

            // order items
            foreach (var orderItem in order.OrderItems)
            {
                var item = new PayPalLineItem()
                {
                    Type = PayPalItemType.CartItem,
                    Name = orderItem.Product.GetLocalized(x => x.Name),
                    Quantity = orderItem.Quantity,
                    Amount = orderItem.UnitPriceExclTax
                };
                lst.Add(item);

                cartTotal += orderItem.PriceExclTax;
            }

            // checkout attributes.... are included in order total
            //foreach (var caValue in checkoutAttributeValues)
            //{
            //	var attributePrice = _taxService.GetCheckoutAttributePrice(caValue, false, order.Customer);

            //	if (attributePrice > decimal.Zero && caValue.CheckoutAttribute != null)
            //	{
            //		var item = new PayPalLineItem()
            //		{
            //			Type = PayPalItemType.CheckoutAttribute,
            //			Name = caValue.CheckoutAttribute.GetLocalized(x => x.Name),
            //			Quantity = 1,
            //			Amount = attributePrice
            //		};
            //		lst.Add(item);

            //		cartTotal += attributePrice;
            //	}
            //}

            // shipping
            if (order.OrderShippingExclTax > decimal.Zero)
            {
                var item = new PayPalLineItem()
                {
                    Type = PayPalItemType.Shipping,
                    Name = T("Plugins.Payments.PayPalStandard.ShippingFee").Text,
                    Quantity = 1,
                    Amount = order.OrderShippingExclTax
                };
                lst.Add(item);

                cartTotal += order.OrderShippingExclTax;
            }

            // payment fee
            if (order.PaymentMethodAdditionalFeeExclTax > decimal.Zero)
            {
                var item = new PayPalLineItem()
                {
                    Type = PayPalItemType.PaymentFee,
                    Name = T("Plugins.Payments.PayPalStandard.PaymentMethodFee").Text,
                    Quantity = 1,
                    Amount = order.PaymentMethodAdditionalFeeExclTax
                };
                lst.Add(item);

                cartTotal += order.PaymentMethodAdditionalFeeExclTax;
            }

            // tax
            if (order.OrderTax > decimal.Zero)
            {
                var item = new PayPalLineItem()
                {
                    Type = PayPalItemType.Tax,
                    Name = T("Plugins.Payments.PayPalStandard.SalesTax").Text,
                    Quantity = 1,
                    Amount = order.OrderTax
                };
                lst.Add(item);

                cartTotal += order.OrderTax;
            }

            return lst;
        }
Ejemplo n.º 12
0
        public ActionResult RePostPayment(int orderId)
        {
            var order = _orderService.GetOrderById(orderId);
            if (order == null || order.Deleted || _workContext.CurrentCustomer.Id != order.CustomerId)
                return new HttpUnauthorizedResult();

            if (!_paymentService.CanRePostProcessPayment(order))
                return RedirectToRoute("OrderDetails", new { orderId = orderId });

            var postProcessPaymentRequest = new PostProcessPaymentRequest()
            {
                Order = order
            };
            _paymentService.PostProcessPayment(postProcessPaymentRequest);

            if (_webHelper.IsRequestBeingRedirected || _webHelper.IsPostBeingDone)
            {
                //redirection or POST has been done in PostProcessPayment
                return Content("Redirected");
            }
            else
            {
                //if no redirection has been done (to a third-party payment page)
                //theoretically it's not possible
                return RedirectToRoute("OrderDetails", new { orderId = orderId });
            }
        }
Ejemplo n.º 13
0
        public ActionResult RePostPayment(int id)
        {
            var order = _orderService.GetOrderById(id);

            if (IsNonExistentOrder(order))
                return HttpNotFound();

            if (IsUnauthorizedOrder(order))
                return new HttpUnauthorizedResult();

            if (_paymentService.CanRePostProcessPayment(order))
            {
                var postProcessPaymentRequest = new PostProcessPaymentRequest
                {
                    Order = order,
                    IsRePostProcessPayment = true
                };

                _paymentService.PostProcessPayment(postProcessPaymentRequest);

                if (postProcessPaymentRequest.RedirectUrl.HasValue())
                {
                    return Redirect(postProcessPaymentRequest.RedirectUrl);
                }
            }
            return RedirectToAction("Details", "Order", new { id = order.Id });
        }
        /// <summary>
        /// Post process payment (e.g. used by payment gateways to redirect to a third-party URL).
        /// Called after an order has been placed or when customer re-post the payment.
        /// </summary>
        /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
        public virtual void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
        {
            if (postProcessPaymentRequest.Order.PaymentMethodSystemName.HasValue())
            {
                var paymentMethod = LoadPaymentMethodBySystemName(postProcessPaymentRequest.Order.PaymentMethodSystemName);
                if (paymentMethod == null)
                    throw new SmartException(T("Payment.CouldNotLoadMethod"));

                paymentMethod.Value.PostProcessPayment(postProcessPaymentRequest);
            }
        }
Ejemplo n.º 15
0
 /// <summary>
 /// Post process payment (used by payment gateways that require redirecting to a third-party URL)
 /// </summary>
 /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
 public virtual void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
 {
     // NoImpl
 }
Ejemplo n.º 16
0
        public void PostProcessPayment(PostProcessPaymentRequest request)
        {
            // early polling... note we do not have the amazon billing address yet
            //try
            //{
            //	int orderId = request.Order.Id;
            //	var settings = _services.Settings.LoadSetting<AmazonPaySettings>(request.Order.StoreId);

            //	if (orderId != 0 && settings.StatusFetching == AmazonPayStatusFetchingType.Polling)
            //	{
            //		AsyncRunner.Run((container, obj) =>
            //		{
            //			var amazonService = container.Resolve<IAmazonPayService>();
            //			amazonService.EarlyPolling(orderId, obj as AmazonPaySettings);
            //		},
            //		settings, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
            //	}
            //}
            //catch (OffAmazonPaymentsServiceException exc)
            //{
            //	LogAmazonError(exc);
            //}
            //catch (Exception exc)
            //{
            //	LogError(exc);
            //}

            try
            {
                var state = _httpContext.GetAmazonPayState(_services.Localization);

                var orderAttribute = new AmazonPayOrderAttribute()
                {
                    OrderReferenceId = state.OrderReferenceId
                };

                SerializeOrderAttribute(orderAttribute, request.Order);
            }
            catch (Exception exc)
            {
                LogError(exc);
            }
        }
        public ActionResult ConfirmOrder(FormCollection form)
        {
            //validation
            var storeId = _storeContext.CurrentStore.Id;
            var customer = _workContext.CurrentCustomer;
            var cart = customer.GetCartItems(ShoppingCartType.ShoppingCart, storeId);

            if (cart.Count == 0)
                return RedirectToRoute("ShoppingCart");

            if ((customer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed))
                return new HttpUnauthorizedResult();

            var model = new CheckoutConfirmModel();
            PlaceOrderResult placeOrderResult = null;
            PostProcessPaymentRequest postProcessPaymentRequest = null;

            try
            {
                var processPaymentRequest = _httpContext.Session["OrderPaymentInfo"] as ProcessPaymentRequest;
                if (processPaymentRequest == null)
                {
                    //Check whether payment workflow is required
                    if (IsPaymentWorkflowRequired(cart))
                        return RedirectToAction("PaymentMethod");

                    processPaymentRequest = new ProcessPaymentRequest();
                }

                //prevent 2 orders being placed within an X seconds time frame
                if (!IsMinimumOrderPlacementIntervalValid(customer))
                    throw new Exception(T("Checkout.MinOrderPlacementInterval"));

                //place order
                processPaymentRequest.StoreId = storeId;
                processPaymentRequest.CustomerId = customer.Id;
                processPaymentRequest.PaymentMethodSystemName = customer.GetAttribute<string>(SystemCustomerAttributeNames.SelectedPaymentMethod, _genericAttributeService, storeId);

                var placeOrderExtraData = new Dictionary<string, string>();
                placeOrderExtraData["CustomerComment"] = form["customercommenthidden"];
                placeOrderExtraData["SubscribeToNewsLetter"] = form["SubscribeToNewsLetterHidden"];
                placeOrderExtraData["AcceptThirdPartyEmailHandOver"] = form["AcceptThirdPartyEmailHandOverHidden"];

                placeOrderResult = _orderProcessingService.PlaceOrder(processPaymentRequest, placeOrderExtraData);

                if (!placeOrderResult.Success)
                {
                    model.Warnings.AddRange(placeOrderResult.Errors.Select(x => HtmlUtils.ConvertPlainTextToHtml(x)));
                }
            }
            catch (Exception exception)
            {
                Logger.Warning(exception.Message, exception);

                if (!model.Warnings.Any(x => x == exception.Message))
                {
                    model.Warnings.Add(exception.Message);
                }
            }

            if (placeOrderResult == null || !placeOrderResult.Success || model.Warnings.Any())
            {
                return View(model);
            }

            try
            {
                postProcessPaymentRequest = new PostProcessPaymentRequest
                {
                    Order = placeOrderResult.PlacedOrder
                };

                _paymentService.PostProcessPayment(postProcessPaymentRequest);
            }
            catch (Exception exception)
            {
                NotifyError(exception);
            }
            finally
            {
                _httpContext.Session["PaymentData"] = null;
                _httpContext.Session["OrderPaymentInfo"] = null;
                _httpContext.RemoveCheckoutState();
            }

            if (postProcessPaymentRequest != null && postProcessPaymentRequest.RedirectUrl.HasValue())
            {
                return Redirect(postProcessPaymentRequest.RedirectUrl);
            }

            return RedirectToAction("Completed");
        }
        public ActionResult OpcConfirmOrder()
        {
            try
            {
                //validation
				var cart = _workContext.CurrentCustomer.GetCartItems(ShoppingCartType.ShoppingCart, _storeContext.CurrentStore.Id);

				if (cart.Count == 0)
                    throw new Exception("Your cart is empty");

                if (!UseOnePageCheckout())
                    throw new Exception("One page checkout is disabled");

                if ((_workContext.CurrentCustomer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed))
                    throw new Exception("Anonymous checkout is not allowed");

                //prevent 2 orders being placed within an X seconds time frame
                if (!IsMinimumOrderPlacementIntervalValid(_workContext.CurrentCustomer))
                    throw new Exception(_localizationService.GetResource("Checkout.MinOrderPlacementInterval"));

                //place order
                var processPaymentRequest = _httpContext.Session["OrderPaymentInfo"] as ProcessPaymentRequest;
                if (processPaymentRequest == null)
                {
                    //Check whether payment workflow is required
                    if (IsPaymentWorkflowRequired(cart))
                    {
                        throw new Exception("Payment information is not entered");
                    }
                    else
                        processPaymentRequest = new ProcessPaymentRequest();
                }

				processPaymentRequest.StoreId = _storeContext.CurrentStore.Id;
                processPaymentRequest.CustomerId = _workContext.CurrentCustomer.Id;
				processPaymentRequest.PaymentMethodSystemName = _workContext.CurrentCustomer.GetAttribute<string>(
					 SystemCustomerAttributeNames.SelectedPaymentMethod,
					 _genericAttributeService, _storeContext.CurrentStore.Id);
                var placeOrderResult = _orderProcessingService.PlaceOrder(processPaymentRequest);
                if (placeOrderResult.Success)
                {
                    _httpContext.Session["OrderPaymentInfo"] = null;
                    var postProcessPaymentRequest = new PostProcessPaymentRequest()
                    {
                        Order = placeOrderResult.PlacedOrder
                    };


                    var paymentMethod = _paymentService.LoadPaymentMethodBySystemName(placeOrderResult.PlacedOrder.PaymentMethodSystemName);
                    if (paymentMethod != null)
                    {
                        if (paymentMethod.PaymentMethodType == PaymentMethodType.Redirection)
                        {
                            //Redirection will not work because it's AJAX request.
                            //That's why we don't process it here (we redirect a user to another page where he'll be redirected)

                            //redirect
                            return Json(new { redirect = string.Format("{0}checkout/OpcCompleteRedirectionPayment", _webHelper.GetStoreLocation()) });
                        }
                        else
                        {
                            _paymentService.PostProcessPayment(postProcessPaymentRequest);
                            //success
                            return Json(new { success = 1 });
                        }
                    }
                    else
                    {
                        //payment method could be null if order total is 0

                        //success
                        return Json(new { success = 1 });
                    }
                }
                else
                {
                    //error
                    var confirmOrderModel = new CheckoutConfirmModel();
                    foreach (var error in placeOrderResult.Errors)
                        confirmOrderModel.Warnings.Add(error); 
                    
                    return Json(new
                        {
                            update_section = new UpdateSectionJsonModel()
                            {
                                name = "confirm-order",
                                html = this.RenderPartialViewToString("OpcConfirmOrder", confirmOrderModel)
                            },
                            goto_section = "confirm_order"
                        });
                }
            }
            catch (Exception exc)
            {
				Logger.Warning(exc.Message, exc, _workContext.CurrentCustomer);
                return Json(new { error = 1, message = exc.Message });
            }
        }
        /// <summary>
        /// Post process payment (e.g. used by payment gateways to redirect to a third-party URL).
		/// Called after an order has been placed or when customer re-post the payment.
        /// </summary>
        /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
        public virtual void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
        {
            var paymentMethod = LoadPaymentMethodBySystemName(postProcessPaymentRequest.Order.PaymentMethodSystemName);
            if (paymentMethod == null)
                throw new SmartException("Payment method couldn't be loaded");
            paymentMethod.Value.PostProcessPayment(postProcessPaymentRequest);
        }
Ejemplo n.º 20
0
		public override void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
		{
			_apiService.PostProcessPayment(postProcessPaymentRequest);
		}