Exemple #1
0
        /// <summary>
        /// Add order items to the request query parameters
        /// </summary>
        /// <param name="parameters">Query parameters</param>
        /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
        private void AddItemsParameters(IDictionary <string, string> parameters, PostProcessPaymentRequest postProcessPaymentRequest)
        {
            //upload order items
            parameters.Add("cmd", "_cart");
            parameters.Add("upload", "1");

            var cartTotal        = decimal.Zero;
            var roundedCartTotal = decimal.Zero;
            var itemCount        = 1;

            //add shopping cart items
            foreach (var item in _orderService.GetOrderItems(postProcessPaymentRequest.Order.Id))
            {
                var roundedItemPrice = Math.Round(item.UnitPriceExclTax, 2);

                var product = _productService.GetProductById(item.ProductId);

                //add query parameters
                parameters.Add($"item_name_{itemCount}", product.Name);
                parameters.Add($"amount_{itemCount}", roundedItemPrice.ToString("0.00", CultureInfo.InvariantCulture));
                parameters.Add($"quantity_{itemCount}", item.Quantity.ToString());

                cartTotal        += item.PriceExclTax;
                roundedCartTotal += roundedItemPrice * item.Quantity;
                itemCount++;
            }

            //add checkout attributes as order items
            var checkoutAttributeValues = _checkoutAttributeParser.ParseCheckoutAttributeValues(postProcessPaymentRequest.Order.CheckoutAttributesXml);
            var customer = _customerService.GetCustomerById(postProcessPaymentRequest.Order.CustomerId);

            foreach (var(attribute, values) in checkoutAttributeValues)
            {
                foreach (var attributeValue in values)
                {
                    var attributePrice        = _taxService.GetCheckoutAttributePrice(attribute, attributeValue, false, customer);
                    var roundedAttributePrice = Math.Round(attributePrice, 2);

                    //add query parameters
                    if (attribute == null)
                    {
                        continue;
                    }

                    parameters.Add($"item_name_{itemCount}", attribute.Name);
                    parameters.Add($"amount_{itemCount}", roundedAttributePrice.ToString("0.00", CultureInfo.InvariantCulture));
                    parameters.Add($"quantity_{itemCount}", "1");

                    cartTotal        += attributePrice;
                    roundedCartTotal += roundedAttributePrice;
                    itemCount++;
                }
            }

            //add shipping fee as a separate order item, if it has price
            var roundedShippingPrice = Math.Round(postProcessPaymentRequest.Order.OrderShippingExclTax, 2);

            if (roundedShippingPrice > decimal.Zero)
            {
                parameters.Add($"item_name_{itemCount}", "Shipping fee");
                parameters.Add($"amount_{itemCount}", roundedShippingPrice.ToString("0.00", CultureInfo.InvariantCulture));
                parameters.Add($"quantity_{itemCount}", "1");

                cartTotal        += postProcessPaymentRequest.Order.OrderShippingExclTax;
                roundedCartTotal += roundedShippingPrice;
                itemCount++;
            }

            //add payment method additional fee as a separate order item, if it has price
            var roundedPaymentMethodPrice = Math.Round(postProcessPaymentRequest.Order.PaymentMethodAdditionalFeeExclTax, 2);

            if (roundedPaymentMethodPrice > decimal.Zero)
            {
                parameters.Add($"item_name_{itemCount}", "Payment method fee");
                parameters.Add($"amount_{itemCount}", roundedPaymentMethodPrice.ToString("0.00", CultureInfo.InvariantCulture));
                parameters.Add($"quantity_{itemCount}", "1");

                cartTotal        += postProcessPaymentRequest.Order.PaymentMethodAdditionalFeeExclTax;
                roundedCartTotal += roundedPaymentMethodPrice;
                itemCount++;
            }

            //add tax as a separate order item, if it has positive amount
            var roundedTaxAmount = Math.Round(postProcessPaymentRequest.Order.OrderTax, 2);

            if (roundedTaxAmount > decimal.Zero)
            {
                parameters.Add($"item_name_{itemCount}", "Tax amount");
                parameters.Add($"amount_{itemCount}", roundedTaxAmount.ToString("0.00", CultureInfo.InvariantCulture));
                parameters.Add($"quantity_{itemCount}", "1");

                cartTotal        += postProcessPaymentRequest.Order.OrderTax;
                roundedCartTotal += roundedTaxAmount;
            }

            if (cartTotal > postProcessPaymentRequest.Order.OrderTotal)
            {
                //get the difference between what the order total is and what it should be and use that as the "discount"
                var discountTotal = Math.Round(cartTotal - postProcessPaymentRequest.Order.OrderTotal, 2);
                roundedCartTotal -= discountTotal;

                //gift card or rewarded point amount applied to cart in nopCommerce - shows in PayPal as "discount"
                parameters.Add("discount_amount_cart", discountTotal.ToString("0.00", CultureInfo.InvariantCulture));
            }

            //save order total that actually sent to PayPal (used for PDT order total validation)
            _genericAttributeService.SaveAttribute(postProcessPaymentRequest.Order, PayPalHelper.OrderTotalSentToPayPal, roundedCartTotal);
        }
Exemple #2
0
        public ActionResult SubmitButton()
        {
            try
            {
                //user validation
                if ((_workContext.CurrentCustomer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed))
                {
                    return(RedirectToRoute("Login"));
                }

                //var cart = _workContext.CurrentCustomer.ShoppingCartItems.Where(sci => sci.ShoppingCartType == ShoppingCartType.ShoppingCart).ToList();
                var cart = _workContext.CurrentCustomer.GetCartItems(ShoppingCartType.ShoppingCart, _storeContext.CurrentStore.Id);

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

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

                if (String.IsNullOrEmpty(_payPalExpressPaymentSettings.ApiAccountName))
                {
                    throw new ApplicationException("PayPal API Account Name is not set");
                }
                if (String.IsNullOrEmpty(_payPalExpressPaymentSettings.ApiAccountPassword))
                {
                    throw new ApplicationException("PayPal API Password is not set");
                }
                if (String.IsNullOrEmpty(_payPalExpressPaymentSettings.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();

                //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(_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, _workContext.WorkingCurrency);
                if (tempDiscount > decimal.Zero)
                {
                    tempDiscount = _currencyService.ConvertFromPrimaryStoreCurrency(tempDiscount, _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 = _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", _storeContext.CurrentStore.Id);

                    var result = new RedirectResult(String.Format(
                                                        PayPalHelper.GetPaypalUrl(_payPalExpressPaymentSettings) +
                                                        "?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));
                    }
                    //TODO: log error
                    return(RedirectToRoute("HomePage"));
                }
            }
            catch
            {
                //TODO: log exception
                return(RedirectToRoute("HomePage"));
            }
        }
Exemple #3
0
        public ProcessPaymentRequest SetCheckoutDetails(ProcessPaymentRequest processPaymentRequest, GetExpressCheckoutDetailsResponseDetailsType checkoutDetails)
        {
            int customerId = Convert.ToInt32(CommonServices.WorkContext.CurrentCustomer.Id.ToString());
            var customer   = _customerService.GetCustomerById(customerId);
            var settings   = CommonServices.Settings.LoadSetting <PayPalExpressPaymentSettings>(CommonServices.StoreContext.CurrentStore.Id);

            CommonServices.WorkContext.CurrentCustomer = customer;

            //var cart = customer.ShoppingCartItems.Where(sci => sci.ShoppingCartType == ShoppingCartType.ShoppingCart).ToList();
            var cart = CommonServices.WorkContext.CurrentCustomer.GetCartItems(ShoppingCartType.ShoppingCart, CommonServices.StoreContext.CurrentStore.Id);

            // get/update billing address
            string billingFirstName       = checkoutDetails.PayerInfo.PayerName.FirstName;
            string billingLastName        = checkoutDetails.PayerInfo.PayerName.LastName;
            string billingEmail           = checkoutDetails.PayerInfo.Payer;
            string billingAddress1        = checkoutDetails.PayerInfo.Address.Street1;
            string billingAddress2        = checkoutDetails.PayerInfo.Address.Street2;
            string billingPhoneNumber     = checkoutDetails.PayerInfo.ContactPhone;
            string billingCity            = checkoutDetails.PayerInfo.Address.CityName;
            int?   billingStateProvinceId = null;
            var    billingStateProvince   = _stateProvinceService.GetStateProvinceByAbbreviation(checkoutDetails.PayerInfo.Address.StateOrProvince);

            if (billingStateProvince != null)
            {
                billingStateProvinceId = billingStateProvince.Id;
            }
            string billingZipPostalCode = checkoutDetails.PayerInfo.Address.PostalCode;
            int?   billingCountryId     = null;
            var    billingCountry       = _countryService.GetCountryByTwoLetterIsoCode(checkoutDetails.PayerInfo.Address.Country.ToString());

            if (billingCountry != null)
            {
                billingCountryId = billingCountry.Id;
            }

            var billingAddress = customer.Addresses.ToList().FindAddress(
                billingFirstName, billingLastName, billingPhoneNumber,
                billingEmail, string.Empty, string.Empty, billingAddress1, billingAddress2, billingCity,
                billingStateProvinceId, billingZipPostalCode, billingCountryId);

            if (billingAddress == null)
            {
                billingAddress = new Core.Domain.Common.Address()
                {
                    FirstName       = billingFirstName,
                    LastName        = billingLastName,
                    PhoneNumber     = billingPhoneNumber,
                    Email           = billingEmail,
                    FaxNumber       = string.Empty,
                    Company         = string.Empty,
                    Address1        = billingAddress1,
                    Address2        = billingAddress2,
                    City            = billingCity,
                    StateProvinceId = billingStateProvinceId,
                    ZipPostalCode   = billingZipPostalCode,
                    CountryId       = billingCountryId,
                    CreatedOnUtc    = DateTime.UtcNow,
                };
                customer.Addresses.Add(billingAddress);
            }

            //set default billing address
            customer.BillingAddress = billingAddress;
            _customerService.UpdateCustomer(customer);

            var genericAttributeService = EngineContext.Current.Resolve <IGenericAttributeService>();

            genericAttributeService.SaveAttribute <ShippingOption>(customer, SystemCustomerAttributeNames.SelectedShippingOption, null);

            bool shoppingCartRequiresShipping = cart.RequiresShipping();

            if (shoppingCartRequiresShipping)
            {
                var      paymentDetails    = checkoutDetails.PaymentDetails.FirstOrDefault();
                string[] shippingFullname  = paymentDetails.ShipToAddress.Name.Trim().Split(new char[] { ' ' }, 2, StringSplitOptions.RemoveEmptyEntries);
                string   shippingFirstName = shippingFullname[0];
                string   shippingLastName  = string.Empty;
                if (shippingFullname.Length > 1)
                {
                    shippingLastName = shippingFullname[1];
                }
                string shippingEmail           = checkoutDetails.PayerInfo.Payer;
                string shippingAddress1        = paymentDetails.ShipToAddress.Street1;
                string shippingAddress2        = paymentDetails.ShipToAddress.Street2;
                string shippingPhoneNumber     = paymentDetails.ShipToAddress.Phone;
                string shippingCity            = paymentDetails.ShipToAddress.CityName;
                int?   shippingStateProvinceId = null;
                var    shippingStateProvince   = _stateProvinceService.GetStateProvinceByAbbreviation(paymentDetails.ShipToAddress.StateOrProvince);
                if (shippingStateProvince != null)
                {
                    shippingStateProvinceId = shippingStateProvince.Id;
                }
                int?   shippingCountryId     = null;
                string shippingZipPostalCode = paymentDetails.ShipToAddress.PostalCode;
                var    shippingCountry       = _countryService.GetCountryByTwoLetterIsoCode(paymentDetails.ShipToAddress.Country.ToString());
                if (shippingCountry != null)
                {
                    shippingCountryId = shippingCountry.Id;
                }

                var shippingAddress = customer.Addresses.ToList().FindAddress(
                    shippingFirstName, shippingLastName, shippingPhoneNumber,
                    shippingEmail, string.Empty, string.Empty,
                    shippingAddress1, shippingAddress2, shippingCity,
                    shippingStateProvinceId, shippingZipPostalCode, shippingCountryId);

                if (shippingAddress == null)
                {
                    shippingAddress = new Core.Domain.Common.Address()
                    {
                        FirstName       = shippingFirstName,
                        LastName        = shippingLastName,
                        PhoneNumber     = shippingPhoneNumber,
                        Email           = shippingEmail,
                        FaxNumber       = string.Empty,
                        Company         = string.Empty,
                        Address1        = shippingAddress1,
                        Address2        = shippingAddress2,
                        City            = shippingCity,
                        StateProvinceId = shippingStateProvinceId,
                        ZipPostalCode   = shippingZipPostalCode,
                        CountryId       = shippingCountryId,
                        CreatedOnUtc    = DateTime.UtcNow,
                    };
                    customer.Addresses.Add(shippingAddress);
                }

                customer.ShippingAddress = shippingAddress;
                _customerService.UpdateCustomer(customer);
            }

            bool isShippingSet = false;
            GetShippingOptionResponse getShippingOptionResponse = _shippingService.GetShippingOptions(cart, customer.ShippingAddress);

            if (checkoutDetails.UserSelectedOptions != null)
            {
                if (getShippingOptionResponse.Success && getShippingOptionResponse.ShippingOptions.Count > 0)
                {
                    foreach (var shippingOption in getShippingOptionResponse.ShippingOptions)
                    {
                        if (checkoutDetails.UserSelectedOptions.ShippingOptionName.Contains(shippingOption.Name) &&
                            checkoutDetails.UserSelectedOptions.ShippingOptionName.Contains(shippingOption.Description))
                        {
                            _genericAttributeService.SaveAttribute(CommonServices.WorkContext.CurrentCustomer, SystemCustomerAttributeNames.SelectedShippingOption, shippingOption);
                            isShippingSet = true;
                            break;
                        }
                    }
                }

                if (!isShippingSet)
                {
                    var shippingOption = new ShippingOption();
                    shippingOption.Name = checkoutDetails.UserSelectedOptions.ShippingOptionName;
                    decimal shippingPrice = settings.DefaultShippingPrice;
                    decimal.TryParse(checkoutDetails.UserSelectedOptions.ShippingOptionAmount.Value, out shippingPrice);
                    shippingOption.Rate = shippingPrice;
                    _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.SelectedShippingOption, shippingOption);
                }
            }

            processPaymentRequest.PaypalPayerId = checkoutDetails.PayerInfo.PayerID;


            return(processPaymentRequest);
        }
        /// <summary>
        /// Create request parameters to charge transaction
        /// </summary>
        /// <param name="paymentRequest">Payment request parameters</param>
        /// <param name="isRecurringPayment">Whether it is a recurring payment</param>
        /// <returns>Charge request parameters</returns>
        private ExtendedChargeRequest CreateChargeRequest(ProcessPaymentRequest paymentRequest, bool isRecurringPayment)
        {
            //get customer
            var customer = _customerService.GetCustomerById(paymentRequest.CustomerId);

            if (customer == null)
            {
                throw new NopException("Customer cannot be loaded");
            }

            //get the primary store currency
            var currency = _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId);

            if (currency == null)
            {
                throw new NopException("Primary store currency cannot be loaded");
            }

            //whether the currency is supported by the Square
            if (!Enum.TryParse(currency.CurrencyCode, out SquareModel.Money.CurrencyEnum moneyCurrency))
            {
                throw new NopException($"The {currency.CurrencyCode} currency is not supported by the Square");
            }

            //check customer's billing address, shipping address and email,
            Func <Address, SquareModel.Address> createAddress = (address) => address == null ? null : new SquareModel.Address
                                                                (
                AddressLine1: address.Address1,
                AddressLine2: address.Address2,
                AdministrativeDistrictLevel1: address.StateProvince?.Abbreviation,
                AdministrativeDistrictLevel2: address.County,
                Country: Enum.TryParse(address.Country?.TwoLetterIsoCode, out SquareModel.Address.CountryEnum countryCode)
                    ? (SquareModel.Address.CountryEnum?)countryCode: null,
                FirstName: address.FirstName,
                LastName: address.LastName,
                Locality: address.City,
                PostalCode: address.ZipPostalCode
                                                                );
            var billingAddress  = createAddress(customer.BillingAddress);
            var shippingAddress = billingAddress == null?createAddress(customer.ShippingAddress) : null;

            var email = customer.BillingAddress != null ? customer.BillingAddress.Email : customer.ShippingAddress?.Email;

            //the transaction is ineligible for chargeback protection if they are not provided
            if ((billingAddress == null && shippingAddress == null) || string.IsNullOrEmpty(email))
            {
                _logger.Warning("Square payment warning: Address or email is not provided, so the transaction is ineligible for chargeback protection", customer: customer);
            }

            //the amount of money, in the smallest denomination of the currency indicated by currency. For example, when currency is USD, amount is in cents;
            //most currencies consist of 100 units of smaller denomination, so we multiply the total by 100
            var orderTotal  = (int)(paymentRequest.OrderTotal * 100);
            var amountMoney = new SquareModel.Money(Amount: orderTotal, Currency: moneyCurrency);

            //create common charge request parameters
            var chargeRequest = new ExtendedChargeRequest
                                (
                amountMoney: amountMoney,
                billingAddress: billingAddress,
                buyerEmailAddress: email,
                delayCapture: _squarePaymentSettings.TransactionMode == TransactionMode.Authorize,
                idempotencyKey: Guid.NewGuid().ToString(),
                integrationId: !string.IsNullOrEmpty(SquarePaymentDefaults.IntegrationId) ? SquarePaymentDefaults.IntegrationId : null,
                note: string.Format(SquarePaymentDefaults.PaymentNote, paymentRequest.OrderGuid),
                referenceId: paymentRequest.OrderGuid.ToString(),
                shippingAddress: shippingAddress
                                );

            //try to get previously stored card details
            var storedCardKey = _localizationService.GetResource("Plugins.Payments.Square.Fields.StoredCard.Key");

            if (paymentRequest.CustomValues.TryGetValue(storedCardKey, out var storedCardId) && !storedCardId.ToString().Equals(Guid.Empty.ToString()))
            {
                //check whether customer exists
                var customerId     = _genericAttributeService.GetAttribute <string>(customer, SquarePaymentDefaults.CustomerIdAttribute);
                var squareCustomer = _squarePaymentManager.GetCustomer(customerId);
                if (squareCustomer == null)
                {
                    throw new NopException("Failed to retrieve customer");
                }

                //set 'card on file' to charge
                chargeRequest.CustomerId     = squareCustomer.Id;
                chargeRequest.CustomerCardId = storedCardId.ToString();
                return(chargeRequest);
            }

            //or try to get the card nonce
            var cardNonceKey = _localizationService.GetResource("Plugins.Payments.Square.Fields.CardNonce.Key");

            if (!paymentRequest.CustomValues.TryGetValue(cardNonceKey, out var cardNonce) || string.IsNullOrEmpty(cardNonce?.ToString()))
            {
                throw new NopException("Failed to get the card nonce");
            }

            //remove the card nonce from payment custom values, since it is no longer needed
            paymentRequest.CustomValues.Remove(cardNonceKey);

            //whether to save card details for the future purchasing
            var saveCardKey = _localizationService.GetResource("Plugins.Payments.Square.Fields.SaveCard.Key");

            if (paymentRequest.CustomValues.TryGetValue(saveCardKey, out var saveCardValue) && saveCardValue is bool saveCard && saveCard && !customer.IsGuest())
            {
                //remove the value from payment custom values, since it is no longer needed
                paymentRequest.CustomValues.Remove(saveCardKey);

                try
                {
                    //check whether customer exists
                    var customerId     = _genericAttributeService.GetAttribute <string>(customer, SquarePaymentDefaults.CustomerIdAttribute);
                    var squareCustomer = _squarePaymentManager.GetCustomer(customerId);

                    if (squareCustomer == null)
                    {
                        //try to create the new one, if not exists
                        var customerRequest = new SquareModel.CreateCustomerRequest
                                              (
                            EmailAddress: customer.Email,
                            Nickname: customer.Username,
                            GivenName: _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.FirstNameAttribute),
                            FamilyName: _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.LastNameAttribute),
                            PhoneNumber: _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.PhoneAttribute),
                            CompanyName: _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.CompanyAttribute),
                            ReferenceId: customer.CustomerGuid.ToString()
                                              );
                        squareCustomer = _squarePaymentManager.CreateCustomer(customerRequest);
                        if (squareCustomer == null)
                        {
                            throw new NopException("Failed to create customer. Error details in the log");
                        }

                        //save customer identifier as generic attribute
                        _genericAttributeService.SaveAttribute(customer, SquarePaymentDefaults.CustomerIdAttribute, squareCustomer.Id);
                    }

                    //create request parameters to create the new card
                    var cardRequest = new SquareModel.CreateCustomerCardRequest
                                      (
                        BillingAddress: chargeRequest.BillingAddress ?? chargeRequest.ShippingAddress,
                        CardNonce: cardNonce.ToString()
                                      );

                    //set postal code
                    var postalCodeKey = _localizationService.GetResource("Plugins.Payments.Square.Fields.PostalCode.Key");
                    if (paymentRequest.CustomValues.TryGetValue(postalCodeKey, out var postalCode) && !string.IsNullOrEmpty(postalCode.ToString()))
                    {
                        //remove the value from payment custom values, since it is no longer needed
                        paymentRequest.CustomValues.Remove(postalCodeKey);

                        cardRequest.BillingAddress            = cardRequest.BillingAddress ?? new SquareModel.Address();
                        cardRequest.BillingAddress.PostalCode = postalCode.ToString();
                    }

                    //try to create card
                    var card = _squarePaymentManager.CreateCustomerCard(squareCustomer.Id, cardRequest);
                    if (card == null)
                    {
                        throw new NopException("Failed to create card. Error details in the log");
                    }

                    //save card identifier to payment custom values for further purchasing
                    if (isRecurringPayment)
                    {
                        paymentRequest.CustomValues.Add(storedCardKey, card.Id);
                    }

                    //set 'card on file' to charge
                    chargeRequest.CustomerId     = squareCustomer.Id;
                    chargeRequest.CustomerCardId = card.Id;
                    return(chargeRequest);
                }
                catch (Exception exception)
                {
                    _logger.Warning(exception.Message, exception, customer);
                    if (isRecurringPayment)
                    {
                        throw new NopException("For recurring payments you need to save the card details");
                    }
                }
            }
        private string GetEcommerceScript(Order order)
        {
            var analyticsTrackingScript = _googleAnalyticsSettings.TrackingScript + "\n";

            analyticsTrackingScript = analyticsTrackingScript.Replace("{GOOGLEID}", _googleAnalyticsSettings.GoogleId);
            //remove {ECOMMERCE} (used in previous versions of the plugin)
            analyticsTrackingScript = analyticsTrackingScript.Replace("{ECOMMERCE}", "");
            //remove {CustomerID} (used in previous versions of the plugin)
            analyticsTrackingScript = analyticsTrackingScript.Replace("{CustomerID}", "");

            //whether to include customer identifier
            var customerIdCode = string.Empty;

            if (_googleAnalyticsSettings.IncludeCustomerId && !_workContext.CurrentCustomer.IsGuest())
            {
                customerIdCode = $"gtag('set', {{'user_id': '{_workContext.CurrentCustomer.Id}'}});{Environment.NewLine}";
            }
            analyticsTrackingScript = analyticsTrackingScript.Replace("{CUSTOMER_TRACKING}", customerIdCode);

            //ecommerce info
            var googleAnalyticsSettings = _settingService.LoadSetting <GoogleAnalyticsSettings>(_storeContext.CurrentStore.Id);

            //ensure that ecommerce tracking code is renderred only once (avoid duplicated data in Google Analytics)
            if (order != null && !_genericAttributeService.GetAttribute <bool>(order, ORDER_ALREADY_PROCESSED_ATTRIBUTE_NAME))
            {
                var usCulture = new CultureInfo("en-US");

                var analyticsEcommerceScript = @"gtag('event', 'purchase', {
                    'transaction_id': '{ORDERID}',
                    'affiliation': '{SITE}',
                    'value': {TOTAL},
                    'currency': '{CURRENCY}',
                    'tax': {TAX},
                    'shipping': {SHIP},
                    'items': [
                    {DETAILS}
                    ]
                });";
                analyticsEcommerceScript = analyticsEcommerceScript.Replace("{ORDERID}", FixIllegalJavaScriptChars(order.CustomOrderNumber));
                analyticsEcommerceScript = analyticsEcommerceScript.Replace("{SITE}", FixIllegalJavaScriptChars(_storeContext.CurrentStore.Name));
                analyticsEcommerceScript = analyticsEcommerceScript.Replace("{TOTAL}", order.OrderTotal.ToString("0.00", usCulture));
                var currencyCode = _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId).CurrencyCode;
                analyticsEcommerceScript = analyticsEcommerceScript.Replace("{CURRENCY}", currencyCode);
                analyticsEcommerceScript = analyticsEcommerceScript.Replace("{TAX}", order.OrderTax.ToString("0.00", usCulture));
                var orderShipping = googleAnalyticsSettings.IncludingTax ? order.OrderShippingInclTax : order.OrderShippingExclTax;
                analyticsEcommerceScript = analyticsEcommerceScript.Replace("{SHIP}", orderShipping.ToString("0.00", usCulture));

                var sb = new StringBuilder();
                int listingPosition = 1;
                foreach (var item in order.OrderItems)
                {
                    if (!String.IsNullOrEmpty(sb.ToString()))
                    {
                        sb.AppendLine(",");
                    }

                    string analyticsEcommerceDetailScript = @"{
                    'id': '{PRODUCTSKU}',
                    'name': '{PRODUCTNAME}',
                    'category': '{CATEGORYNAME}',
                    'list_position': {LISTPOSITION},
                    'quantity': {QUANTITY},
                    'price': '{UNITPRICE}'
                    }
                    ";
                    var    sku = _productService.FormatSku(item.Product, item.AttributesXml);
                    if (String.IsNullOrEmpty(sku))
                    {
                        sku = item.Product.Id.ToString();
                    }
                    analyticsEcommerceDetailScript = analyticsEcommerceDetailScript.Replace("{PRODUCTSKU}", FixIllegalJavaScriptChars(sku));
                    analyticsEcommerceDetailScript = analyticsEcommerceDetailScript.Replace("{PRODUCTNAME}", FixIllegalJavaScriptChars(item.Product.Name));
                    string category = _categoryService.GetProductCategoriesByProductId(item.ProductId).FirstOrDefault()?.Category.Name;
                    analyticsEcommerceDetailScript = analyticsEcommerceDetailScript.Replace("{CATEGORYNAME}", FixIllegalJavaScriptChars(category));
                    analyticsEcommerceDetailScript = analyticsEcommerceDetailScript.Replace("{LISTPOSITION}", listingPosition.ToString());
                    var unitPrice = googleAnalyticsSettings.IncludingTax ? item.UnitPriceInclTax : item.UnitPriceExclTax;
                    analyticsEcommerceDetailScript = analyticsEcommerceDetailScript.Replace("{QUANTITY}", item.Quantity.ToString());
                    analyticsEcommerceDetailScript = analyticsEcommerceDetailScript.Replace("{UNITPRICE}", unitPrice.ToString("0.00", usCulture));
                    sb.AppendLine(analyticsEcommerceDetailScript);

                    listingPosition++;
                }

                analyticsEcommerceScript = analyticsEcommerceScript.Replace("{DETAILS}", sb.ToString());

                analyticsTrackingScript = analyticsTrackingScript.Replace("{ECOMMERCE_TRACKING}", analyticsEcommerceScript);

                _genericAttributeService.SaveAttribute(order, ORDER_ALREADY_PROCESSED_ATTRIBUTE_NAME, true);
            }
            else
            {
                analyticsTrackingScript = analyticsTrackingScript.Replace("{ECOMMERCE_TRACKING}", "");
            }

            return(analyticsTrackingScript);
        }
        public ActionResult Category(int categoryId, CatalogSearchQuery query)
        {
            var category = _categoryService.GetCategoryById(categoryId);

            if (category == null || category.Deleted)
            {
                return(HttpNotFound());
            }

            // Check whether the current user has a "Manage catalog" permission.
            // It allows him to preview a category before publishing.
            if (!category.Published && !Services.Permissions.Authorize(Permissions.Catalog.Category.Read))
            {
                return(HttpNotFound());
            }

            // ACL (access control list).
            if (!_aclService.Authorize(category))
            {
                return(HttpNotFound());
            }

            // Store mapping.
            if (!_storeMappingService.Authorize(category))
            {
                return(HttpNotFound());
            }

            var store    = Services.StoreContext.CurrentStore;
            var customer = Services.WorkContext.CurrentCustomer;

            // 'Continue shopping' URL.
            if (!Services.WorkContext.CurrentCustomer.IsSystemAccount)
            {
                _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.LastContinueShoppingPage, Services.WebHelper.GetThisPageUrl(false), store.Id);
            }

            var model = category.ToModel();

            if (query.IsSubPage && !_catalogSettings.ShowDescriptionInSubPages)
            {
                model.Description.ChangeValue(string.Empty);
                model.BottomDescription.ChangeValue(string.Empty);
            }

            Services.DisplayControl.Announce(category);

            // Category breadcrumb.
            if (_catalogSettings.CategoryBreadcrumbEnabled)
            {
                _helper.GetCategoryBreadcrumb(_breadcrumb, ControllerContext);
            }

            // Products.
            var catIds = new int[] { categoryId };

            if (_catalogSettings.ShowProductsFromSubcategories)
            {
                // Include subcategories.
                catIds = catIds.Concat(_helper.GetChildCategoryIds(categoryId)).ToArray();
            }

            query.WithCategoryIds(_catalogSettings.IncludeFeaturedProductsInNormalLists ? (bool?)null : false, catIds);

            var searchResult = _catalogSearchService.Search(query);

            model.SearchResult = searchResult;

            var mappingSettings = _helper.GetBestFitProductSummaryMappingSettings(query.GetViewMode());

            model.Products = _helper.MapProductSummaryModel(searchResult.Hits, mappingSettings);

            model.SubCategoryDisplayType = _catalogSettings.SubCategoryDisplayType;

            var customerRolesIds = customer.CustomerRoles.Where(x => x.Active).Select(x => x.Id).ToList();
            var pictureSize      = _mediaSettings.CategoryThumbPictureSize;
            var fallbackType     = _catalogSettings.HideCategoryDefaultPictures ? FallbackPictureType.NoFallback : FallbackPictureType.Entity;

            var hideSubCategories = _catalogSettings.SubCategoryDisplayType == SubCategoryDisplayType.Hide ||
                                    (_catalogSettings.SubCategoryDisplayType == SubCategoryDisplayType.AboveProductList && query.IsSubPage && !_catalogSettings.ShowSubCategoriesInSubPages);
            var hideFeaturedProducts = _catalogSettings.IgnoreFeaturedProducts || (query.IsSubPage && !_catalogSettings.IncludeFeaturedProductsInSubPages);

            // Subcategories.
            if (!hideSubCategories)
            {
                var subCategories = _categoryService.GetAllCategoriesByParentCategoryId(categoryId);
                model.SubCategories = _helper.MapCategorySummaryModel(subCategories, pictureSize);
            }

            // Featured Products.
            if (!hideFeaturedProducts)
            {
                CatalogSearchResult featuredProductsResult = null;

                string cacheKey = ModelCacheEventConsumer.CATEGORY_HAS_FEATURED_PRODUCTS_KEY.FormatInvariant(categoryId, string.Join(",", customerRolesIds), store.Id);
                var    hasFeaturedProductsCache = Services.Cache.Get <bool?>(cacheKey);

                var featuredProductsQuery = new CatalogSearchQuery()
                                            .VisibleOnly(customer)
                                            .WithVisibility(ProductVisibility.Full)
                                            .WithCategoryIds(true, categoryId)
                                            .HasStoreId(Services.StoreContext.CurrentStore.Id)
                                            .WithLanguage(Services.WorkContext.WorkingLanguage)
                                            .WithCurrency(Services.WorkContext.WorkingCurrency);

                if (!hasFeaturedProductsCache.HasValue)
                {
                    featuredProductsResult   = _catalogSearchService.Search(featuredProductsQuery);
                    hasFeaturedProductsCache = featuredProductsResult.TotalHitsCount > 0;
                    Services.Cache.Put(cacheKey, hasFeaturedProductsCache, TimeSpan.FromHours(6));
                }

                if (hasFeaturedProductsCache.Value && featuredProductsResult == null)
                {
                    featuredProductsResult = _catalogSearchService.Search(featuredProductsQuery);
                }

                if (featuredProductsResult != null)
                {
                    var featuredProductsmappingSettings = _helper.GetBestFitProductSummaryMappingSettings(ProductSummaryViewMode.Grid);
                    model.FeaturedProducts = _helper.MapProductSummaryModel(featuredProductsResult.Hits, featuredProductsmappingSettings);
                }
            }

            // Prepare paging/sorting/mode stuff.
            _helper.MapListActions(model.Products, category, _catalogSettings.DefaultPageSizeOptions);

            // Template.
            var templateCacheKey = string.Format(ModelCacheEventConsumer.CATEGORY_TEMPLATE_MODEL_KEY, category.CategoryTemplateId);
            var templateViewPath = Services.Cache.Get(templateCacheKey, () =>
            {
                var template = _categoryTemplateService.GetCategoryTemplateById(category.CategoryTemplateId);
                if (template == null)
                {
                    template = _categoryTemplateService.GetAllCategoryTemplates().FirstOrDefault();
                }
                return(template.ViewPath);
            });

            // Activity log.
            Services.CustomerActivity.InsertActivity("PublicStore.ViewCategory", T("ActivityLog.PublicStore.ViewCategory"), category.Name);

            return(View(templateViewPath, model));
        }
Exemple #7
0
            /// <summary>
            /// Called before the action executes, after model binding is complete
            /// </summary>
            /// <param name="context">A context for action filters</param>
            public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
            {
                await next();

                if (context == null || context.HttpContext == null || context.HttpContext.Request == null)
                {
                    return;
                }

                if (!DataSettingsHelper.DatabaseIsInstalled())
                {
                    return;
                }

                //only in GET requests
                if (!HttpMethods.IsGet(context.HttpContext.Request.Method))
                {
                    return;
                }

                //ajax request should not save
                bool isAjaxCall = context.HttpContext.Request.Headers["x-requested-with"] == "XMLHttpRequest";

                if (isAjaxCall)
                {
                    return;
                }

                //whether is need to store last visited page URL
                if (!_customerSettings.StoreLastVisitedPage)
                {
                    return;
                }

                //get current page
                var pageUrl = _webHelper.GetThisPageUrl(true);

                if (string.IsNullOrEmpty(pageUrl))
                {
                    return;
                }

                //get previous last page
                var previousPageUrl = _workContext.CurrentCustomer.GetAttributeFromEntity <string>(SystemCustomerAttributeNames.LastVisitedPage);

                //save new one if don't match
                if (!pageUrl.Equals(previousPageUrl, StringComparison.OrdinalIgnoreCase))
                {
                    await _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer, SystemCustomerAttributeNames.LastVisitedPage, pageUrl);
                }

                if (!string.IsNullOrEmpty(context.HttpContext.Request.Headers[HeaderNames.Referer]))
                {
                    if (!context.HttpContext.Request.Headers[HeaderNames.Referer].ToString().Contains(context.HttpContext.Request.Host.ToString()))
                    {
                        var previousUrlReferrer = _workContext.CurrentCustomer.GetAttribute <string>(_genericAttributeService, SystemCustomerAttributeNames.LastUrlReferrer);
                        var actualUrlReferrer   = context.HttpContext.Request.Headers[HeaderNames.Referer];
                        if (previousUrlReferrer != actualUrlReferrer)
                        {
                            await _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer, SystemCustomerAttributeNames.LastUrlReferrer, actualUrlReferrer);
                        }
                    }
                }

                if (_customerSettings.SaveVisitedPage)
                {
                    if (!_workContext.CurrentCustomer.IsSearchEngineAccount())
                    {
                        await _customerActivityService.InsertActivityAsync("PublicStore.Url", pageUrl, pageUrl, _workContext.CurrentCustomer.Id, _webHelper.GetCurrentIpAddress());
                    }
                }
            }
Exemple #8
0
 public virtual IActionResult EuCookieLawAccept()
 {
     //save setting
     _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer, SystemCustomerAttributeNames.EuCookieLawAccepted, true);
     return(Json(new { stored = true }));
 }
 public void HandleEvent(OrderPlacedEvent eventMessage)
 {
     _genericAttributeService.SaveAttribute <decimal>(_workContext.CurrentCustomer, CustomCustomerAttributeNames.DeliveryMethodRate, 0, _storeContext.CurrentStore.Id);
     _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer, CustomCustomerAttributeNames.DeliveryMethodAddress, "", _storeContext.CurrentStore.Id);
     _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer, CustomCustomerAttributeNames.DeliveryMethod, "", _storeContext.CurrentStore.Id);
 }
        public virtual async Task <IActionResult> ApplyDiscountCoupon(string discountcouponcode)
        {
            var cart = _shoppingCartService.GetShoppingCart(_storeContext.CurrentStore.Id, PrepareCartTypes());

            var message   = string.Empty;
            var isApplied = false;

            if (!string.IsNullOrWhiteSpace(discountcouponcode))
            {
                discountcouponcode = discountcouponcode.ToUpper();
                //we find even hidden records here. this way we can display a user-friendly message if it's expired
                var discount = await _discountService.GetDiscountByCouponCode(discountcouponcode, true);

                if (discount != null && discount.RequiresCouponCode)
                {
                    var coupons       = _workContext.CurrentCustomer.ParseAppliedCouponCodes(SystemCustomerAttributeNames.DiscountCoupons);
                    var existsAndUsed = false;
                    foreach (var item in coupons)
                    {
                        if (await _discountService.ExistsCodeInDiscount(item, discount.Id, null))
                        {
                            existsAndUsed = true;
                        }
                    }
                    if (!existsAndUsed)
                    {
                        if (!discount.Reused)
                        {
                            existsAndUsed = !await _discountService.ExistsCodeInDiscount(discountcouponcode, discount.Id, false);
                        }

                        if (!existsAndUsed)
                        {
                            var validationResult = await _discountService.ValidateDiscount(discount, _workContext.CurrentCustomer, discountcouponcode);

                            if (validationResult.IsValid)
                            {
                                //valid
                                var applyCouponCode = _workContext.CurrentCustomer.ApplyCouponCode(SystemCustomerAttributeNames.DiscountCoupons, discountcouponcode);
                                //apply new value
                                await _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer, SystemCustomerAttributeNames.DiscountCoupons, applyCouponCode);

                                message   = _localizationService.GetResource("ShoppingCart.DiscountCouponCode.Applied");
                                isApplied = true;
                            }
                            else
                            {
                                if (!String.IsNullOrEmpty(validationResult.UserError))
                                {
                                    //some user error
                                    message   = validationResult.UserError;
                                    isApplied = false;
                                }
                                else
                                {
                                    //general error text
                                    message   = _localizationService.GetResource("ShoppingCart.DiscountCouponCode.WrongDiscount");
                                    isApplied = false;
                                }
                            }
                        }
                        else
                        {
                            message   = _localizationService.GetResource("ShoppingCart.DiscountCouponCode.WasUsed");
                            isApplied = false;
                        }
                    }
                    else
                    {
                        message   = _localizationService.GetResource("ShoppingCart.DiscountCouponCode.UsesTheSameDiscount");
                        isApplied = false;
                    }
                }
                else
                {
                    message   = _localizationService.GetResource("ShoppingCart.DiscountCouponCode.WrongDiscount");
                    isApplied = false;
                }
            }
            else
            {
                message   = _localizationService.GetResource("ShoppingCart.DiscountCouponCode.Required");
                isApplied = false;
            }

            var model = await _mediator.Send(new GetShoppingCart()
            {
                Cart           = cart,
                Customer       = _workContext.CurrentCustomer,
                Currency       = _workContext.WorkingCurrency,
                Language       = _workContext.WorkingLanguage,
                Store          = _storeContext.CurrentStore,
                TaxDisplayType = _workContext.TaxDisplayType
            });

            model.DiscountBox.Message   = message;
            model.DiscountBox.IsApplied = isApplied;

            return(Json(new
            {
                cart = RenderViewComponentToString("OrderSummary", new { overriddenModel = model }),
                model = model
            }));
        }
        /// <summary>
        /// Create request parameters to charge transaction
        /// </summary>
        /// <param name="paymentRequest">Payment request parameters</param>
        /// <param name="isRecurringPayment">Whether it is a recurring payment</param>
        /// <returns>Charge request parameters</returns>
        private ChargeRequest CreateChargeRequest(ProcessPaymentRequest paymentRequest, bool isRecurringPayment)
        {
            //get customer
            var customer = _customerService.GetCustomerById(paymentRequest.CustomerId);

            if (customer == null)
            {
                throw new NopException("Customer cannot be loaded");
            }

            //whether USD is available
            var usdCurrency = _currencyService.GetCurrencyByCode("USD");

            if (usdCurrency == null)
            {
                throw new NopException("USD currency cannot be loaded");
            }

            //create common charge request parameters
            var request = new ChargeRequest
            {
                OrderId = CommonHelper.EnsureMaximumLength(paymentRequest.OrderGuid.ToString(), 25),
                TransactionDuplicateCheckType = TransactionDuplicateCheckType.NoCheck,
                ExtendedInformation           = new ExtendedInformation
                {
                    InvoiceNumber      = paymentRequest.OrderGuid.ToString(),
                    InvoiceDescription = $"Order from the '{_storeService.GetStoreById(paymentRequest.StoreId)?.Name}'"
                }
            };

            //set amount in USD
            var amount = _currencyService.ConvertFromPrimaryStoreCurrency(paymentRequest.OrderTotal, usdCurrency);

            request.Amount = Math.Round(amount, 2);

            //get current shopping cart
            var shoppingCart = customer.ShoppingCartItems
                               .Where(shoppingCartItem => shoppingCartItem.ShoppingCartType == ShoppingCartType.ShoppingCart)
                               .LimitPerStore(paymentRequest.StoreId).ToList();

            //whether there are non-downloadable items in the shopping cart
            var nonDownloadable = shoppingCart.Any(item => !item.Product.IsDownload);

            request.ExtendedInformation.GoodsType = nonDownloadable ? GoodsType.Physical : GoodsType.Digital;

            //try to get previously stored card details
            var storedCardKey = _localizationService.GetResource("Plugins.Payments.Worldpay.Fields.StoredCard.Key");

            if (paymentRequest.CustomValues.TryGetValue(storedCardKey, out object storedCardId) && !storedCardId.ToString().Equals(Guid.Empty.ToString()))
            {
                //check whether customer exists in Vault
                var vaultCustomer = _worldpayPaymentManager.GetCustomer(customer.GetAttribute <string>(WorldpayPaymentDefaults.CustomerIdAttribute))
                                    ?? throw new NopException("Failed to retrieve customer");

                //use previously stored card to charge
                request.PaymentVaultToken = new VaultToken
                {
                    CustomerId      = vaultCustomer.CustomerId,
                    PaymentMethodId = storedCardId.ToString()
                };

                return(request);
            }

            //or try to get the card token
            var cardTokenKey = _localizationService.GetResource("Plugins.Payments.Worldpay.Fields.Token.Key");

            if (!paymentRequest.CustomValues.TryGetValue(cardTokenKey, out object token) || string.IsNullOrEmpty(token?.ToString()))
            {
                throw new NopException("Failed to get the card token");
            }

            //remove the card token from payment custom values, since it is no longer needed
            paymentRequest.CustomValues.Remove(cardTokenKey);

            //public key is required to pay with card token
            request.PaymentVaultToken = new VaultToken
            {
                PublicKey = _worldpayPaymentSettings.PublicKey
            };

            //whether to save card details for the future purchasing
            var saveCardKey = _localizationService.GetResource("Plugins.Payments.Worldpay.Fields.SaveCard.Key");

            if (paymentRequest.CustomValues.TryGetValue(saveCardKey, out object saveCardValue) && saveCardValue is bool saveCard && saveCard && !customer.IsGuest())
            {
                //remove the value from payment custom values, since it is no longer needed
                paymentRequest.CustomValues.Remove(saveCardKey);

                try
                {
                    //check whether customer exists and try to create the new one, if not exists
                    var vaultCustomer = _worldpayPaymentManager.GetCustomer(customer.GetAttribute <string>(WorldpayPaymentDefaults.CustomerIdAttribute))
                                        ?? _worldpayPaymentManager.CreateCustomer(new CreateCustomerRequest
                    {
                        CustomerId = customer.Id.ToString(),
                        CustomerDuplicateCheckType = CustomerDuplicateCheckType.Ignore,
                        EmailReceiptEnabled        = !string.IsNullOrEmpty(customer.Email),
                        Email          = customer.Email,
                        FirstName      = customer.GetAttribute <string>(SystemCustomerAttributeNames.FirstName),
                        LastName       = customer.GetAttribute <string>(SystemCustomerAttributeNames.LastName),
                        Company        = customer.GetAttribute <string>(SystemCustomerAttributeNames.Company),
                        Phone          = customer.GetAttribute <string>(SystemCustomerAttributeNames.Phone),
                        BillingAddress = new Address
                        {
                            Line1   = customer.BillingAddress?.Address1,
                            City    = customer.BillingAddress?.City,
                            State   = customer.BillingAddress?.StateProvince?.Abbreviation,
                            Country = customer.BillingAddress?.Country?.TwoLetterIsoCode,
                            Zip     = customer.BillingAddress?.ZipPostalCode,
                            Company = customer.BillingAddress?.Company,
                            Phone   = customer.BillingAddress?.PhoneNumber
                        }
                    }) ?? throw new NopException("Failed to create customer. Error details in the log");

                    //save Vault customer identifier as a generic attribute
                    _genericAttributeService.SaveAttribute(customer, WorldpayPaymentDefaults.CustomerIdAttribute, vaultCustomer.CustomerId);

                    //add card to the Vault after charge
                    request.AddToVault = true;
                    request.PaymentVaultToken.CustomerId = vaultCustomer.CustomerId;
                }
                catch (Exception exception)
                {
                    _logger.Warning(exception.Message, exception, customer);
                    if (isRecurringPayment)
                    {
                        throw new NopException("For recurring payments you need to save the card details");
                    }
                }
            }
        private static ShippingOption GetDefaultShippingOption(
            IShippingService shippingService,
            IWorkContext workContext,
            IStoreContext storeContext,
            ICountryService countryService,
            IStateProvinceService stateProvinceService,
            IGenericAttributeService genericAttributeService)
        {
            // TODO: set these values in the config? - like EstimateShipping but default values are provided?
            int countryId = 80; // UK
            int? stateProvinceId = null;
            string zipPostalCode = "SB2 8BW";
            Address address = new Address
            {
                CountryId = countryId,
                Country = countryService.GetCountryById(countryId),
                StateProvinceId = stateProvinceId,
                StateProvince = stateProvinceId.HasValue ? stateProvinceService.GetStateProvinceById(stateProvinceId.Value) : null,
                ZipPostalCode = zipPostalCode,
            };

            if (workContext.CurrentCustomer.ShippingAddress != null)
            {
                address = workContext.CurrentCustomer.ShippingAddress;
            }

            List<ShoppingCartItem> cart = workContext.CurrentCustomer.ShoppingCartItems
                .Where(sci => sci.ShoppingCartType == ShoppingCartType.ShoppingCart)
                .LimitPerStore(storeContext.CurrentStore.Id)
                .ToList();

            GetShippingOptionResponse shippingOptionResponse = shippingService.GetShippingOptions(cart, address);

            ShippingOption selectedShippingOption = shippingOptionResponse.ShippingOptions.FirstOrDefault();
            genericAttributeService.SaveAttribute(workContext.CurrentCustomer, SystemCustomerAttributeNames.SelectedShippingOption, selectedShippingOption, storeContext.CurrentStore.Id);

            return selectedShippingOption;
        }
Exemple #13
0
        public async Task <string> Handle(SaveCheckoutAttributesCommand request, CancellationToken cancellationToken)
        {
            if (request.Cart == null)
            {
                throw new ArgumentNullException("cart");
            }

            if (request.Form == null)
            {
                throw new ArgumentNullException("form");
            }

            string attributesXml      = "";
            var    checkoutAttributes = await _checkoutAttributeService.GetAllCheckoutAttributes(request.Store.Id, !request.Cart.RequiresShipping());

            foreach (var attribute in checkoutAttributes)
            {
                string controlId = string.Format("checkout_attribute_{0}", attribute.Id);
                switch (attribute.AttributeControlType)
                {
                case AttributeControlType.DropdownList:
                case AttributeControlType.RadioList:
                case AttributeControlType.ColorSquares:
                case AttributeControlType.ImageSquares:
                {
                    var ctrlAttributes = request.Form[controlId];
                    if (!String.IsNullOrEmpty(ctrlAttributes))
                    {
                        attributesXml = _checkoutAttributeParser.AddCheckoutAttribute(attributesXml,
                                                                                      attribute, ctrlAttributes);
                    }
                }
                break;

                case AttributeControlType.Checkboxes:
                {
                    var cblAttributes = request.Form[controlId].ToString();
                    if (!String.IsNullOrEmpty(cblAttributes))
                    {
                        foreach (var item in cblAttributes.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                        {
                            attributesXml = _checkoutAttributeParser.AddCheckoutAttribute(attributesXml, attribute, item);
                        }
                    }
                }
                break;

                case AttributeControlType.ReadonlyCheckboxes:
                {
                    //load read-only (already server-side selected) values
                    var attributeValues = attribute.CheckoutAttributeValues;
                    foreach (var selectedAttributeId in attributeValues
                             .Where(v => v.IsPreSelected)
                             .Select(v => v.Id)
                             .ToList())
                    {
                        attributesXml = _checkoutAttributeParser.AddCheckoutAttribute(attributesXml,
                                                                                      attribute, selectedAttributeId.ToString());
                    }
                }
                break;

                case AttributeControlType.TextBox:
                case AttributeControlType.MultilineTextbox:
                {
                    var ctrlAttributes = request.Form[controlId].ToString();
                    if (!String.IsNullOrEmpty(ctrlAttributes))
                    {
                        string enteredText = ctrlAttributes.Trim();
                        attributesXml = _checkoutAttributeParser.AddCheckoutAttribute(attributesXml,
                                                                                      attribute, enteredText);
                    }
                }
                break;

                case AttributeControlType.Datepicker:
                {
                    var      date         = request.Form[controlId + "_day"];
                    var      month        = request.Form[controlId + "_month"];
                    var      year         = request.Form[controlId + "_year"];
                    DateTime?selectedDate = null;
                    try
                    {
                        selectedDate = new DateTime(Int32.Parse(year), Int32.Parse(month), Int32.Parse(date));
                    }
                    catch { }
                    if (selectedDate.HasValue)
                    {
                        attributesXml = _checkoutAttributeParser.AddCheckoutAttribute(attributesXml,
                                                                                      attribute, selectedDate.Value.ToString("D"));
                    }
                }
                break;

                case AttributeControlType.FileUpload:
                {
                    Guid downloadGuid;
                    Guid.TryParse(request.Form[controlId], out downloadGuid);
                    var download = await _downloadService.GetDownloadByGuid(downloadGuid);

                    if (download != null)
                    {
                        attributesXml = _checkoutAttributeParser.AddCheckoutAttribute(attributesXml,
                                                                                      attribute, download.DownloadGuid.ToString());
                    }
                }
                break;

                default:
                    break;
                }
            }

            //save checkout attributes
            //validate conditional attributes (if specified)
            foreach (var attribute in checkoutAttributes)
            {
                var conditionMet = await _checkoutAttributeParser.IsConditionMet(attribute, attributesXml);

                if (conditionMet.HasValue && !conditionMet.Value)
                {
                    attributesXml = _checkoutAttributeParser.RemoveCheckoutAttribute(attributesXml, attribute);
                }
            }
            await _genericAttributeService.SaveAttribute(request.Customer, SystemCustomerAttributeNames.CheckoutAttributes, attributesXml, request.Store.Id);

            return(attributesXml);
        }
        public IActionResult CreateProduct([ModelBinder(typeof(JsonModelBinder <ProductDto>))] Delta <ProductDto> productDelta)
        {
            var genricAttribute = _genericAttributeRepository.Table.Where(g => g.Key == "nop.product.admindid" && g.Value == productDelta.Dto.AdmindId.ToString()).FirstOrDefault();

            Product product = null;

            if (genricAttribute == null)
            {
                // Here we display the errors if the validation has failed at some point.
                if (!ModelState.IsValid)
                {
                    return(Error());
                }

                // Inserting the new product
                product = _factory.Initialize();

                productDelta.Merge(product);

                _productService.InsertProduct(product);

                UpdateProductPictures(product, productDelta.Dto.Images);

                UpdateProductTags(product, productDelta.Dto.Tags);

                UpdateProductManufacturers(product, productDelta.Dto.ManufacturerIds);

                UpdateAssociatedProducts(product, productDelta.Dto.AssociatedProductIds);
                /*EXTRA*/
                UpdateProductAttributes(product, productDelta);

                UpdateProductAttributeCombinations(product, productDelta.Dto.ProductAttributeCombinations);

                UpdateProductTirePrices(product, productDelta.Dto.DtoTierPrices);

                UpdateProductGenericAttributes(product, productDelta.Dto.DtoGenericAttributes);

                _genericAttributeService.SaveAttribute <int>(product, "nop.product.admindid", productDelta.Dto.AdmindId);
                /*EXTRA*/

                //search engine name
                var seName = _urlRecordService.ValidateSeName(product, productDelta.Dto.SeName, product.Name, true);
                _urlRecordService.SaveSlug(product, seName, 0);

                UpdateAclRoles(product, productDelta.Dto.RoleIds);

                UpdateDiscountMappings(product, productDelta.Dto.DiscountIds);

                UpdateStoreMappings(product, productDelta.Dto.StoreIds);

                _productService.UpdateProduct(product);

                CustomerActivityService.InsertActivity("AddNewProduct",
                                                       LocalizationService.GetResource("ActivityLog.AddNewProduct"), product);
            }
            else
            {
                product = _productService.GetProductById(genricAttribute.EntityId);
            }

            if (product == null)
            {
                return(Error(HttpStatusCode.Conflict, "product", "could not find product!"));
            }

            // Preparing the result dto of the new product
            var productDto = _dtoHelper.PrepareProductDTO(product);

            /*EXTRA*/
            productDto.AdmindId = _genericAttributeService.GetAttribute <int>(product, "nop.product.admindid");
            /*EXTRA*/

            var productsRootObject = new ProductsRootObjectDto();

            productsRootObject.Products.Add(productDto);

            var json = JsonFieldsSerializer.Serialize(productsRootObject, string.Empty);

            return(new RawJsonActionResult(json));
        }
Exemple #15
0
        public ActionResult Search(CatalogSearchQuery query)
        {
            var model = new SearchResultModel(query);
            CatalogSearchResult result = null;

            if (query.Term == null || query.Term.Length < _searchSettings.InstantSearchTermMinLength)
            {
                model.SearchResult = new CatalogSearchResult(query);
                model.Error        = T("Search.SearchTermMinimumLengthIsNCharacters", _searchSettings.InstantSearchTermMinLength);
                return(View(model));
            }

            // 'Continue shopping' URL
            _genericAttributeService.SaveAttribute(Services.WorkContext.CurrentCustomer,
                                                   SystemCustomerAttributeNames.LastContinueShoppingPage,
                                                   Services.WebHelper.GetThisPageUrl(false),
                                                   Services.StoreContext.CurrentStore.Id);

            try
            {
                result = _catalogSearchService.Search(query);
            }
            catch (Exception ex)
            {
                model.Error = ex.ToString();
                result      = new CatalogSearchResult(query);
            }

            if (result.TotalHitsCount == 0 && result.SpellCheckerSuggestions.Any())
            {
                // No matches, but spell checker made a suggestion.
                // We implicitly search again with the first suggested term.
                var oldSuggestions = result.SpellCheckerSuggestions;
                var oldTerm        = query.Term;
                query.Term = oldSuggestions[0];

                result = _catalogSearchService.Search(query);

                if (result.TotalHitsCount > 0)
                {
                    model.AttemptedTerm = oldTerm;
                    // Restore the original suggestions.
                    result.SpellCheckerSuggestions = oldSuggestions.Where(x => x != query.Term).ToArray();
                }
                else
                {
                    query.Term = oldTerm;
                }
            }

            model.SearchResult       = result;
            model.Term               = query.Term;
            model.TotalProductsCount = result.TotalHitsCount;

            var mappingSettings = _catalogHelper.GetBestFitProductSummaryMappingSettings(query.GetViewMode());
            var summaryModel    = _catalogHelper.MapProductSummaryModel(result.Hits, mappingSettings);

            // Prepare paging/sorting/mode stuff.
            _catalogHelper.MapListActions(summaryModel, null, _catalogSettings.DefaultPageSizeOptions);

            // Add product hits.
            model.TopProducts = summaryModel;

            return(View(model));
        }
Exemple #16
0
        /// <summary>
        /// Sets a user email
        /// </summary>
        /// <param name="customer">Customer</param>
        /// <param name="newEmail">New email</param>
        /// <param name="requireValidation">Require validation of new email address</param>
        public virtual void SetEmail(Customer customer, string newEmail, bool requireValidation)
        {
            if (customer == null)
            {
                throw new ArgumentNullException(nameof(customer));
            }

            if (newEmail == null)
            {
                throw new NopException("Email cannot be null");
            }

            newEmail = newEmail.Trim();
            var oldEmail = customer.Email;

            if (!CommonHelper.IsValidEmail(newEmail))
            {
                throw new NopException(_localizationService.GetResource("Account.EmailUsernameErrors.NewEmailIsNotValid"));
            }

            if (newEmail.Length > 100)
            {
                throw new NopException(_localizationService.GetResource("Account.EmailUsernameErrors.EmailTooLong"));
            }

            var customer2 = _customerService.GetCustomerByEmail(newEmail);

            if (customer2 != null && customer.Id != customer2.Id)
            {
                throw new NopException(_localizationService.GetResource("Account.EmailUsernameErrors.EmailAlreadyExists"));
            }

            if (requireValidation)
            {
                //re-validate email
                customer.EmailToRevalidate = newEmail;
                _customerService.UpdateCustomer(customer);

                //email re-validation message
                _genericAttributeService.SaveAttribute(customer, NopCustomerDefaults.EmailRevalidationTokenAttribute, Guid.NewGuid().ToString());
                _workflowMessageService.SendCustomerEmailRevalidationMessage(customer, _workContext.WorkingLanguage.Id);
            }
            else
            {
                customer.Email = newEmail;
                _customerService.UpdateCustomer(customer);

                if (string.IsNullOrEmpty(oldEmail) || oldEmail.Equals(newEmail, StringComparison.InvariantCultureIgnoreCase))
                {
                    return;
                }

                //update newsletter subscription (if required)
                foreach (var store in _storeService.GetAllStores())
                {
                    var subscriptionOld = _newsLetterSubscriptionService.GetNewsLetterSubscriptionByEmailAndStoreId(oldEmail, store.Id);

                    if (subscriptionOld == null)
                    {
                        continue;
                    }

                    subscriptionOld.Email = newEmail;
                    _newsLetterSubscriptionService.UpdateNewsLetterSubscription(subscriptionOld);
                }
            }
        }
Exemple #17
0
        protected CheckoutShippingMethodModel PrepareShippingMethodModel(IList <OrganizedShoppingCartItem> cart)
        {
            var model = new CheckoutShippingMethodModel();

            var getShippingOptionResponse = _shippingService.GetShippingOptions(cart, _workContext.CurrentCustomer.ShippingAddress, "", _storeContext.CurrentStore.Id);

            if (getShippingOptionResponse.Success)
            {
                //performance optimization. cache returned shipping options.
                //we'll use them later (after a customer has selected an option).
                _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer,
                                                       SystemCustomerAttributeNames.OfferedShippingOptions, getShippingOptionResponse.ShippingOptions, _storeContext.CurrentStore.Id);

                var shippingMethods = _shippingService.GetAllShippingMethods();

                foreach (var shippingOption in getShippingOptionResponse.ShippingOptions)
                {
                    var soModel = new CheckoutShippingMethodModel.ShippingMethodModel()
                    {
                        ShippingMethodId = shippingOption.ShippingMethodId,
                        Name             = shippingOption.Name,
                        Description      = shippingOption.Description,
                        ShippingRateComputationMethodSystemName = shippingOption.ShippingRateComputationMethodSystemName,
                    };

                    var srcmProvider = _shippingService.LoadShippingRateComputationMethodBySystemName(shippingOption.ShippingRateComputationMethodSystemName);
                    if (srcmProvider != null)
                    {
                        soModel.BrandUrl = _pluginMediator.GetBrandImageUrl(srcmProvider.Metadata);
                    }

                    //adjust rate
                    Discount appliedDiscount = null;
                    var      shippingTotal   = _orderTotalCalculationService.AdjustShippingRate(
                        shippingOption.Rate, cart, shippingOption.Name, shippingMethods, out appliedDiscount);

                    decimal rateBase = _taxService.GetShippingPrice(shippingTotal, _workContext.CurrentCustomer);
                    decimal rate     = _currencyService.ConvertFromPrimaryStoreCurrency(rateBase, _workContext.WorkingCurrency);
                    soModel.FeeRaw = rate;
                    soModel.Fee    = _priceFormatter.FormatShippingPrice(rate, true);

                    model.ShippingMethods.Add(soModel);
                }

                //find a selected (previously) shipping method
                var selectedShippingOption = _workContext.CurrentCustomer.GetAttribute <ShippingOption>(SystemCustomerAttributeNames.SelectedShippingOption, _storeContext.CurrentStore.Id);
                if (selectedShippingOption != null)
                {
                    var shippingOptionToSelect = model.ShippingMethods.ToList()
                                                 .Find(so => !String.IsNullOrEmpty(so.Name) && so.Name.Equals(selectedShippingOption.Name, StringComparison.InvariantCultureIgnoreCase) &&
                                                       !String.IsNullOrEmpty(so.ShippingRateComputationMethodSystemName) &&
                                                       so.ShippingRateComputationMethodSystemName.Equals(selectedShippingOption.ShippingRateComputationMethodSystemName, StringComparison.InvariantCultureIgnoreCase));

                    if (shippingOptionToSelect != null)
                    {
                        shippingOptionToSelect.Selected = true;
                    }
                }
                //if no option has been selected, let's do it for the first one
                if (model.ShippingMethods.Where(so => so.Selected).FirstOrDefault() == null)
                {
                    var shippingOptionToSelect = model.ShippingMethods.FirstOrDefault();
                    if (shippingOptionToSelect != null)
                    {
                        shippingOptionToSelect.Selected = true;
                    }
                }
            }
            else
            {
                foreach (var error in getShippingOptionResponse.Errors)
                {
                    model.Warnings.Add(error);
                }
            }

            return(model);
        }
        public IActionResult CreateCustomer([ModelBinder(typeof(JsonModelBinder <CustomerDto>))] Delta <CustomerDto> customerDelta)
        {
            // Here we display the errors if the validation has failed at some point.
            if (!ModelState.IsValid)
            {
                return(Error());
            }

            var customer = CustomerService.GetCustomerByEmail(customerDelta.Dto.Email);

            if (customer != null && !customer.Deleted)
            {
                return(Error(HttpStatusCode.Conflict, nameof(Customer.Email), "Email is already registered"));
            }

            //If the validation has passed the customerDelta object won't be null for sure so we don't need to check for this.

            // Inserting the new customer
            var newCustomer = _factory.Initialize();

            customerDelta.Merge(newCustomer);

            foreach (var address in customerDelta.Dto.Addresses)
            {
                // we need to explicitly set the date as if it is not specified
                // it will default to 01/01/0001 which is not supported by SQL Server and throws and exception
                if (address.CreatedOnUtc == null)
                {
                    address.CreatedOnUtc = DateTime.UtcNow;
                }

                CustomerService.InsertCustomerAddress(newCustomer, address.ToEntity());
            }

            CustomerService.InsertCustomer(newCustomer);

            InsertFirstAndLastNameGenericAttributes(customerDelta.Dto.FirstName, customerDelta.Dto.LastName, newCustomer);

            if (!string.IsNullOrEmpty(customerDelta.Dto.LanguageId) && int.TryParse(customerDelta.Dto.LanguageId, out var languageId) &&
                _languageService.GetLanguageById(languageId) != null)
            {
                _genericAttributeService.SaveAttribute(newCustomer, NopCustomerDefaults.LanguageIdAttribute, languageId);
            }

            //password
            if (!string.IsNullOrWhiteSpace(customerDelta.Dto.Password))
            {
                AddPassword(customerDelta.Dto.Password, newCustomer);
            }

            // We need to insert the entity first so we can have its id in order to map it to anything.
            // TODO: Localization
            // TODO: move this before inserting the customer.
            if (customerDelta.Dto.RoleIds.Count > 0)
            {
                AddValidRoles(customerDelta, newCustomer);
            }

            // Preparing the result dto of the new customer
            // We do not prepare the shopping cart items because we have a separate endpoint for them.
            var newCustomerDto = _dtoHelper.PrepareCustomerDTO(newCustomer);

            // This is needed because the entity framework won't populate the navigation properties automatically
            // and the country will be left null. So we do it by hand here.
            PopulateAddressCountryNames(newCustomerDto);

            // Set the fist and last name separately because they are not part of the customer entity, but are saved in the generic attributes.
            newCustomerDto.FirstName = customerDelta.Dto.FirstName;
            newCustomerDto.LastName  = customerDelta.Dto.LastName;

            newCustomerDto.LanguageId = customerDelta.Dto.LanguageId;

            //activity log
            CustomerActivityService.InsertActivity("AddNewCustomer", LocalizationService.GetResource("ActivityLog.AddNewCustomer"), newCustomer);

            var customersRootObject = new CustomersRootObject();

            customersRootObject.Customers.Add(newCustomerDto);

            var json = JsonFieldsSerializer.Serialize(customersRootObject, string.Empty);

            return(new RawJsonActionResult(json));
        }
Exemple #19
0
        public async Task <ActionResult> ImportXml(int id, FormCollection form, ImportModeFlags mode, bool updateTouched, int?availableLanguageSetId)
        {
            if (!_services.Permissions.Authorize(StandardPermissionProvider.ManageLanguages))
            {
                return(AccessDeniedView());
            }

            var language = _languageService.GetLanguageById(id);

            if (language == null)
            {
                return(RedirectToAction("List"));
            }

            // Set page timeout to 5 minutes
            this.Server.ScriptTimeout = 300;

            string tempFilePath = null;

            try
            {
                var file = Request.Files["importxmlfile"];
                if (file != null && file.ContentLength > 0)
                {
                    _services.Localization.ImportResourcesFromXml(language, file.InputStream.AsString(), mode: mode, updateTouchedResources: updateTouched);

                    NotifySuccess(T("Admin.Configuration.Languages.Imported"));
                }
                else if ((availableLanguageSetId ?? 0) != 0)
                {
                    var checkResult = await CheckAvailableResources();

                    var availableResources = checkResult.Resources.First(x => x.Id == availableLanguageSetId.Value);

                    tempFilePath = await DownloadAvailableResources(availableResources.DownloadUrl, _services.StoreContext.CurrentStore.Url);

                    var xmlDoc = new XmlDocument();
                    xmlDoc.Load(tempFilePath);

                    _services.Localization.ImportResourcesFromXml(language, xmlDoc, null, false, mode, updateTouched);

                    var str = JsonConvert.SerializeObject(new LastResourcesImportInfo
                    {
                        TranslatedPercentage = availableResources.TranslatedPercentage,
                        ImportedOn           = DateTime.UtcNow
                    });
                    _genericAttributeService.SaveAttribute(language, "LastResourcesImportInfo", str);

                    NotifySuccess(T("Admin.Configuration.Languages.Imported"));
                }
                else
                {
                    NotifyError(T("Admin.Configuration.Languages.UploadFileOrSelectLanguage"));
                }
            }
            catch (Exception exception)
            {
                NotifyError(exception);
                Logger.ErrorsAll(exception);
            }
            finally
            {
                FileSystemHelper.Delete(tempFilePath);
            }

            return(RedirectToAction("Edit", new { id = language.Id }));
        }
        public virtual IActionResult PasswordRecoverySend(PasswordRecoveryModel model)
        {
            if (ModelState.IsValid)
            {
                var user = _userService.GetUserByEmail(model.Email);
                if (user != null && user.Active && !user.Deleted)
                {
                    //save token and current date
                    var passwordRecoveryToken = Guid.NewGuid();
                    _genericAttributeService.SaveAttribute(user, NopUserDefaults.PasswordRecoveryTokenAttribute,
                                                           passwordRecoveryToken.ToString());
                    DateTime?generatedDateTime = DateTime.UtcNow;
                    _genericAttributeService.SaveAttribute(user,
                                                           NopUserDefaults.PasswordRecoveryTokenDateGeneratedAttribute, generatedDateTime);

                    //send email
                    _workflowMessageService.SendUserPasswordRecoveryMessage(user,
                                                                            _workContext.WorkingLanguage.Id);

                    model.Result = _localizationService.GetResource("Account.PasswordRecovery.EmailHasBeenSent");
                }
                else
                {
                    model.Result = _localizationService.GetResource("Account.PasswordRecovery.EmailNotFound");
                }

                return(View(model));
            }

            //If we got this far, something failed, redisplay form
            return(View(model));
        }
Exemple #21
0
        /// <summary>
        /// Register new user
        /// </summary>
        /// <param name="parameters">Authentication parameters received from external authentication method</param>
        /// <param name="returnUrl">URL to which the user will return after authentication</param>
        /// <returns>Result of an authentication</returns>
        protected virtual IActionResult RegisterNewUser(ExternalAuthenticationParameters parameters, string returnUrl)
        {
            //check whether the specified email has been already registered
            if (_customerService.GetCustomerByEmail(parameters.Email) != null)
            {
                var alreadyExistsError = string.Format(_localizationService.GetResource("Account.AssociatedExternalAuth.EmailAlreadyExists"),
                                                       !string.IsNullOrEmpty(parameters.ExternalDisplayIdentifier) ? parameters.ExternalDisplayIdentifier : parameters.ExternalIdentifier);
                return(ErrorAuthentication(new[] { alreadyExistsError }, returnUrl));
            }

            //registration is approved if validation isn't required
            var registrationIsApproved = _customerSettings.UserRegistrationType == UserRegistrationType.Standard ||
                                         (_customerSettings.UserRegistrationType == UserRegistrationType.EmailValidation && !_externalAuthenticationSettings.RequireEmailValidation);

            //create registration request
            var registrationRequest = new CustomerRegistrationRequest(_workContext.CurrentCustomer,
                                                                      parameters.Email, parameters.Email,
                                                                      CommonHelper.GenerateRandomDigitCode(20),
                                                                      PasswordFormat.Hashed,
                                                                      _storeContext.CurrentStore.Id,
                                                                      registrationIsApproved);

            //whether registration request has been completed successfully
            var registrationResult = _customerRegistrationService.RegisterCustomer(registrationRequest, out string _);

            if (!registrationResult.Success)
            {
                return(ErrorAuthentication(registrationResult.Errors, returnUrl));
            }

            //allow to save other customer values by consuming this event
            _eventPublisher.Publish(new CustomerAutoRegisteredByExternalMethodEvent(_workContext.CurrentCustomer, parameters));

            //raise customer registered event
            _eventPublisher.Publish(new CustomerRegisteredEvent(_workContext.CurrentCustomer));

            //store owner notifications
            if (_customerSettings.NotifyNewCustomerRegistration)
            {
                _workflowMessageService.SendCustomerRegisteredNotificationMessage(_workContext.CurrentCustomer, _localizationSettings.DefaultAdminLanguageId);
            }

            //associate external account with registered user
            AssociateExternalAccountWithUser(_workContext.CurrentCustomer, parameters);

            //authenticate
            if (registrationIsApproved)
            {
                _authenticationService.SignIn(_workContext.CurrentCustomer, false);
                _workflowMessageService.SendCustomerWelcomeMessage(_workContext.CurrentCustomer, _workContext.WorkingLanguage.Id);

                return(new RedirectToRouteResult("RegisterResult", new { resultId = (int)UserRegistrationType.Standard, returnUrl }));
            }

            //registration is succeeded but isn't activated
            if (_customerSettings.UserRegistrationType == UserRegistrationType.EmailValidation)
            {
                //email validation message
                _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer, NopCustomerDefaults.AccountActivationTokenAttribute, Guid.NewGuid().ToString());
                _workflowMessageService.SendCustomerEmailValidationMessage(_workContext.CurrentCustomer, _workContext.WorkingLanguage.Id);

                return(new RedirectToRouteResult("RegisterResult", new { resultId = (int)UserRegistrationType.EmailValidation }));
            }

            //registration is succeeded but isn't approved by admin
            if (_customerSettings.UserRegistrationType == UserRegistrationType.AdminApproval)
            {
                return(new RedirectToRouteResult("RegisterResult", new { resultId = (int)UserRegistrationType.AdminApproval }));
            }

            return(ErrorAuthentication(new[] { "Error on registration" }, returnUrl));
        }
        public virtual IActionResult ApplyVendorSubmit(ApplyVendorModel model, bool captchaValid, IFormFile uploadedFile)
        {
            if (!_vendorSettings.AllowCustomersToApplyForVendorAccount)
            {
                return(RedirectToRoute("HomePage"));
            }

            if (!_workContext.CurrentCustomer.IsRegistered())
            {
                return(Challenge());
            }

            //validate CAPTCHA
            if (_captchaSettings.Enabled && _captchaSettings.ShowOnApplyVendorPage && !captchaValid)
            {
                ModelState.AddModelError("", _captchaSettings.GetWrongCaptchaMessage(_localizationService));
            }

            var pictureId = 0;

            if (uploadedFile != null && !string.IsNullOrEmpty(uploadedFile.FileName))
            {
                try
                {
                    var contentType         = uploadedFile.ContentType;
                    var vendorPictureBinary = uploadedFile.GetPictureBits();
                    var picture             = _pictureService.InsertPicture(vendorPictureBinary, contentType, null);

                    if (picture != null)
                    {
                        pictureId = picture.Id;
                    }
                }
                catch (Exception)
                {
                    ModelState.AddModelError("", _localizationService.GetResource("Vendors.ApplyAccount.Picture.ErrorMessage"));
                }
            }

            //vendor attributes
            var vendorAttributesXml = ParseVendorAttributes(model.Form);

            _vendorAttributeParser.GetAttributeWarnings(vendorAttributesXml).ToList()
            .ForEach(warning => ModelState.AddModelError(string.Empty, warning));

            if (ModelState.IsValid)
            {
                var description = Core.Html.HtmlHelper.FormatText(model.Description, false, false, true, false, false, false);
                //disabled by default
                var vendor = new Vendor
                {
                    Name  = model.Name,
                    Email = model.Email,
                    //some default settings
                    PageSize = 6,
                    AllowCustomersToSelectPageSize = true,
                    PageSizeOptions = _vendorSettings.DefaultVendorPageSizeOptions,
                    PictureId       = pictureId,
                    Description     = description
                };
                _vendorService.InsertVendor(vendor);
                //search engine name (the same as vendor name)
                var seName = vendor.ValidateSeName(vendor.Name, vendor.Name, true);
                _urlRecordService.SaveSlug(vendor, seName, 0);

                //associate to the current customer
                //but a store owner will have to manually add this customer role to "Vendors" role
                //if he wants to grant access to admin area
                _workContext.CurrentCustomer.VendorId = vendor.Id;
                _customerService.UpdateCustomer(_workContext.CurrentCustomer);

                //update picture seo file name
                UpdatePictureSeoNames(vendor);

                //save vendor attributes
                _genericAttributeService.SaveAttribute(vendor, VendorAttributeNames.VendorAttributes, vendorAttributesXml);

                //notify store owner here (email)
                _workflowMessageService.SendNewVendorAccountApplyStoreOwnerNotification(_workContext.CurrentCustomer,
                                                                                        vendor, _localizationSettings.DefaultAdminLanguageId);

                model.DisableFormInput = true;
                model.Result           = _localizationService.GetResource("Vendors.ApplyAccount.Submitted");
                return(View(model));
            }

            //If we got this far, something failed, redisplay form
            model = _vendorModelFactory.PrepareApplyVendorModel(model, false, true, vendorAttributesXml);
            return(View(model));
        }
        public IActionResult PDTHandler(IFormCollection form)
        {
            var processor = _paymentService.LoadPaymentMethodBySystemName("Payments.MOLPay") as MOLPayPaymentProcessor;

            if (processor == null ||
                !processor.IsPaymentMethodActive(_paymentSettings) || !processor.PluginDescriptor.Installed)
            {
                throw new NopException("MOLPay module cannot be loaded");
            }

            var skey       = form["skey"];
            var tranID     = form["tranID"];
            var domain     = form["domain"];
            var status     = form["status"];
            var amount     = form["amount"];
            var currency   = form["currency"];
            var paydate    = form["paydate"];
            int orderid    = Int32.Parse(form["orderid"]);
            var appcode    = form["appcode"];
            var error_code = form["error_code"];
            var error_desc = form["error_desc"];
            var channel    = form["channel"];
            var vkey       = _molPayPaymentSettings.VerifyKey;
            var mc_gross   = decimal.Zero;

            try
            {
                mc_gross = decimal.Parse(form["mc_gross"], new CultureInfo("en-US"));
            }
            catch (Exception exc)
            {
                _logger.Error("MOLPay PDT. Error getting mc_gross", exc);
            }

            if (tranID != "")
            {
                var order = _orderService.GetOrderById(orderid);
                //if (order != null)
                //{

                var sb = new StringBuilder();
                sb.AppendLine("MOLPay PDT:");
                sb.AppendLine("tranID: " + tranID);
                sb.AppendLine("amount: " + amount);
                sb.AppendLine("currency: " + currency);
                sb.AppendLine("Pending reason: " + string.Empty);
                sb.AppendLine("paydate: " + paydate);
                sb.AppendLine("orderid: " + orderid);
                sb.AppendLine("channel: " + channel);

                var captured = _molPayPaymentSettings.CapturedMode;
                var failed   = _molPayPaymentSettings.FailedMode;
                var pending  = _molPayPaymentSettings.PendingMode;
                var result   = pending;
                switch (status)
                {
                case "00":
                    result = captured;
                    break;

                case "11":
                    result = failed;
                    break;

                case "22":
                    result = pending;
                    break;

                default:
                    break;
                }

                //var newPaymentStatus = MOLPayHelper.GetPaymentStatus(status);
                var newPaymentStatus = result;
                sb.AppendLine("New payment status: " + newPaymentStatus);

                //order note
                order.OrderNotes.Add(new OrderNote
                {
                    Note = sb.ToString(),
                    DisplayToCustomer = false,
                    CreatedOnUtc      = DateTime.UtcNow
                });
                _orderService.UpdateOrder(order);

                //validate order total
                var orderTotalSentToMOLPay = order.GetAttribute <decimal?>(MOLPayHelper.OrderTotalSentToMOLPay);
                if (orderTotalSentToMOLPay.HasValue && mc_gross != orderTotalSentToMOLPay.Value)
                {
                    var errorStr =
                        $"MOLPay PDT. Returned order total {mc_gross} doesn't equal order total {order.OrderTotal}. Order# {order.Id}.";
                    //log
                    _logger.Error(errorStr);
                    //order note
                    order.OrderNotes.Add(new OrderNote
                    {
                        Note = errorStr,
                        DisplayToCustomer = false,
                        CreatedOnUtc      = DateTime.UtcNow
                    });
                    _orderService.UpdateOrder(order);

                    return(RedirectToAction("Index", "Home", new { area = "" }));
                }

                //clear attribute
                if (orderTotalSentToMOLPay.HasValue)
                {
                    _genericAttributeService.SaveAttribute <decimal?>(order, MOLPayHelper.OrderTotalSentToMOLPay, null);
                }

                //mark order as paid
                if (newPaymentStatus == captured)
                {
                    if (_orderProcessingService.CanMarkOrderAsPaid(order))
                    {
                        order.AuthorizationTransactionId = tranID;
                        _orderService.UpdateOrder(order);

                        _orderProcessingService.MarkOrderAsPaid(order);
                    }
                }

                order.PaymentStatus = result;

                //if(order.PaymentStatus == PaymentStatus.Paid)
                //{
                //    order.PaymentStatus = _molPayPaymentSettings.CapturedMode;
                //}
                //else if (order.PaymentStatus == PaymentStatus.Pending)
                //{
                //    order.PaymentStatus = _molPayPaymentSettings.PendingMode;
                //}
                //else
                //{
                //    order.PaymentStatus = _molPayPaymentSettings.FailedMode;
                //}

                var key0 = md5encode(tranID + orderid + status + domain + amount + currency);
                var key1 = md5encode(paydate + domain + key0 + appcode + vkey);

                if (skey != key1)
                {
                    order.OrderNotes.Add(new OrderNote
                    {
                        Note = "Invalid Transaction.",
                        DisplayToCustomer = false,
                        CreatedOnUtc      = DateTime.UtcNow
                    });
                    _orderService.UpdateOrder(order);

                    return(RedirectToAction("Index", "Home", new { area = "" }));
                }
                else
                {
                    switch (status)
                    {
                    case "00":
                        order.OrderNotes.Add(new OrderNote
                        {
                            Note = "Captured.",
                            DisplayToCustomer = false,
                            CreatedOnUtc      = DateTime.UtcNow
                        });
                        _orderService.UpdateOrder(order);
                        return(RedirectToRoute("CheckoutCompleted", new { orderId = orderid }));

                    case "11":
                        order.OrderNotes.Add(new OrderNote
                        {
                            Note = "Failed.",
                            DisplayToCustomer = false,
                            CreatedOnUtc      = DateTime.UtcNow
                        });
                        _orderService.UpdateOrder(order);
                        return(RedirectToAction("Index", "Home", new { area = "" }));

                    case "22":
                        order.OrderNotes.Add(new OrderNote
                        {
                            Note = "Pending.",
                            DisplayToCustomer = false,
                            CreatedOnUtc      = DateTime.UtcNow
                        });
                        _orderService.UpdateOrder(order);
                        return(RedirectToAction("Index", "Home", new { area = "" }));
                    }
                }
            }

            return(RedirectToAction("Index", "Home", new { area = "" }));
        }
        public HttpResponseMessage Register(RegisterModel model)
        {
            var response = this.Request.CreateResponse(HttpStatusCode.OK);

            try
            {
                string jsonString = "";
                var    Sponsors   = _customerService.GetCustomerByUsername(model.SponsorsName);
                //check whether registration is allowed
                if (_customerSettings.UserRegistrationType == UserRegistrationType.Disabled)
                {
                    //Registrition Disable
                    //(int)UserRegistrationType.Disabled
                }

                var customer = _customerService.InsertGuestCustomer();
                if (customer.Id != 0)
                {
                    _workContext.CurrentCustomer = customer;
                }

                if (_customerSettings.UsernamesEnabled && model.Username != null)
                {
                    model.Username = model.Username.Trim();
                }
                customer.AffiliateId  = Sponsors.Id;
                customer.SponsorsName = model.SponsorsName;
                bool isApproved          = _customerSettings.UserRegistrationType == UserRegistrationType.Standard;
                var  registrationRequest = new CustomerRegistrationRequest(customer, model.Email,
                                                                           _customerSettings.UsernamesEnabled ? model.Username : model.Email, model.Password, _customerSettings.DefaultPasswordFormat, isApproved);
                var registrationResult = _customerRegistrationService.RegisterCustomer(registrationRequest);
                if (registrationResult.Success)
                {
                    // properties
                    if (_dateTimeSettings.AllowCustomersToSetTimeZone)
                    {
                        _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.TimeZoneId, model.TimeZoneId);
                    }

                    // form fields
                    if (_customerSettings.GenderEnabled)
                    {
                        _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.Gender, model.Gender);
                    }
                    _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.FirstName, model.FirstName);
                    _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.LastName, model.LastName);
                    if (_customerSettings.DateOfBirthEnabled)
                    {
                        DateTime?dateOfBirth = null;
                        try
                        {
                            dateOfBirth = new DateTime(model.DateOfBirthYear.Value, model.DateOfBirthMonth.Value, model.DateOfBirthDay.Value);
                        }
                        catch { }
                        _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.DateOfBirth, dateOfBirth);
                    }

                    if (_customerSettings.CountryEnabled)
                    {
                        _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.CountryId, model.CountryId);
                    }
                    if (_customerSettings.PhoneEnabled)
                    {
                        _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.Phone, model.Phone);
                    }
                    if (_customerSettings.CustomerNumberMethod == CustomerNumberMethod.AutomaticallySet && String.IsNullOrEmpty(customer.GetAttribute <string>(SystemCustomerAttributeNames.CustomerNumber)))
                    {
                        _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.CustomerNumber, customer.Id);
                    }

                    // Notifications
                    if (_customerSettings.NotifyNewCustomerRegistration)
                    {
                        Services.MessageFactory.SendCustomerRegisteredNotificationMessage(customer, _localizationSettings.DefaultAdminLanguageId);
                    }

                    Services.MessageFactory.SendCustomerWelcomeMessage(customer, _workContext.WorkingLanguage.Id);

                    if (_customerSettings.UserRegistrationType == UserRegistrationType.EmailValidation)
                    {
                        // email validation message
                        _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.AccountActivationToken, Guid.NewGuid().ToString());
                        Services.MessageFactory.SendCustomerEmailValidationMessage(customer, _workContext.WorkingLanguage.Id);
                        var subscription = new NewsLetterSubscription
                        {
                            NewsLetterSubscriptionGuid = Guid.NewGuid(),
                            Email        = customer.Email,
                            Active       = false,
                            CreatedOnUtc = DateTime.UtcNow,
                            StoreId      = _storeContext.CurrentStore.Id
                        };

                        _newsLetterSubscriptionService.InsertNewsLetterSubscription(subscription);
                        //return RedirectToRoute("RegisterResult", new { resultId = (int)UserRegistrationType.EmailValidation });
                        return(Request.CreateResponse(HttpStatusCode.OK, new { code = 1, Message = _localizationService.GetResource("Customer.VerifyEmail") }));
                    }
                    else if (_customerSettings.UserRegistrationType == UserRegistrationType.AdminApproval)
                    {
                        return(Request.CreateResponse(HttpStatusCode.OK, new { code = 0, Message = _localizationService.GetResource("Customer.AdminApproval") }));
                    }
                    else
                    {
                        return(Request.CreateResponse(HttpStatusCode.OK, new { code = 0, Message = "success", GUID = customer.CustomerGuid }));
                    }
                }
                else
                {
                    return(Request.CreateResponse(HttpStatusCode.OK, new { code = 0, Message = registrationResult.Errors[0] }));
                }
            }
            catch (Exception ex)
            {
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, new { code = 1, Message = "Something went wrong, Ex:" + ex.ToString() }));
            }
        }
Exemple #25
0
        public virtual async Task <IActionResult> Details(string courseId)
        {
            var customer = _workContext.CurrentCustomer;

            //Check whether the current user is a guest
            if (customer.IsGuest() && !_courseSettings.AllowGuestsToAccessCourse)
            {
                return(InvokeHttp404());
            }

            var course = await _courseViewModelService.GetCourseById(courseId);

            if (course == null)
            {
                return(InvokeHttp404());
            }

            //Check whether the current user has a "Manage course" permission
            //It allows him to preview a category before publishing
            if (!course.Published && !await _permissionService.Authorize(StandardPermissionProvider.ManageCourses, customer))
            {
                return(InvokeHttp404());
            }

            //Check whether the current user purchased the course
            if (!await _courseViewModelService.CheckOrder(course, customer) && !await _permissionService.Authorize(StandardPermissionProvider.ManageCourses, customer))
            {
                return(InvokeHttp404());
            }

            //ACL (access control list)
            if (!_aclService.Authorize(course, customer))
            {
                return(InvokeHttp404());
            }

            //Store mapping
            if (!_storeMappingService.Authorize(course))
            {
                return(InvokeHttp404());
            }

            //'Continue shopping' URL
            await _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.LastContinueShoppingPage, _webHelper.GetThisPageUrl(false), _storeContext.CurrentStore.Id);

            //display "edit" (manage) link
            if (await _permissionService.Authorize(StandardPermissionProvider.AccessAdminPanel, customer) && await _permissionService.Authorize(StandardPermissionProvider.ManageCourses, customer))
            {
                DisplayEditLink(Url.Action("Edit", "Course", new { id = course.Id, area = "Admin" }));
            }

            //activity log
            await _customerActivityService.InsertActivity("PublicStore.ViewCourse", course.Id, _localizationService.GetResource("ActivityLog.PublicStore.ViewCourse"), course.Name);

            await _customerActionEventService.Viewed(customer, this.HttpContext.Request.Path.ToString(), this.Request.Headers[HeaderNames.Referer].ToString() != null?Request.Headers["Referer"].ToString() : "");

            //model
            var model = await _courseViewModelService.PrepareCourseModel(course);

            return(View(model));
        }
Exemple #26
0
        public ActionResult Category(int categoryId, CatalogSearchQuery query)
        {
            var category = _categoryService.GetCategoryById(categoryId);

            if (category == null || category.Deleted)
            {
                return(HttpNotFound());
            }

            // Check whether the current user has a "Manage catalog" permission
            // It allows him to preview a category before publishing
            if (!category.Published && !_services.Permissions.Authorize(StandardPermissionProvider.ManageCatalog))
            {
                return(HttpNotFound());
            }

            // ACL (access control list)
            if (!_aclService.Authorize(category))
            {
                return(HttpNotFound());
            }

            // Store mapping
            if (!_storeMappingService.Authorize(category))
            {
                return(HttpNotFound());
            }

            // 'Continue shopping' URL
            if (!_services.WorkContext.CurrentCustomer.IsSystemAccount)
            {
                _genericAttributeService.SaveAttribute(_services.WorkContext.CurrentCustomer,
                                                       SystemCustomerAttributeNames.LastContinueShoppingPage,
                                                       _services.WebHelper.GetThisPageUrl(false),
                                                       _services.StoreContext.CurrentStore.Id);
            }

            var model = category.ToModel();

            _services.DisplayControl.Announce(category);

            // Category breadcrumb
            if (_catalogSettings.CategoryBreadcrumbEnabled)
            {
                _helper.GetCategoryBreadCrumb(category.Id, 0).Select(x => x.Value).Each(x => _breadcrumb.Track(x));
            }

            model.SubCategoryDisplayType = _catalogSettings.SubCategoryDisplayType;

            var customerRolesIds = _services.WorkContext.CurrentCustomer.CustomerRoles.Where(x => x.Active).Select(x => x.Id).ToList();
            var subCategories    = _categoryService.GetAllCategoriesByParentCategoryId(categoryId);
            int pictureSize      = _mediaSettings.CategoryThumbPictureSize;
            var allPictureInfos  = _pictureService.GetPictureInfos(subCategories.Select(x => x.PictureId.GetValueOrDefault()));
            var fallbackType     = _catalogSettings.HideCategoryDefaultPictures ? FallbackPictureType.NoFallback : FallbackPictureType.Entity;

            // subcategories
            model.SubCategories = subCategories
                                  .Select(x =>
            {
                var subCatName  = x.GetLocalized(y => y.Name);
                var subCatModel = new CategoryModel.SubCategoryModel
                {
                    Id     = x.Id,
                    Name   = subCatName,
                    SeName = x.GetSeName(),
                };

                _services.DisplayControl.Announce(x);

                // prepare picture model
                var pictureInfo = allPictureInfos.Get(x.PictureId.GetValueOrDefault());

                subCatModel.PictureModel = new PictureModel
                {
                    PictureId           = pictureInfo?.Id ?? 0,
                    Size                = pictureSize,
                    ImageUrl            = _pictureService.GetUrl(pictureInfo, pictureSize, fallbackType),
                    FullSizeImageUrl    = _pictureService.GetUrl(pictureInfo, 0, FallbackPictureType.NoFallback),
                    FullSizeImageWidth  = pictureInfo?.Width,
                    FullSizeImageHeight = pictureInfo?.Height,
                    Title               = string.Format(T("Media.Category.ImageLinkTitleFormat"), subCatName),
                    AlternateText       = string.Format(T("Media.Category.ImageAlternateTextFormat"), subCatName)
                };

                return(subCatModel);
            })
                                  .ToList();

            // Featured Products
            if (!_catalogSettings.IgnoreFeaturedProducts)
            {
                CatalogSearchResult featuredProductsResult = null;

                string cacheKey = ModelCacheEventConsumer.CATEGORY_HAS_FEATURED_PRODUCTS_KEY.FormatInvariant(categoryId, string.Join(",", customerRolesIds), _services.StoreContext.CurrentStore.Id);
                var    hasFeaturedProductsCache = _services.Cache.Get <bool?>(cacheKey);

                var featuredProductsQuery = new CatalogSearchQuery()
                                            .VisibleOnly(_services.WorkContext.CurrentCustomer)
                                            .VisibleIndividuallyOnly(true)
                                            .WithCategoryIds(true, categoryId)
                                            .HasStoreId(_services.StoreContext.CurrentStore.Id)
                                            .WithLanguage(_services.WorkContext.WorkingLanguage)
                                            .WithCurrency(_services.WorkContext.WorkingCurrency);

                if (!hasFeaturedProductsCache.HasValue)
                {
                    featuredProductsResult   = _catalogSearchService.Search(featuredProductsQuery);
                    hasFeaturedProductsCache = featuredProductsResult.TotalHitsCount > 0;
                    _services.Cache.Put(cacheKey, hasFeaturedProductsCache, TimeSpan.FromHours(6));
                }

                if (hasFeaturedProductsCache.Value && featuredProductsResult == null)
                {
                    featuredProductsResult = _catalogSearchService.Search(featuredProductsQuery);
                }

                if (featuredProductsResult != null)
                {
                    var featuredProductsmappingSettings = _helper.GetBestFitProductSummaryMappingSettings(ProductSummaryViewMode.Grid);
                    model.FeaturedProducts = _helper.MapProductSummaryModel(featuredProductsResult.Hits, featuredProductsmappingSettings);
                }
            }

            // Products
            int[] catIds = new int[] { categoryId };
            if (_catalogSettings.ShowProductsFromSubcategories)
            {
                // Include subcategories
                catIds = catIds.Concat(_helper.GetChildCategoryIds(categoryId)).ToArray();
            }

            query.WithCategoryIds(_catalogSettings.IncludeFeaturedProductsInNormalLists ? (bool?)null : false, catIds);

            var searchResult = _catalogSearchService.Search(query);

            model.SearchResult = searchResult;

            var mappingSettings = _helper.GetBestFitProductSummaryMappingSettings(query.GetViewMode());

            model.Products = _helper.MapProductSummaryModel(searchResult.Hits, mappingSettings);

            // Prepare paging/sorting/mode stuff
            _helper.MapListActions(model.Products, category, _catalogSettings.DefaultPageSizeOptions);

            // template
            var templateCacheKey = string.Format(ModelCacheEventConsumer.CATEGORY_TEMPLATE_MODEL_KEY, category.CategoryTemplateId);
            var templateViewPath = _services.Cache.Get(templateCacheKey, () =>
            {
                var template = _categoryTemplateService.GetCategoryTemplateById(category.CategoryTemplateId);
                if (template == null)
                {
                    template = _categoryTemplateService.GetAllCategoryTemplates().FirstOrDefault();
                }
                return(template.ViewPath);
            });

            // Activity log
            _services.CustomerActivity.InsertActivity("PublicStore.ViewCategory", T("ActivityLog.PublicStore.ViewCategory"), category.Name);

            return(View(templateViewPath, model));
        }
        public virtual AuthorizationResult Authorize(OpenAuthenticationParameters parameters)
        {
            var userFound = _openAuthenticationService.GetUser(parameters);

            var userLoggedIn = _workContext.CurrentCustomer.IsRegistered() ? _workContext.CurrentCustomer : null;

            if (AccountAlreadyExists(userFound, userLoggedIn))
            {
                if (AccountIsAssignedToLoggedOnAccount(userFound, userLoggedIn))
                {
                    // The person is trying to log in as himself.. bit weird
                    return(new AuthorizationResult(OpenAuthenticationStatus.Authenticated));
                }

                var result = new AuthorizationResult(OpenAuthenticationStatus.Error);
                result.AddError("Account is already assigned");
                return(result);
            }
            if (AccountDoesNotExistAndUserIsNotLoggedOn(userFound, userLoggedIn))
            {
                ExternalAuthorizerHelper.StoreParametersForRoundTrip(parameters);

                if (AutoRegistrationIsEnabled())
                {
                    #region Register user

                    var currentCustomer = _workContext.CurrentCustomer;
                    var details         = new RegistrationDetails(parameters);
                    var randomPassword  = CommonHelper.GenerateRandomDigitCode(20);


                    bool isApproved          = _customerSettings.UserRegistrationType == UserRegistrationType.Standard;
                    var  registrationRequest = new CustomerRegistrationRequest(currentCustomer, details.EmailAddress,
                                                                               _customerSettings.UsernamesEnabled ? details.UserName : details.EmailAddress, randomPassword, PasswordFormat.Clear, isApproved);
                    var registrationResult = _customerRegistrationService.RegisterCustomer(registrationRequest);
                    if (registrationResult.Success)
                    {
                        //store other parameters (form fields)
                        if (!String.IsNullOrEmpty(details.FirstName))
                        {
                            _genericAttributeService.SaveAttribute(currentCustomer, SystemCustomerAttributeNames.FirstName, details.FirstName);
                        }
                        if (!String.IsNullOrEmpty(details.LastName))
                        {
                            _genericAttributeService.SaveAttribute(currentCustomer, SystemCustomerAttributeNames.LastName, details.LastName);
                        }


                        userFound = currentCustomer;
                        _openAuthenticationService.AssociateExternalAccountWithUser(currentCustomer, parameters);
                        ExternalAuthorizerHelper.RemoveParameters();

                        //code below is copied from CustomerController.Register method

                        //authenticate
                        if (isApproved)
                        {
                            _authenticationService.SignIn(userFound ?? userLoggedIn, false);
                        }

                        //notifications
                        if (_customerSettings.NotifyNewCustomerRegistration)
                        {
                            _workflowMessageService.SendCustomerRegisteredNotificationMessage(currentCustomer, _localizationSettings.DefaultAdminLanguageId);
                        }

                        switch (_customerSettings.UserRegistrationType)
                        {
                        case UserRegistrationType.EmailValidation:
                        {
                            //email validation message
                            _genericAttributeService.SaveAttribute(currentCustomer, SystemCustomerAttributeNames.AccountActivationToken, Guid.NewGuid().ToString());
                            _workflowMessageService.SendCustomerEmailValidationMessage(currentCustomer, _workContext.WorkingLanguage.Id);

                            //result
                            return(new AuthorizationResult(OpenAuthenticationStatus.AutoRegisteredEmailValidation));
                        }

                        case UserRegistrationType.AdminApproval:
                        {
                            //result
                            return(new AuthorizationResult(OpenAuthenticationStatus.AutoRegisteredAdminApproval));
                        }

                        case UserRegistrationType.Standard:
                        {
                            //send customer welcome message
                            _workflowMessageService.SendCustomerWelcomeMessage(currentCustomer, _workContext.WorkingLanguage.Id);

                            //result
                            return(new AuthorizationResult(OpenAuthenticationStatus.AutoRegisteredStandard));
                        }

                        default:
                            break;
                        }
                    }
                    else
                    {
                        ExternalAuthorizerHelper.RemoveParameters();

                        var result = new AuthorizationResult(OpenAuthenticationStatus.Error);
                        foreach (var error in registrationResult.Errors)
                        {
                            result.AddError(string.Format(error));
                        }
                        return(result);
                    }

                    #endregion
                }
                else if (RegistrationIsEnabled())
                {
                    return(new AuthorizationResult(OpenAuthenticationStatus.AssociateOnLogon));
                }
                else
                {
                    ExternalAuthorizerHelper.RemoveParameters();

                    var result = new AuthorizationResult(OpenAuthenticationStatus.Error);
                    result.AddError("Registration is disabled");
                    return(result);
                }
            }
            if (userFound == null)
            {
                _openAuthenticationService.AssociateExternalAccountWithUser(userLoggedIn, parameters);
            }

            //migrate shopping cart
            _shoppingCartService.MigrateShoppingCart(_workContext.CurrentCustomer, userFound ?? userLoggedIn);
            //authenticate
            _authenticationService.SignIn(userFound ?? userLoggedIn, false);
            //activity log
            _customerActivityService.InsertActivity("PublicStore.Login", _localizationService.GetResource("ActivityLog.PublicStore.Login"),
                                                    userFound ?? userLoggedIn);

            return(new AuthorizationResult(OpenAuthenticationStatus.Authenticated));
        }
        /// <summary>
        /// Prepare shipping method model
        /// </summary>
        /// <param name="cart">Cart</param>
        /// <param name="shippingAddress">Shipping address</param>
        /// <returns>Shipping method model</returns>
        public virtual CheckoutShippingMethodModel PrepareShippingMethodModel(IList <ShoppingCartItem> cart, Address shippingAddress)
        {
            var model = new CheckoutShippingMethodModel();

            var getShippingOptionResponse = _shippingService.GetShippingOptions(cart, shippingAddress, _workContext.CurrentCustomer, storeId: _storeContext.CurrentStore.Id);

            if (getShippingOptionResponse.Success)
            {
                //performance optimization. cache returned shipping options.
                //we'll use them later (after a customer has selected an option).
                _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer,
                                                       SystemCustomerAttributeNames.OfferedShippingOptions,
                                                       getShippingOptionResponse.ShippingOptions,
                                                       _storeContext.CurrentStore.Id);

                foreach (var shippingOption in getShippingOptionResponse.ShippingOptions)
                {
                    var soModel = new CheckoutShippingMethodModel.ShippingMethodModel
                    {
                        Name        = shippingOption.Name,
                        Description = shippingOption.Description,
                        ShippingRateComputationMethodSystemName = shippingOption.ShippingRateComputationMethodSystemName,
                        ShippingOption = shippingOption,
                    };

                    //adjust rate
                    var shippingTotal = _orderTotalCalculationService.AdjustShippingRate(shippingOption.Rate, cart, out List <DiscountForCaching> _);

                    var rateBase = _taxService.GetShippingPrice(shippingTotal, _workContext.CurrentCustomer);
                    var rate     = _currencyService.ConvertFromPrimaryStoreCurrency(rateBase, _workContext.WorkingCurrency);
                    soModel.Fee = _priceFormatter.FormatShippingPrice(rate, true);

                    model.ShippingMethods.Add(soModel);
                }

                //find a selected (previously) shipping method
                var selectedShippingOption = _workContext.CurrentCustomer.GetAttribute <ShippingOption>(
                    SystemCustomerAttributeNames.SelectedShippingOption, _storeContext.CurrentStore.Id);
                if (selectedShippingOption != null)
                {
                    var shippingOptionToSelect = model.ShippingMethods.ToList()
                                                 .Find(so =>
                                                       !string.IsNullOrEmpty(so.Name) &&
                                                       so.Name.Equals(selectedShippingOption.Name, StringComparison.InvariantCultureIgnoreCase) &&
                                                       !string.IsNullOrEmpty(so.ShippingRateComputationMethodSystemName) &&
                                                       so.ShippingRateComputationMethodSystemName.Equals(selectedShippingOption.ShippingRateComputationMethodSystemName, StringComparison.InvariantCultureIgnoreCase));
                    if (shippingOptionToSelect != null)
                    {
                        shippingOptionToSelect.Selected = true;
                    }
                }
                //if no option has been selected, let's do it for the first one
                if (model.ShippingMethods.FirstOrDefault(so => so.Selected) == null)
                {
                    var shippingOptionToSelect = model.ShippingMethods.FirstOrDefault();
                    if (shippingOptionToSelect != null)
                    {
                        shippingOptionToSelect.Selected = true;
                    }
                }

                //notify about shipping from multiple locations
                if (_shippingSettings.NotifyCustomerAboutShippingFromMultipleLocations)
                {
                    model.NotifyCustomerAboutShippingFromMultipleLocations = getShippingOptionResponse.ShippingFromMultipleLocations;
                }
            }
            else
            {
                foreach (var error in getShippingOptionResponse.Errors)
                {
                    model.Warnings.Add(error);
                }
            }

            return(model);
        }
        public IActionResult PDTHandler()
        {
            var tx = _webHelper.QueryString <string>("tx");

            if (!(_paymentPluginManager.LoadPluginBySystemName("Payments.PayPalStandard") is IngenicoPaymentProcessor processor) || !_paymentPluginManager.IsPluginActive(processor))
            {
                throw new NopException("PayPal Standard module cannot be loaded");
            }

            if (processor.GetPdtDetails(tx, out var values, out var response))
            {
                values.TryGetValue("custom", out var orderNumber);
                var orderNumberGuid = Guid.Empty;
                try
                {
                    orderNumberGuid = new Guid(orderNumber);
                }
                catch
                {
                    // ignored
                }

                var order = _orderService.GetOrderByGuid(orderNumberGuid);

                if (order == null)
                {
                    return(RedirectToAction("Index", "Home", new { area = string.Empty }));
                }

                var mcGross = decimal.Zero;

                try
                {
                    mcGross = decimal.Parse(values["mc_gross"], new CultureInfo("en-US"));
                }
                catch (Exception exc)
                {
                    _logger.Error("PayPal PDT. Error getting mc_gross", exc);
                }

                values.TryGetValue("payer_status", out var payerStatus);
                values.TryGetValue("payment_status", out var paymentStatus);
                values.TryGetValue("pending_reason", out var pendingReason);
                values.TryGetValue("mc_currency", out var mcCurrency);
                values.TryGetValue("txn_id", out var txnId);
                values.TryGetValue("payment_type", out var paymentType);
                values.TryGetValue("payer_id", out var payerId);
                values.TryGetValue("receiver_id", out var receiverId);
                values.TryGetValue("invoice", out var invoice);
                values.TryGetValue("payment_fee", out var paymentFee);

                var sb = new StringBuilder();
                sb.AppendLine("PayPal PDT:");
                sb.AppendLine("mc_gross: " + mcGross);
                sb.AppendLine("Payer status: " + payerStatus);
                sb.AppendLine("Payment status: " + paymentStatus);
                sb.AppendLine("Pending reason: " + pendingReason);
                sb.AppendLine("mc_currency: " + mcCurrency);
                sb.AppendLine("txn_id: " + txnId);
                sb.AppendLine("payment_type: " + paymentType);
                sb.AppendLine("payer_id: " + payerId);
                sb.AppendLine("receiver_id: " + receiverId);
                sb.AppendLine("invoice: " + invoice);
                sb.AppendLine("payment_fee: " + paymentFee);

                var newPaymentStatus = IngenicoHelper.GetPaymentStatus(paymentStatus, string.Empty);
                sb.AppendLine("New payment status: " + newPaymentStatus);

                //order note
                order.OrderNotes.Add(new OrderNote
                {
                    Note = sb.ToString(),
                    DisplayToCustomer = false,
                    CreatedOnUtc      = DateTime.UtcNow
                });
                _orderService.UpdateOrder(order);

                //validate order total
                var orderTotalSentToPayPal = _genericAttributeService.GetAttribute <decimal?>(order, IngenicoHelper.OrderTotalSentToPayPal);
                if (orderTotalSentToPayPal.HasValue && mcGross != orderTotalSentToPayPal.Value)
                {
                    var errorStr = $"PayPal PDT. Returned order total {mcGross} doesn't equal order total {order.OrderTotal}. Order# {order.Id}.";
                    //log
                    _logger.Error(errorStr);
                    //order note
                    order.OrderNotes.Add(new OrderNote
                    {
                        Note = errorStr,
                        DisplayToCustomer = false,
                        CreatedOnUtc      = DateTime.UtcNow
                    });
                    _orderService.UpdateOrder(order);

                    return(RedirectToAction("Index", "Home", new { area = string.Empty }));
                }

                //clear attribute
                if (orderTotalSentToPayPal.HasValue)
                {
                    _genericAttributeService.SaveAttribute <decimal?>(order, IngenicoHelper.OrderTotalSentToPayPal, null);
                }

                if (newPaymentStatus != PaymentStatus.Paid)
                {
                    return(RedirectToRoute("CheckoutCompleted", new { orderId = order.Id }));
                }

                if (!_orderProcessingService.CanMarkOrderAsPaid(order))
                {
                    return(RedirectToRoute("CheckoutCompleted", new { orderId = order.Id }));
                }

                //mark order as paid
                order.AuthorizationTransactionId = txnId;
                _orderService.UpdateOrder(order);
                _orderProcessingService.MarkOrderAsPaid(order);

                return(RedirectToRoute("CheckoutCompleted", new { orderId = order.Id }));
            }
        public IList <string> ValidateShippingForm(IFormCollection form)
        {
            var shippingMethodName = form["shippingoption"].ToString().Replace("___", "_").Split(new[] { '_' })[0];
            var shippingOptionId   = form["selectedShippingOption"].ToString();

            if (string.IsNullOrEmpty(shippingOptionId))
            {
                return new List <string>()
                       {
                           _localizationService.GetResource("Plugins.Shipping.ShippingPoint.SelectBeforeProceed")
                       }
            }
            ;

            if (shippingMethodName != _localizationService.GetResource("Plugins.Shipping.ShippingPoint.PluginName"))
            {
                throw new ArgumentException("shippingMethodName");
            }

            var chosenShippingOption = _shippingPointService.GetStoreShippingPointById(shippingOptionId);

            if (chosenShippingOption == null)
            {
                return new List <string>()
                       {
                           _localizationService.GetResource("Plugins.Shipping.ShippingPoint.SelectBeforeProceed")
                       }
            }
            ;

            //override price
            var offeredShippingOptions = _workContext.CurrentCustomer.GetAttribute <List <ShippingOption> >(SystemCustomerAttributeNames.OfferedShippingOptions, _storeContext.CurrentStore.Id);

            offeredShippingOptions.Find(x => x.Name == shippingMethodName).Rate = chosenShippingOption.PickupFee;

            _genericAttributeService.SaveAttribute(
                _workContext.CurrentCustomer,
                SystemCustomerAttributeNames.OfferedShippingOptions,
                offeredShippingOptions,
                _storeContext.CurrentStore.Id);

            var forCustomer =
                string.Format("<strong>{0}:</strong> {1}<br><strong>{2}:</strong> {3}<br>",
                              _localizationService.GetResource("Plugins.Shipping.ShippingPoint.Fields.ShippingPointName"), chosenShippingOption.ShippingPointName,
                              _localizationService.GetResource("Plugins.Shipping.ShippingPoint.Fields.Description"), chosenShippingOption.Description
                              );

            _genericAttributeService.SaveAttribute(
                _workContext.CurrentCustomer,
                SystemCustomerAttributeNames.ShippingOptionAttributeDescription,
                forCustomer,
                _storeContext.CurrentStore.Id);

            var serializedObject = new Domain.ShippingPointSerializable()
            {
                Id = chosenShippingOption.Id,
                ShippingPointName = chosenShippingOption.ShippingPointName,
                Description       = chosenShippingOption.Description,
                OpeningHours      = chosenShippingOption.OpeningHours,
                PickupFee         = chosenShippingOption.PickupFee,
                Country           = _countryService.GetCountryById(chosenShippingOption.CountryId)?.Name,
                City          = chosenShippingOption.City,
                Address1      = chosenShippingOption.Address1,
                ZipPostalCode = chosenShippingOption.ZipPostalCode,
                StoreId       = chosenShippingOption.StoreId,
            };

            var    stringBuilder = new StringBuilder();
            string serializedAttribute;

            using (var tw = new StringWriter(stringBuilder))
            {
                var xmlS = new XmlSerializer(typeof(Domain.ShippingPointSerializable));

                xmlS.Serialize(tw, serializedObject);
                serializedAttribute = stringBuilder.ToString();
            }

            _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer,
                                                   SystemCustomerAttributeNames.ShippingOptionAttributeXml,
                                                   serializedAttribute,
                                                   _storeContext.CurrentStore.Id);

            return(new List <string>());
        }
Exemple #31
0
        public IActionResult CreateUpdateCustomer(int customerId, string worldpayCustomerId)
        {
            //whether user has the authority
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageCustomers))
            {
                return(AccessDeniedView());
            }

            //check whether customer exists
            var customer = _customerService.GetCustomerById(customerId);

            if (customer == null)
            {
                throw new ArgumentException("No customer found with the specified id", nameof(customerId));
            }

            if (!ModelState.IsValid)
            {
                return(Json(new DataSourceResult {
                    Errors = ModelState.SerializeErrors()
                }));
            }

            //ensure that customer identifier not exceed 25 characters
            if ((worldpayCustomerId?.Length ?? 0) > 25)
            {
                throw new NopException("Worldpay Vault error: Customer ID must not exceed 25 characters");
            }

            //create request parameters to store a customer in Vault
            var createCustomerRequest = new CreateCustomerRequest
            {
                CustomerId = worldpayCustomerId,
                CustomerDuplicateCheckType = CustomerDuplicateCheckType.Error,
                EmailReceiptEnabled        = !string.IsNullOrEmpty(customer.Email),
                Email          = customer.Email,
                FirstName      = customer.GetAttribute <string>(SystemCustomerAttributeNames.FirstName),
                LastName       = customer.GetAttribute <string>(SystemCustomerAttributeNames.LastName),
                Company        = customer.GetAttribute <string>(SystemCustomerAttributeNames.Company),
                Phone          = customer.GetAttribute <string>(SystemCustomerAttributeNames.Phone),
                BillingAddress = new Address
                {
                    Line1   = customer.BillingAddress?.Address1,
                    City    = customer.BillingAddress?.City,
                    State   = customer.BillingAddress?.StateProvince?.Abbreviation,
                    Country = customer.BillingAddress?.Country?.TwoLetterIsoCode,
                    Zip     = customer.BillingAddress?.ZipPostalCode,
                    Company = customer.BillingAddress?.Company,
                    Phone   = customer.BillingAddress?.PhoneNumber
                }
            };

            //check whether customer is already stored in the Vault and try to store, if it is not so
            var vaultCustomer = _worldpayPaymentManager.GetCustomer(customer.GetAttribute <string>(WorldpayPaymentDefaults.CustomerIdAttribute))
                                ?? _worldpayPaymentManager.CreateCustomer(createCustomerRequest);

            if (vaultCustomer == null)
            {
                throw new NopException("Worldpay Vault error: Failed to create customer. Error details in the log");
            }

            //save Vault customer identifier as a generic attribute
            _genericAttributeService.SaveAttribute(customer, WorldpayPaymentDefaults.CustomerIdAttribute, vaultCustomer.CustomerId);

            //selected tab
            SaveSelectedTabName();

            return(Json(new { Result = true }));
        }