Exemplo n.º 1
0
        public ActionResult SubmitButton()
        {
            try
            {
                //user validation
                if ((Services.WorkContext.CurrentCustomer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed))
                {
                    return(RedirectToRoute("Login"));
                }

                var store    = Services.StoreContext.CurrentStore;
                var customer = Services.WorkContext.CurrentCustomer;
                var settings = Services.Settings.LoadSetting <PayPalExpressPaymentSettings>(store.Id);
                var cart     = Services.WorkContext.CurrentCustomer.GetCartItems(ShoppingCartType.ShoppingCart, store.Id);

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

                if (String.IsNullOrEmpty(settings.ApiAccountName))
                {
                    throw new ApplicationException("PayPal API Account Name is not set");
                }
                if (String.IsNullOrEmpty(settings.ApiAccountPassword))
                {
                    throw new ApplicationException("PayPal API Password is not set");
                }
                if (String.IsNullOrEmpty(settings.Signature))
                {
                    throw new ApplicationException("PayPal API Signature is not set");
                }

                var provider  = PaymentService.LoadPaymentMethodBySystemName(PayPalExpressProvider.SystemName, true);
                var processor = provider != null ? provider.Value as PayPalExpressProvider : null;
                if (processor == null)
                {
                    throw new SmartException(T("Plugins.CannotLoadModule", T("Plugins.FriendlyName.Payments.PayPalExpress")));
                }

                var processPaymentRequest = new PayPalProcessPaymentRequest();

                processPaymentRequest.StoreId = store.Id;

                //Get sub-total and discounts that apply to sub-total
                decimal  orderSubTotalDiscountAmountBase = decimal.Zero;
                Discount orderSubTotalAppliedDiscount    = null;
                decimal  subTotalWithoutDiscountBase     = decimal.Zero;
                decimal  subTotalWithDiscountBase        = decimal.Zero;

                _orderTotalCalculationService.GetShoppingCartSubTotal(cart,
                                                                      out orderSubTotalDiscountAmountBase, out orderSubTotalAppliedDiscount, out subTotalWithoutDiscountBase, out subTotalWithDiscountBase);

                //order total
                decimal resultTemp = decimal.Zero;
                resultTemp += subTotalWithDiscountBase;

                //Get discounts that apply to Total
                Discount appliedDiscount = null;
                var      discountAmount  = _orderTotalCalculationService.GetOrderTotalDiscount(customer, resultTemp, out appliedDiscount);

                //if the current total is less than the discount amount, we only make the discount equal to the current total
                if (resultTemp < discountAmount)
                {
                    discountAmount = resultTemp;
                }

                //reduce subtotal
                resultTemp -= discountAmount;

                if (resultTemp < decimal.Zero)
                {
                    resultTemp = decimal.Zero;
                }

                decimal tempDiscount = discountAmount + orderSubTotalDiscountAmountBase;

                resultTemp = _currencyService.ConvertFromPrimaryStoreCurrency(resultTemp, Services.WorkContext.WorkingCurrency);
                if (tempDiscount > decimal.Zero)
                {
                    tempDiscount = _currencyService.ConvertFromPrimaryStoreCurrency(tempDiscount, Services.WorkContext.WorkingCurrency);
                }

                processPaymentRequest.PaymentMethodSystemName = PayPalExpressProvider.SystemName;
                processPaymentRequest.OrderTotal         = resultTemp;
                processPaymentRequest.Discount           = tempDiscount;
                processPaymentRequest.IsRecurringPayment = false;

                //var selectedPaymentMethodSystemName = _workContext.CurrentCustomer.GetAttribute<string>(SystemCustomerAttributeNames.SelectedPaymentMethod, _storeContext.CurrentStore.Id);

                processPaymentRequest.CustomerId = Services.WorkContext.CurrentCustomer.Id;
                this.Session["OrderPaymentInfo"] = processPaymentRequest;

                var resp = processor.SetExpressCheckout(processPaymentRequest, cart);

                if (resp.Ack == AckCodeType.Success)
                {
                    // Note: If Token is null and an empty page with "No token passed" is displyed, then this is caused by a broken
                    // Web References/PayPalSvc/Reference.cs file. To fix it, check git history of the file and revert changes.
                    processPaymentRequest.PaypalToken         = resp.Token;
                    processPaymentRequest.OrderGuid           = new Guid();
                    processPaymentRequest.IsShippingMethodSet = ControllerContext.RouteData.IsRouteEqual("ShoppingCart", "Cart");
                    this.Session["OrderPaymentInfo"]          = processPaymentRequest;

                    _genericAttributeService.SaveAttribute <string>(customer, SystemCustomerAttributeNames.SelectedPaymentMethod, PayPalExpressProvider.SystemName, store.Id);

                    var result = new RedirectResult(String.Format(settings.GetPayPalUrl() + "?cmd=_express-checkout&useraction=commit&token={0}", resp.Token));

                    return(result);
                }
                else
                {
                    var error = new StringBuilder("We apologize, but an error has occured.<br />");
                    foreach (var errormsg in resp.Errors)
                    {
                        error.AppendLine(String.Format("{0} | {1} | {2}", errormsg.ErrorCode, errormsg.ShortMessage, errormsg.LongMessage));
                    }

                    Logger.Error(new Exception(error.ToString()), resp.Errors[0].ShortMessage);

                    NotifyError(error.ToString(), false);

                    return(RedirectToAction("Cart", "ShoppingCart", new { area = "" }));
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex);

                NotifyError(ex.Message, false);

                return(RedirectToAction("Cart", "ShoppingCart", new { area = "" }));
            }
        }
Exemplo n.º 2
0
        public ActionResult SubmitButton()
        {
            try
            {
                //user validation
                if ((_services.WorkContext.CurrentCustomer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed))
                {
                    return(RedirectToRoute("Login"));
                }

                var settings = _services.Settings.LoadSetting <PayPalExpressPaymentSettings>(_services.StoreContext.CurrentStore.Id);
                var cart     = _services.WorkContext.CurrentCustomer.GetCartItems(ShoppingCartType.ShoppingCart, _services.StoreContext.CurrentStore.Id);

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

                var currency = _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId).CurrencyCode;

                if (String.IsNullOrEmpty(settings.ApiAccountName))
                {
                    throw new ApplicationException("PayPal API Account Name is not set");
                }
                if (String.IsNullOrEmpty(settings.ApiAccountPassword))
                {
                    throw new ApplicationException("PayPal API Password is not set");
                }
                if (String.IsNullOrEmpty(settings.Signature))
                {
                    throw new ApplicationException("PayPal API Signature is not set");
                }

                var provider  = _paymentService.LoadPaymentMethodBySystemName("Payments.PayPalExpress", true);
                var processor = provider != null ? provider.Value as PayPalExpress : null;
                if (processor == null)
                {
                    throw new SmartException("PayPal Express Checkout module cannot be loaded");
                }

                var processPaymentRequest = new PayPalProcessPaymentRequest();

                processPaymentRequest.StoreId = _services.StoreContext.CurrentStore.Id;

                //Get sub-total and discounts that apply to sub-total
                decimal  orderSubTotalDiscountAmountBase = decimal.Zero;
                Discount orderSubTotalAppliedDiscount    = null;
                decimal  subTotalWithoutDiscountBase     = decimal.Zero;
                decimal  subTotalWithDiscountBase        = decimal.Zero;
                _orderTotalCalculationService.GetShoppingCartSubTotal(cart,
                                                                      out orderSubTotalDiscountAmountBase, out orderSubTotalAppliedDiscount,
                                                                      out subTotalWithoutDiscountBase, out subTotalWithDiscountBase);

                //order total
                decimal resultTemp = decimal.Zero;
                resultTemp += subTotalWithDiscountBase;

                // get customer
                int customerId = Convert.ToInt32(_services.WorkContext.CurrentCustomer.Id.ToString());
                var customer   = _customerService.GetCustomerById(customerId);

                //Get discounts that apply to Total
                Discount appliedDiscount = null;
                var      discountAmount  = _orderTotalCalculationService.GetOrderTotalDiscount(customer, resultTemp, out appliedDiscount);

                //if the current total is less than the discount amount, we only make the discount equal to the current total
                if (resultTemp < discountAmount)
                {
                    discountAmount = resultTemp;
                }

                //reduce subtotal
                resultTemp -= discountAmount;

                if (resultTemp < decimal.Zero)
                {
                    resultTemp = decimal.Zero;
                }

                decimal tempDiscount = discountAmount + orderSubTotalDiscountAmountBase;

                resultTemp = _currencyService.ConvertFromPrimaryStoreCurrency(resultTemp, _services.WorkContext.WorkingCurrency);
                if (tempDiscount > decimal.Zero)
                {
                    tempDiscount = _currencyService.ConvertFromPrimaryStoreCurrency(tempDiscount, _services.WorkContext.WorkingCurrency);
                }

                processPaymentRequest.PaymentMethodSystemName = "Payments.PayPalExpress";
                processPaymentRequest.OrderTotal         = resultTemp;
                processPaymentRequest.Discount           = tempDiscount;
                processPaymentRequest.IsRecurringPayment = false;

                //var selectedPaymentMethodSystemName = _workContext.CurrentCustomer.GetAttribute<string>(SystemCustomerAttributeNames.SelectedPaymentMethod, _storeContext.CurrentStore.Id);

                processPaymentRequest.CustomerId = _services.WorkContext.CurrentCustomer.Id;
                this.Session["OrderPaymentInfo"] = processPaymentRequest;

                var resp = processor.SetExpressCheckout(processPaymentRequest, cart);

                if (resp.Ack == AckCodeType.Success)
                {
                    processPaymentRequest.PaypalToken         = resp.Token;
                    processPaymentRequest.OrderGuid           = new Guid();
                    processPaymentRequest.IsShippingMethodSet = PayPalHelper.CurrentPageIsBasket(this.RouteData);
                    this.Session["OrderPaymentInfo"]          = processPaymentRequest;

                    _genericAttributeService.SaveAttribute <string>(customer, SystemCustomerAttributeNames.SelectedPaymentMethod, "Payments.PayPalExpress",
                                                                    _services.StoreContext.CurrentStore.Id);

                    var result = new RedirectResult(String.Format(
                                                        PayPalHelper.GetPaypalUrl(settings) +
                                                        "?cmd=_express-checkout&useraction=commit&token={0}", resp.Token));

                    return(result);
                }
                else
                {
                    var error = new StringBuilder("We apologize, but an error has occured.<br />");
                    foreach (var errormsg in resp.Errors)
                    {
                        error.AppendLine(String.Format("{0} | {1} | {2}", errormsg.ErrorCode, errormsg.ShortMessage, errormsg.LongMessage));
                    }

                    _logger.InsertLog(LogLevel.Error, resp.Errors[0].ShortMessage, resp.Errors[0].LongMessage, _services.WorkContext.CurrentCustomer);

                    NotifyError(error.ToString(), false);

                    return(RedirectToAction("Cart", "ShoppingCart", new { area = "" }));
                }
            }
            catch (Exception ex)
            {
                _logger.InsertLog(LogLevel.Error, ex.Message, ex.StackTrace, _services.WorkContext.CurrentCustomer);

                NotifyError(ex.Message, false);

                return(RedirectToAction("Cart", "ShoppingCart", new { area = "" }));
            }
        }