public void Can_get_storeLocation_without_ssl() { var serverVariables = new NameValueCollection(); serverVariables.Add("HTTP_HOST", "www.example.com"); _httpContext = new FakeHttpContext("~/", "GET", null, null, null, null, null, serverVariables); _webHelper = new WebHelper(_httpContext); _webHelper.GetStoreLocation(false).ShouldEqual("http://www.example.com/"); }
public void Get_storeLocation_should_return_lowerCased_result() { var serverVariables = new NameValueCollection(); serverVariables.Add("HTTP_HOST", "www.Example.com"); _httpContext = new FakeHttpContext("~/", "GET", null, null, null, null, null, serverVariables); _webHelper = new WebHelper(_httpContext); _webHelper.GetStoreLocation(false).ShouldEqual("http://www.example.com/"); }
public void Can_get_storeLocation_in_virtual_directory() { var serverVariables = new NameValueCollection(); serverVariables.Add("HTTP_HOST", "www.example.com"); _httpContext = new FakeHttpContext("~/SmartStoreNETpath", "GET", null, null, null, null, null, serverVariables); _webHelper = new WebHelper(_httpContext); _webHelper.GetStoreLocation(false).ShouldEqual("http://www.example.com/smartstorenetpath/"); }
/// <summary> /// Trả về đường dẫn file logo của plugin ( qui ước đó là file "logo.jpg" nằm trong thư mục gốc của plugin ) /// </summary> public static string GetLogoUrl(this PluginDescriptor pluginDescriptor, IWebHelper webHelper) { if (pluginDescriptor == null) throw new ArgumentNullException("pluginDescriptor"); if (webHelper == null) throw new ArgumentNullException("webHelper"); if (pluginDescriptor.OriginalAssemblyFile == null || pluginDescriptor.OriginalAssemblyFile.Directory == null) return null; var pluginDirectory = pluginDescriptor.OriginalAssemblyFile.Directory; string logoLocalPath = Path.Combine(pluginDirectory.FullName, "logo.jpg"); if(!File.Exists(logoLocalPath)) return null; return string.Format("{0}plugins/{1}/logo.jpg", webHelper.GetStoreLocation(), pluginDirectory.Name); }
/// <summary> /// Generate affilaite URL /// </summary> /// <param name="affiliate">Affiliate</param> /// <param name="webHelper">Web helper</param> /// <returns>Generated affilaite URL</returns> public static string GenerateUrl(this Affiliate affiliate, IWebHelper webHelper = null) { if (webHelper == null) webHelper = EngineContext.Current.Resolve<IWebHelper>(); string storeUrl = webHelper.GetStoreLocation(false); if (!string.IsNullOrWhiteSpace(affiliate.FriendlyUrlName)) storeUrl = webHelper.ModifyQueryString(storeUrl, string.Format("{0}={1}", Affiliate.AFFILIATE_FRIENDLYURLNAME_QUERY_PARAMETER_NAME, affiliate.FriendlyUrlName), null); else storeUrl = webHelper.ModifyQueryString(storeUrl, string.Format("{0}={1}", Affiliate.AFFILIATE_ID_QUERY_PARAMETER_NAME, affiliate.Id), null); return storeUrl; }
/// <summary> /// Generate affilaite URL /// </summary> /// <param name="affiliate">Affiliate</param> /// <param name="webHelper">Web helper</param> /// <returns>Generated affilaite URL</returns> public static string GenerateUrl(this Affiliate affiliate, IWebHelper webHelper) { if (affiliate == null) throw new ArgumentNullException("affiliate"); if (webHelper == null) throw new ArgumentNullException("webHelper"); var storeUrl = webHelper.GetStoreLocation(false); var url = !String.IsNullOrEmpty(affiliate.FriendlyUrlName) ? //use friendly URL webHelper.ModifyQueryString(storeUrl, "affiliate=" + affiliate.FriendlyUrlName, null): //use ID webHelper.ModifyQueryString(storeUrl, "affiliateid=" + affiliate.Id, null); return url; }
public static string GetLogoUrl(this PluginDescriptor pluginDescriptor, IWebHelper webHelper) { if (pluginDescriptor == null) throw new ArgumentNullException("pluginDescriptor"); if (webHelper == null) throw new ArgumentNullException("webHelper"); if (pluginDescriptor.OriginalAssemblyFile == null || pluginDescriptor.OriginalAssemblyFile.Directory == null) { return null; } var pluginDirectory = pluginDescriptor.OriginalAssemblyFile.Directory; var logoExtension = SupportedLogoImageExtensions.FirstOrDefault(ext => File.Exists(Path.Combine(pluginDirectory.FullName, "logo." + ext))); if (string.IsNullOrWhiteSpace(logoExtension)) return null; //No logo file was found with any of the supported extensions. string logoUrl = string.Format("{0}plugins/{1}/logo.{2}", webHelper.GetStoreLocation(), pluginDirectory.Name, logoExtension); return logoUrl; }
/// <summary> /// Generate a feed /// </summary> /// <param name="stream">Stream</param> /// <returns>Generated feed</returns> public void GenerateFeed(Stream stream) { using (var writer = new StreamWriter(stream)) { writer.WriteLine("UPC;Mfr Part #;Manufacturer;Product URL;Image URL;Product Title;Product Description;Category;Price;Condition;Stock Status"); foreach (var p in _productService.GetAllProducts(false)) { foreach (var pv in _productService.GetProductVariantsByProductId(p.Id, false)) { string sku = pv.Id.ToString("000000000000"); var productManufacturers = _manufacturerService.GetProductManufacturersByProductId(p.Id, false); string manufacturerName = productManufacturers.Count > 0 ? productManufacturers[0].Manufacturer.Name : String.Empty; string manufacturerPartNumber = pv.ManufacturerPartNumber; string productTitle = pv.FullProductName; //TODO add a method for getting product URL (e.g. SEOHelper.GetProductUrl) var productUrl = string.Format("{0}p/{1}/{2}", _webHelper.GetStoreLocation(false), p.Id, p.GetSeName()); string imageUrl = string.Empty; var pictures = _pictureService.GetPicturesByProductId(p.Id, 1); //always use HTTP when getting image URL if (pictures.Count > 0) { imageUrl = _pictureService.GetPictureUrl(pictures[0], _becomeSettings.ProductPictureSize, useSsl: false); } else { imageUrl = _pictureService.GetDefaultPictureUrl(_becomeSettings.ProductPictureSize, useSsl: false); } string description = pv.Description; var currency = GetUsedCurrency(); string price = _currencyService.ConvertFromPrimaryStoreCurrency(pv.Price, currency).ToString(new CultureInfo("en-US", false).NumberFormat); string stockStatus = pv.StockQuantity > 0 ? "In Stock" : "Out of Stock"; string category = "no category"; if (String.IsNullOrEmpty(description)) { description = p.FullDescription; } if (String.IsNullOrEmpty(description)) { description = p.ShortDescription; } if (String.IsNullOrEmpty(description)) { description = p.Name; } var productCategories = _categoryService.GetProductCategoriesByProductId(p.Id); if (productCategories.Count > 0) { var firstCategory = productCategories[0].Category; if (firstCategory != null) { var sb = new StringBuilder(); foreach (var cat in GetCategoryBreadCrumb(firstCategory)) { sb.AppendFormat("{0}>", cat.Name); } sb.Length -= 1; category = sb.ToString(); } } productTitle = CommonHelper.EnsureMaximumLength(productTitle, 80); productTitle = RemoveSpecChars(productTitle); manufacturerPartNumber = RemoveSpecChars(manufacturerPartNumber); manufacturerName = RemoveSpecChars(manufacturerName); description = HtmlHelper.StripTags(description); description = CommonHelper.EnsureMaximumLength(description, 250); description = RemoveSpecChars(description); category = RemoveSpecChars(category); writer.WriteLine("{0};{1};{2};{3};{4};{5};{6};{7};{8};New;{9}", sku, manufacturerPartNumber, manufacturerName, productUrl, imageUrl, productTitle, description, category, price, stockStatus); } } } }
public void Can_get_storeLocation_without_ssl() { _webHelper.GetStoreLocation(false).ShouldEqual("http://www.Example.com/"); }
/// <summary> /// Gets a configuration page URL /// </summary> public override string GetConfigurationPageUrl() { return($"{_webHelper.GetStoreLocation()}Admin/OAuth2Authentication/Configure"); }
protected void PrepareAffiliateModel(AffiliateModel model, Affiliate affiliate, bool excludeProperties) { if (model == null) { throw new ArgumentNullException("model"); } if (affiliate != null) { model.Id = affiliate.Id; model.Url = _webHelper.ModifyQueryString(_webHelper.GetStoreLocation(false), "affiliateid=" + affiliate.Id, null); if (!excludeProperties) { model.Active = affiliate.Active; model.Address = affiliate.Address.ToModel(_addressService); } } model.Address.FirstNameEnabled = true; model.Address.FirstNameRequired = true; model.Address.LastNameEnabled = true; model.Address.LastNameRequired = true; model.Address.EmailEnabled = true; model.Address.EmailRequired = true; model.Address.CompanyEnabled = true; model.Address.CountryEnabled = true; model.Address.StateProvinceEnabled = true; model.Address.CityEnabled = true; model.Address.CityRequired = true; model.Address.StreetAddressEnabled = true; model.Address.StreetAddressRequired = true; model.Address.StreetAddress2Enabled = true; model.Address.ZipPostalCodeEnabled = true; model.Address.ZipPostalCodeRequired = true; model.Address.PhoneEnabled = true; model.Address.PhoneRequired = true; model.Address.FaxEnabled = true; model.GridPageSize = _adminAreaSettings.GridPageSize; model.UsernamesEnabled = _customerSettings.UsernamesEnabled; //address //model.Address.AvailableCountries.Add(new SelectListItem() { Text = _localizationService.GetResource("Admin.Address.SelectCountry"), Value = "0" }); foreach (var c in _countryService.GetAllCountries(true)) { model.Address.AvailableCountries.Add(new SelectListItem() { Text = c.Name, Value = c.Id.ToString(), Selected = (affiliate != null && c.Id == affiliate.Address.CountryId) }); } var states = model.Address.CountryId.HasValue ? _stateProvinceService.GetStateProvincesByCountryId(model.Address.CountryId.Value, true).ToList() : new List <StateProvince>(); if (states.Count > 0) { foreach (var s in states) { model.Address.AvailableStates.Add(new SelectListItem() { Text = s.Name, Value = s.Id.ToString(), Selected = (affiliate != null && s.Id == affiliate.Address.StateProvinceId) }); } } else { model.Address.AvailableStates.Add(new SelectListItem() { Text = _localizationService.GetResource("Admin.Address.OtherNonUS"), Value = "0" }); } }
/// <summary> /// Formats attributes /// </summary> /// <param name="attributesXml">Attributes in XML format</param> /// <param name="customer">Customer</param> /// <param name="separator">Separator</param> /// <param name="htmlEncode">A value indicating whether to encode (HTML) values</param> /// <param name="renderPrices">A value indicating whether to render prices</param> /// <param name="allowHyperlinks">A value indicating whether to HTML hyperlink tags could be rendered (if required)</param> /// <returns>Attributes</returns> public virtual string FormatAttributes(string attributesXml, Customer customer, string separator = "<br />", bool htmlEncode = true, bool renderPrices = true, bool allowHyperlinks = true) { var result = new StringBuilder(); var attributes = _checkoutAttributeParser.ParseCheckoutAttributes(attributesXml); for (var i = 0; i < attributes.Count; i++) { var attribute = attributes[i]; var valuesStr = _checkoutAttributeParser.ParseValues(attributesXml, attribute.Id); for (var j = 0; j < valuesStr.Count; j++) { var valueStr = valuesStr[j]; var formattedAttribute = string.Empty; if (!attribute.ShouldHaveValues()) { //no values if (attribute.AttributeControlType == AttributeControlType.MultilineTextbox) { //multiline textbox var attributeName = _localizationService.GetLocalized(attribute, a => a.Name, _workContext.WorkingLanguage.Id); //encode (if required) if (htmlEncode) { attributeName = WebUtility.HtmlEncode(attributeName); } formattedAttribute = $"{attributeName}: {HtmlHelper.FormatText(valueStr, false, true, false, false, false, false)}"; //we never encode multiline textbox input } else if (attribute.AttributeControlType == AttributeControlType.FileUpload) { //file upload Guid.TryParse(valueStr, out var downloadGuid); var download = _downloadService.GetDownloadByGuid(downloadGuid); if (download != null) { string attributeText; var fileName = $"{download.Filename ?? download.DownloadGuid.ToString()}{download.Extension}"; //encode (if required) if (htmlEncode) { fileName = WebUtility.HtmlEncode(fileName); } if (allowHyperlinks) { //hyperlinks are allowed var downloadLink = $"{_webHelper.GetStoreLocation(false)}download/getfileupload/?downloadId={download.DownloadGuid}"; attributeText = $"<a href=\"{downloadLink}\" class=\"fileuploadattribute\">{fileName}</a>"; } else { //hyperlinks aren't allowed attributeText = fileName; } var attributeName = _localizationService.GetLocalized(attribute, a => a.Name, _workContext.WorkingLanguage.Id); //encode (if required) if (htmlEncode) { attributeName = WebUtility.HtmlEncode(attributeName); } formattedAttribute = $"{attributeName}: {attributeText}"; } } else { //other attributes (textbox, datepicker) formattedAttribute = $"{_localizationService.GetLocalized(attribute, a => a.Name, _workContext.WorkingLanguage.Id)}: {valueStr}"; //encode (if required) if (htmlEncode) { formattedAttribute = WebUtility.HtmlEncode(formattedAttribute); } } } else { if (int.TryParse(valueStr, out var attributeValueId)) { var attributeValue = _checkoutAttributeService.GetCheckoutAttributeValueById(attributeValueId); if (attributeValue != null) { formattedAttribute = $"{_localizationService.GetLocalized(attribute, a => a.Name, _workContext.WorkingLanguage.Id)}: {_localizationService.GetLocalized(attributeValue, a => a.Name, _workContext.WorkingLanguage.Id)}"; if (renderPrices) { var priceAdjustmentBase = _taxService.GetCheckoutAttributePrice(attribute, attributeValue, customer); var priceAdjustment = _currencyService.ConvertFromPrimaryStoreCurrency(priceAdjustmentBase, _workContext.WorkingCurrency); if (priceAdjustmentBase > 0) { formattedAttribute += string.Format( _localizationService.GetResource("FormattedAttributes.PriceAdjustment"), "+", _priceFormatter.FormatPrice(priceAdjustment), string.Empty); } } } //encode (if required) if (htmlEncode) { formattedAttribute = WebUtility.HtmlEncode(formattedAttribute); } } } if (string.IsNullOrEmpty(formattedAttribute)) { continue; } if (i != 0 || j != 0) { result.Append(separator); } result.Append(formattedAttribute); } } return(result.ToString()); }
/// <summary> /// Gets a configuration page URL /// </summary> public override string GetConfigurationPageUrl() { return(_webHelper.GetStoreLocation() + "Admin/WidgetsNivoSlider/Configure"); }
/// <summary> /// Gets a configuration page URL /// </summary> public override string GetConfigurationPageUrl() { return(_webHelper.GetStoreLocation() + "Admin/WidgetsPayPalMarketingSolutions/Configure"); }
public async Task <string> FormatAttributesAsync( CheckoutAttributeSelection selection, Customer customer = null, string serapator = "<br />", bool htmlEncode = true, bool renderPrices = true, bool allowHyperlinks = true) { Guard.NotNull(selection, nameof(selection)); customer ??= _workContext.CurrentCustomer; using var psb = StringBuilderPool.Instance.Get(out var sb); var attributesList = await _checkoutAttributeMaterializer.MaterializeCheckoutAttributesAsync(selection); if (attributesList.IsNullOrEmpty()) { return(null); } var attributeValues = attributesList .Where(x => x.IsListTypeAttribute) .SelectMany(x => x.CheckoutAttributeValues); var language = _workContext.WorkingLanguage; for (var i = 0; i < attributesList.Count; i++) { var currentAttribute = attributesList[i]; var currentAttributeValues = selection.GetAttributeValues(currentAttribute.Id).ToList(); for (var j = 0; j < currentAttributeValues.Count; j++) { var currentValue = currentAttributeValues[j].ToString(); var attributeStr = string.Empty; if (!currentAttribute.IsListTypeAttribute) { if (currentAttribute.AttributeControlType is AttributeControlType.MultilineTextbox) { // Multiline textbox input gets never encoded var attributeName = currentAttribute.GetLocalized(a => a.Name, language).ToString(); if (htmlEncode) { attributeName = HttpUtility.HtmlEncode(attributeName); } attributeStr = string.Format( "{0}: {1}", attributeName, HtmlUtils.ConvertPlainTextToHtml(currentValue.EmptyNull().Replace(":", "").HtmlEncode())); } else if (currentAttribute.AttributeControlType is AttributeControlType.FileUpload) { Guid.TryParse(currentValue, out var downloadGuid); var download = await _db.Downloads .Include(x => x.MediaFile) .Where(x => x.DownloadGuid == downloadGuid) .FirstOrDefaultAsync(); if (download?.MediaFile != null) { // TODO: (ms) (core) add a method for getting URL (use routing because it handles all SEO friendly URLs) ? //var genratedUrl = _mediaService.GenerateFileDownloadUrl(download.MediaFileId, 0); var attributeText = string.Empty; var fileName = download.MediaFile.Name; if (htmlEncode) { fileName = HttpUtility.HtmlEncode(fileName); } if (allowHyperlinks) { var downloadLink = string.Format( "{0}download/getfileupload/?downloadId={1}", _webHelper.GetStoreLocation(false), download.DownloadGuid); attributeText = string.Format( "<a href=\"{0}\" class=\"fileuploadattribute\">{1}</a>", downloadLink, fileName); } else { attributeText = fileName; } var attributeName = currentAttribute.GetLocalized(a => a.Name, language).ToString(); if (htmlEncode) { attributeName = HttpUtility.HtmlEncode(attributeName); } attributeStr = string.Format("{0}: {1}", attributeName, attributeText); } } else { // Other attributes (textbox, datepicker...) attributeStr = string.Format( "{0}: {1}", currentAttribute.GetLocalized(a => a.Name, language), currentValue); if (htmlEncode) { attributeStr = HttpUtility.HtmlEncode(attributeStr); } } } else { if (int.TryParse(currentValue, out var id)) { var attributeValue = attributeValues.Where(x => x.Id == id).FirstOrDefault(); if (attributeValue != null) { attributeStr = string.Format( "{0}: {1}", currentAttribute.GetLocalized(x => x.Name, language), attributeValue.GetLocalized(x => x.Name, language)); if (renderPrices) { var adjustment = await _taxCalculator.CalculateCheckoutAttributeTaxAsync(attributeValue, customer : customer); if (adjustment.Price > 0m) { var convertedAdjustment = _currencyService.ConvertToWorkingCurrency(adjustment.Price); attributeStr += " [+{0}]".FormatInvariant(_currencyService.ApplyTaxFormat(convertedAdjustment).ToString()); } } } if (htmlEncode) { attributeStr = HttpUtility.HtmlEncode(attributeStr); } } } if (attributeStr.HasValue()) { if (i != 0 || j != 0) { sb.Append(serapator); } sb.Append(attributeStr); } } } return(sb.ToString()); }
/// <summary> /// Gets a configuration page URL /// </summary> public override string GetConfigurationPageUrl() { return(_webHelper.GetStoreLocation().TrimEnd('/') + ConfigurePath); }
/// <summary> /// Gets a configuration page URL /// </summary> public override string GetConfigurationPageUrl() { return(_webHelper.GetStoreLocation() + "Admin/WidgetsSegmentAnalytics/Configure"); }
public override string GetConfigurationPageUrl() => $"{_webHelper.GetStoreLocation()}Admin/PaymentPagSeguro/Configure";
public ActionResult GenerateFeed(FeedBecomeModel model) { if (!ModelState.IsValid) { return(Configure()); } try { string fileName = string.Format("become_{0}_{1}.csv", DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss"), CommonHelper.GenerateRandomDigitCode(4)); string filePath = Path.Combine(Request.PhysicalApplicationPath, "content\\files\\exportimport", fileName); using (var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite)) { var pluginDescriptor = _pluginFinder.GetPluginDescriptorBySystemName("PromotionFeed.Become"); if (pluginDescriptor == null) { throw new Exception("Cannot load the plugin"); } //plugin var plugin = pluginDescriptor.Instance() as BecomeService; if (plugin == null) { throw new Exception("Cannot load the plugin"); } plugin.GenerateFeed(fs, _storeContext.CurrentStore); } string clickhereStr = string.Format("<a href=\"{0}content/files/exportimport/{1}\" target=\"_blank\">{2}</a>", _webHelper.GetStoreLocation(false), fileName, _localizationService.GetResource("Plugins.Feed.Become.ClickHere")); string result = string.Format(_localizationService.GetResource("Plugins.Feed.Become.SuccessResult"), clickhereStr); model.GenerateFeedResult = result; } catch (Exception exc) { model.GenerateFeedResult = exc.Message; _logger.Error(exc.Message, exc); } foreach (var c in _currencyService.GetAllCurrencies(false)) { model.AvailableCurrencies.Add(new SelectListItem() { Text = c.Name, Value = c.Id.ToString() }); } return(View("~/Plugins/Feed.Become/Views/FeedBecome/Configure.cshtml", model)); }
public virtual async Task <string> FormatAttributesAsync( ProductVariantAttributeSelection selection, Product product, Customer customer = null, string separator = "<br />", bool htmlEncode = true, bool includePrices = true, bool includeProductAttributes = true, bool includeGiftCardAttributes = true, bool includeHyperlinks = true) { Guard.NotNull(selection, nameof(selection)); Guard.NotNull(product, nameof(product)); customer ??= _workContext.CurrentCustomer; using var pool = StringBuilderPool.Instance.Get(out var result); if (includeProductAttributes) { var languageId = _workContext.WorkingLanguage.Id; var attributes = await _productAttributeMaterializer.MaterializeProductVariantAttributesAsync(selection); var attributesDic = attributes.ToDictionary(x => x.Id); foreach (var kvp in selection.AttributesMap) { if (!attributesDic.TryGetValue(kvp.Key, out var pva)) { continue; } foreach (var value in kvp.Value) { var valueStr = value.ToString().EmptyNull(); var pvaAttribute = string.Empty; if (pva.IsListTypeAttribute()) { var pvaValue = pva.ProductVariantAttributeValues.FirstOrDefault(x => x.Id == valueStr.ToInt()); if (pvaValue != null) { pvaAttribute = "{0}: {1}".FormatInvariant( pva.ProductAttribute.GetLocalized(x => x.Name, languageId), pvaValue.GetLocalized(x => x.Name, languageId)); if (includePrices) { var attributeValuePriceAdjustment = await _priceCalculationService.GetProductVariantAttributeValuePriceAdjustmentAsync(pvaValue, product, customer, null, 1); var(priceAdjustmentBase, _) = await _taxService.GetProductPriceAsync(product, attributeValuePriceAdjustment, customer : customer); var priceAdjustment = _currencyService.ConvertToWorkingCurrency(priceAdjustmentBase); if (_shoppingCartSettings.ShowLinkedAttributeValueQuantity && pvaValue.ValueType == ProductVariantAttributeValueType.ProductLinkage && pvaValue.Quantity > 1) { pvaAttribute = pvaAttribute + " × " + pvaValue.Quantity; } if (_catalogSettings.ShowVariantCombinationPriceAdjustment) { if (priceAdjustmentBase > decimal.Zero) { pvaAttribute += $" (+{priceAdjustment})"; } else if (priceAdjustmentBase < decimal.Zero) { pvaAttribute += $" (+{priceAdjustment * -1})"; } } } if (htmlEncode) { pvaAttribute = pvaAttribute.HtmlEncode(); } } } else if (pva.AttributeControlType == AttributeControlType.MultilineTextbox) { string attributeName = pva.ProductAttribute.GetLocalized(x => x.Name, languageId); pvaAttribute = "{0}: {1}".FormatInvariant( htmlEncode ? attributeName.HtmlEncode() : attributeName, HtmlUtils.ConvertPlainTextToHtml(valueStr.HtmlEncode())); } else if (pva.AttributeControlType == AttributeControlType.FileUpload) { if (Guid.TryParse(valueStr, out var downloadGuid) && downloadGuid != Guid.Empty) { var download = await _db.Downloads .AsNoTracking() .Include(x => x.MediaFile) .Where(x => x.DownloadGuid == downloadGuid) .FirstOrDefaultAsync(); if (download?.MediaFile != null) { var attributeText = string.Empty; var fileName = htmlEncode ? download.MediaFile.Name.HtmlEncode() : download.MediaFile.Name; if (includeHyperlinks) { // TODO: (core) add a method for getting URL (use routing because it handles all SEO friendly URLs). var downloadLink = _webHelper.GetStoreLocation(false) + "download/getfileupload/?downloadId=" + download.DownloadGuid; attributeText = $"<a href=\"{downloadLink}\" class=\"fileuploadattribute\">{fileName}</a>"; } else { attributeText = fileName; } string attributeName = pva.ProductAttribute.GetLocalized(a => a.Name, languageId); pvaAttribute = "{0}: {1}".FormatInvariant( htmlEncode ? attributeName.HtmlEncode() : attributeName, attributeText); } } } else { // TextBox, Datepicker pvaAttribute = "{0}: {1}".FormatInvariant(pva.ProductAttribute.GetLocalized(x => x.Name, languageId), valueStr); if (htmlEncode) { pvaAttribute = pvaAttribute.HtmlEncode(); } } result.Grow(pvaAttribute, separator); } } } if (includeGiftCardAttributes && product.IsGiftCard) { var gci = selection.GiftCardInfo; if (gci != null) { // Sender. var giftCardFrom = product.GiftCardType == GiftCardType.Virtual ? (await _localizationService.GetResourceAsync("GiftCardAttribute.From.Virtual")).FormatInvariant(gci.SenderName, gci.SenderEmail) : (await _localizationService.GetResourceAsync("GiftCardAttribute.From.Physical")).FormatInvariant(gci.SenderName); // Recipient. var giftCardFor = product.GiftCardType == GiftCardType.Virtual ? (await _localizationService.GetResourceAsync("GiftCardAttribute.For.Virtual")).FormatInvariant(gci.RecipientName, gci.RecipientEmail) : (await _localizationService.GetResourceAsync("GiftCardAttribute.For.Physical")).FormatInvariant(gci.RecipientName); if (htmlEncode) { giftCardFrom = giftCardFrom.HtmlEncode(); giftCardFor = giftCardFor.HtmlEncode(); } result.Grow(giftCardFrom, separator); result.Grow(giftCardFor, separator); } } return(result.ToString()); }
/// <summary> /// Gets a configuration page URL /// </summary> public override string GetConfigurationPageUrl() { return($"{_webHelper.GetStoreLocation()}Admin/PaymentTransfer/Configure"); }
/// <summary> /// Gets a configuration page URL /// </summary> public override string GetConfigurationPageUrl() { return($"{_webHelper.GetStoreLocation()}Admin/UPSShipping/Configure"); }
/// <summary> /// Generate string (URL) for redirection /// </summary> /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param> /// <param name="passProductNamesAndTotals">A value indicating whether to pass product names and totals</param> private string GenerationRedirectionUrl(PostProcessPaymentRequest postProcessPaymentRequest, bool passProductNamesAndTotals) { var builder = new StringBuilder(); builder.Append(GetPaypalUrl()); var cmd = passProductNamesAndTotals ? "_cart" : "_xclick"; builder.AppendFormat("?cmd={0}&business={1}", cmd, HttpUtility.UrlEncode(_paypalStandardPaymentSettings.BusinessEmail)); if (passProductNamesAndTotals) { builder.AppendFormat("&upload=1"); //get the items in the cart decimal cartTotal = decimal.Zero; var cartItems = postProcessPaymentRequest.Order.OrderItems; int x = 1; foreach (var item in cartItems) { var unitPriceExclTax = item.UnitPriceExclTax; var priceExclTax = item.PriceExclTax; //round var unitPriceExclTaxRounded = Math.Round(unitPriceExclTax, 2); builder.AppendFormat("&item_name_" + x + "={0}", HttpUtility.UrlEncode(item.Product.Name)); builder.AppendFormat("&amount_" + x + "={0}", unitPriceExclTaxRounded.ToString("0.00", CultureInfo.InvariantCulture)); builder.AppendFormat("&quantity_" + x + "={0}", item.Quantity); x++; cartTotal += priceExclTax; } //the checkout attributes that have a dollar value and send them to Paypal as items to be paid for var attributeValues = _checkoutAttributeParser.ParseCheckoutAttributeValues(postProcessPaymentRequest.Order.CheckoutAttributesXml); foreach (var val in attributeValues) { var attPrice = _taxService.GetCheckoutAttributePrice(val, false, postProcessPaymentRequest.Order.Customer); //round var attPriceRounded = Math.Round(attPrice, 2); if (attPrice > decimal.Zero) //if it has a price { var attribute = val.CheckoutAttribute; if (attribute != null) { var attName = attribute.Name; //set the name builder.AppendFormat("&item_name_" + x + "={0}", HttpUtility.UrlEncode(attName)); //name builder.AppendFormat("&amount_" + x + "={0}", attPriceRounded.ToString("0.00", CultureInfo.InvariantCulture)); //amount builder.AppendFormat("&quantity_" + x + "={0}", 1); //quantity x++; cartTotal += attPrice; } } } //order totals //shipping var orderShippingExclTax = postProcessPaymentRequest.Order.OrderShippingExclTax; var orderShippingExclTaxRounded = Math.Round(orderShippingExclTax, 2); if (orderShippingExclTax > decimal.Zero) { builder.AppendFormat("&item_name_" + x + "={0}", "Shipping fee"); builder.AppendFormat("&amount_" + x + "={0}", orderShippingExclTaxRounded.ToString("0.00", CultureInfo.InvariantCulture)); builder.AppendFormat("&quantity_" + x + "={0}", 1); x++; cartTotal += orderShippingExclTax; } //payment method additional fee var paymentMethodAdditionalFeeExclTax = postProcessPaymentRequest.Order.PaymentMethodAdditionalFeeExclTax; var paymentMethodAdditionalFeeExclTaxRounded = Math.Round(paymentMethodAdditionalFeeExclTax, 2); if (paymentMethodAdditionalFeeExclTax > decimal.Zero) { builder.AppendFormat("&item_name_" + x + "={0}", "Payment method fee"); builder.AppendFormat("&amount_" + x + "={0}", paymentMethodAdditionalFeeExclTaxRounded.ToString("0.00", CultureInfo.InvariantCulture)); builder.AppendFormat("&quantity_" + x + "={0}", 1); x++; cartTotal += paymentMethodAdditionalFeeExclTax; } //tax var orderTax = postProcessPaymentRequest.Order.OrderTax; var orderTaxRounded = Math.Round(orderTax, 2); if (orderTax > decimal.Zero) { //builder.AppendFormat("&tax_1={0}", orderTax.ToString("0.00", CultureInfo.InvariantCulture)); //add tax as item builder.AppendFormat("&item_name_" + x + "={0}", HttpUtility.UrlEncode("Sales Tax")); //name builder.AppendFormat("&amount_" + x + "={0}", orderTaxRounded.ToString("0.00", CultureInfo.InvariantCulture)); //amount builder.AppendFormat("&quantity_" + x + "={0}", 1); //quantity cartTotal += orderTax; x++; } if (cartTotal > postProcessPaymentRequest.Order.OrderTotal) { /* Take the difference between what the order total is and what it should be and use that as the "discount". * The difference equals the amount of the gift card and/or reward points used. */ decimal discountTotal = cartTotal - postProcessPaymentRequest.Order.OrderTotal; discountTotal = Math.Round(discountTotal, 2); //gift card or rewared point amount applied to cart in nopCommerce - shows in Paypal as "discount" builder.AppendFormat("&discount_amount_cart={0}", discountTotal.ToString("0.00", CultureInfo.InvariantCulture)); } } else { //pass order total builder.AppendFormat("&item_name=Order Number {0}", postProcessPaymentRequest.Order.Id); var orderTotal = Math.Round(postProcessPaymentRequest.Order.OrderTotal, 2); builder.AppendFormat("&amount={0}", orderTotal.ToString("0.00", CultureInfo.InvariantCulture)); } builder.AppendFormat("&custom={0}", postProcessPaymentRequest.Order.OrderGuid); builder.AppendFormat("&charset={0}", "utf-8"); builder.AppendFormat("&bn={0}", BN_CODE); builder.Append(string.Format("&no_note=1¤cy_code={0}", HttpUtility.UrlEncode(_currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId).CurrencyCode))); builder.AppendFormat("&invoice={0}", postProcessPaymentRequest.Order.Id); builder.AppendFormat("&rm=2", new object[0]); if (postProcessPaymentRequest.Order.ShippingStatus != ShippingStatus.ShippingNotRequired) { builder.AppendFormat("&no_shipping=2", new object[0]); } else { builder.AppendFormat("&no_shipping=1", new object[0]); } string returnUrl = _webHelper.GetStoreLocation(false) + "Plugins/PaymentPayPalStandard/PDTHandler"; string cancelReturnUrl = _webHelper.GetStoreLocation(false) + "Plugins/PaymentPayPalStandard/CancelOrder"; builder.AppendFormat("&return={0}&cancel_return={1}", HttpUtility.UrlEncode(returnUrl), HttpUtility.UrlEncode(cancelReturnUrl)); //Instant Payment Notification (server to server message) if (_paypalStandardPaymentSettings.EnableIpn) { string ipnUrl; if (String.IsNullOrWhiteSpace(_paypalStandardPaymentSettings.IpnUrl)) { ipnUrl = _webHelper.GetStoreLocation(false) + "Plugins/PaymentPayPalStandard/IPNHandler"; } else { ipnUrl = _paypalStandardPaymentSettings.IpnUrl; } builder.AppendFormat("¬ify_url={0}", ipnUrl); } //address builder.AppendFormat("&address_override={0}", _paypalStandardPaymentSettings.AddressOverride ? "1" : "0"); builder.AppendFormat("&first_name={0}", HttpUtility.UrlEncode(postProcessPaymentRequest.Order.BillingAddress.FirstName)); builder.AppendFormat("&last_name={0}", HttpUtility.UrlEncode(postProcessPaymentRequest.Order.BillingAddress.LastName)); builder.AppendFormat("&address1={0}", HttpUtility.UrlEncode(postProcessPaymentRequest.Order.BillingAddress.Address1)); builder.AppendFormat("&address2={0}", HttpUtility.UrlEncode(postProcessPaymentRequest.Order.BillingAddress.Address2)); builder.AppendFormat("&city={0}", HttpUtility.UrlEncode(postProcessPaymentRequest.Order.BillingAddress.City)); //if (!String.IsNullOrEmpty(postProcessPaymentRequest.Order.BillingAddress.PhoneNumber)) //{ // //strip out all non-digit characters from phone number; // string billingPhoneNumber = System.Text.RegularExpressions.Regex.Replace(postProcessPaymentRequest.Order.BillingAddress.PhoneNumber, @"\D", string.Empty); // if (billingPhoneNumber.Length >= 10) // { // builder.AppendFormat("&night_phone_a={0}", HttpUtility.UrlEncode(billingPhoneNumber.Substring(0, 3))); // builder.AppendFormat("&night_phone_b={0}", HttpUtility.UrlEncode(billingPhoneNumber.Substring(3, 3))); // builder.AppendFormat("&night_phone_c={0}", HttpUtility.UrlEncode(billingPhoneNumber.Substring(6, 4))); // } //} if (postProcessPaymentRequest.Order.BillingAddress.StateProvince != null) { builder.AppendFormat("&state={0}", HttpUtility.UrlEncode(postProcessPaymentRequest.Order.BillingAddress.StateProvince.Abbreviation)); } else { builder.AppendFormat("&state={0}", ""); } if (postProcessPaymentRequest.Order.BillingAddress.Country != null) { builder.AppendFormat("&country={0}", HttpUtility.UrlEncode(postProcessPaymentRequest.Order.BillingAddress.Country.TwoLetterIsoCode)); } else { builder.AppendFormat("&country={0}", ""); } builder.AppendFormat("&zip={0}", HttpUtility.UrlEncode(postProcessPaymentRequest.Order.BillingAddress.ZipPostalCode)); builder.AppendFormat("&email={0}", HttpUtility.UrlEncode(postProcessPaymentRequest.Order.BillingAddress.Email)); return(builder.ToString()); }
public async Task <IList <SearchAutoCompleteModel> > Handle(GetSearchAutoComplete request, CancellationToken cancellationToken) { var model = new List <SearchAutoCompleteModel>(); var productNumber = _catalogSettings.ProductSearchAutoCompleteNumberOfProducts > 0 ? _catalogSettings.ProductSearchAutoCompleteNumberOfProducts : 10; var storeId = request.Store.Id; var categoryIds = new List <string>(); if (!string.IsNullOrEmpty(request.CategoryId)) { categoryIds.Add(request.CategoryId); if (_catalogSettings.ShowProductsFromSubcategoriesInSearchBox) { //include subcategories categoryIds.AddRange(await _mediator.Send(new GetChildCategoryIds() { ParentCategoryId = request.CategoryId, Customer = request.Customer, Store = request.Store })); } } var products = (await _productService.SearchProducts( storeId: storeId, keywords: request.Term, categoryIds: categoryIds, searchSku: _catalogSettings.SearchBySku, searchDescriptions: _catalogSettings.SearchByDescription, languageId: request.Language.Id, visibleIndividuallyOnly: true, pageSize: productNumber)).products; var categories = new List <string>(); var manufacturers = new List <string>(); var storeurl = _webHelper.GetStoreLocation(); foreach (var item in products) { var pictureUrl = ""; if (_catalogSettings.ShowProductImagesInSearchAutoComplete) { var picture = item.ProductPictures.OrderBy(x => x.DisplayOrder).FirstOrDefault(); if (picture != null) { pictureUrl = await _pictureService.GetPictureUrl(picture.PictureId, _mediaSettings.AutoCompleteSearchThumbPictureSize); } } var rating = await _mediator.Send(new GetProductReviewOverview() { Language = request.Language, Product = item, Store = request.Store }); var price = await PreparePrice(item, request); model.Add(new SearchAutoCompleteModel() { SearchType = "Product", Label = item.GetLocalized(x => x.Name, request.Language.Id) ?? "", Desc = item.GetLocalized(x => x.ShortDescription, request.Language.Id) ?? "", PictureUrl = pictureUrl, AllowCustomerReviews = rating.AllowCustomerReviews, Rating = rating.TotalReviews > 0 ? (((rating.RatingSum * 100) / rating.TotalReviews) / 5) : 0, Price = price.Price, PriceWithDiscount = price.PriceWithDiscount, Url = $"{storeurl}{item.SeName}" }); foreach (var category in item.ProductCategories) { categories.Add(category.CategoryId); } foreach (var manufacturer in item.ProductManufacturers) { manufacturers.Add(manufacturer.ManufacturerId); } } foreach (var item in manufacturers.Distinct()) { var manufacturer = await _manufacturerService.GetManufacturerById(item); if (manufacturer != null && manufacturer.Published) { var allow = true; if (!_catalogSettings.IgnoreAcl) { if (!_aclService.Authorize(manufacturer)) { allow = false; } } if (!_catalogSettings.IgnoreStoreLimitations) { if (!_storeMappingService.Authorize(manufacturer)) { allow = false; } } if (allow) { var desc = ""; if (_catalogSettings.SearchByDescription) { desc = "&sid=true"; } model.Add(new SearchAutoCompleteModel() { SearchType = "Manufacturer", Label = manufacturer.GetLocalized(x => x.Name, request.Language.Id), Desc = "", PictureUrl = "", Url = $"{storeurl}search?q={request.Term}&adv=true&mid={item}{desc}" }); } } } foreach (var item in categories.Distinct()) { var category = await _categoryService.GetCategoryById(item); if (category != null && category.Published) { var allow = true; if (!_catalogSettings.IgnoreAcl) { if (!_aclService.Authorize(category)) { allow = false; } } if (!_catalogSettings.IgnoreStoreLimitations) { if (!_storeMappingService.Authorize(category)) { allow = false; } } if (allow) { var desc = ""; if (_catalogSettings.SearchByDescription) { desc = "&sid=true"; } model.Add(new SearchAutoCompleteModel() { SearchType = "Category", Label = category.GetLocalized(x => x.Name, request.Language.Id), Desc = "", PictureUrl = "", Url = $"{storeurl}search?q={request.Term}&adv=true&cid={item}{desc}" }); } } } if (_blogSettings.ShowBlogPostsInSearchAutoComplete) { var posts = await _blogService.GetAllBlogPosts(storeId : storeId, pageSize : productNumber, blogPostName : request.Term); foreach (var item in posts) { model.Add(new SearchAutoCompleteModel() { SearchType = "Blog", Label = item.GetLocalized(x => x.Title, request.Language.Id), Desc = "", PictureUrl = "", Url = $"{storeurl}{item.SeName}" }); } } //search term statistics if (!String.IsNullOrEmpty(request.Term) && _catalogSettings.SaveSearchAutoComplete) { var searchTerm = await _searchTermService.GetSearchTermByKeyword(request.Term, request.Store.Id); if (searchTerm != null) { searchTerm.Count++; await _searchTermService.UpdateSearchTerm(searchTerm); } else { searchTerm = new SearchTerm { Keyword = request.Term, StoreId = storeId, Count = 1 }; await _searchTermService.InsertSearchTerm(searchTerm); } } return(model); }
private async Task <StringBuilder> PrepareFormattedAttribute(Product product, IList <CustomAttribute> customAttributes, string langId, string serapator, bool htmlEncode, bool renderPrices, bool allowHyperlinks, bool showInAdmin) { var result = new StringBuilder(); var attributes = _productAttributeParser.ParseProductAttributeMappings(product, customAttributes); for (int i = 0; i < attributes.Count; i++) { var productAttribute = await _productAttributeService.GetProductAttributeById(attributes[i].ProductAttributeId); var attribute = attributes[i]; var valuesStr = _productAttributeParser.ParseValues(customAttributes, attribute.Id); for (int j = 0; j < valuesStr.Count; j++) { string valueStr = valuesStr[j]; string formattedAttribute = string.Empty; if (!attribute.ShouldHaveValues()) { //no values if (attribute.AttributeControlType == AttributeControlType.MultilineTextbox) { //multiline textbox var attributeName = productAttribute.GetLocalized(a => a.Name, langId); //encode (if required) if (htmlEncode) { attributeName = WebUtility.HtmlEncode(attributeName); } formattedAttribute = string.Format("{0}: {1}", attributeName, HtmlHelper.FormatText(valueStr)); //we never encode multiline textbox input } else if (attribute.AttributeControlType == AttributeControlType.FileUpload) { //file upload Guid downloadGuid; Guid.TryParse(valueStr, out downloadGuid); var download = await _downloadService.GetDownloadByGuid(downloadGuid); if (download != null) { //TODO add a method for getting URL (use routing because it handles all SEO friendly URLs) string attributeText = ""; var fileName = string.Format("{0}{1}", download.Filename ?? download.DownloadGuid.ToString(), download.Extension); //encode (if required) if (htmlEncode) { fileName = WebUtility.HtmlEncode(fileName); } if (allowHyperlinks) { //hyperlinks are allowed var downloadLink = string.Format("{0}download/getfileupload/?downloadId={1}", _webHelper.GetStoreLocation(false), download.DownloadGuid); attributeText = string.Format("<a href=\"{0}\" class=\"fileuploadattribute\">{1}</a>", downloadLink, fileName); } else { //hyperlinks aren't allowed attributeText = fileName; } var attributeName = productAttribute.GetLocalized(a => a.Name, langId); //encode (if required) if (htmlEncode) { attributeName = WebUtility.HtmlEncode(attributeName); } formattedAttribute = string.Format("{0}: {1}", attributeName, attributeText); } } else { //other attributes (textbox, datepicker) formattedAttribute = string.Format("{0}: {1}", productAttribute.GetLocalized(a => a.Name, langId), valueStr); //encode (if required) if (htmlEncode) { formattedAttribute = WebUtility.HtmlEncode(formattedAttribute); } } } else { //attributes with values if (product.ProductAttributeMappings.Where(x => x.Id == attributes[i].Id).FirstOrDefault() != null) { var attributeValue = product.ProductAttributeMappings.Where(x => x.Id == attributes[i].Id).FirstOrDefault().ProductAttributeValues.Where(x => x.Id == valueStr).FirstOrDefault(); if (attributeValue != null) { formattedAttribute = string.Format("{0}: {1}", productAttribute.GetLocalized(a => a.Name, langId), attributeValue.GetLocalized(a => a.Name, langId)); if (renderPrices) { decimal attributeValuePriceAdjustment = await _priceCalculationService.GetProductAttributeValuePriceAdjustment(attributeValue); var prices = await _taxService.GetProductPrice(product, attributeValuePriceAdjustment, _workContext.CurrentCustomer); decimal priceAdjustmentBase = prices.productprice; decimal taxRate = prices.taxRate; decimal priceAdjustment = await _currencyService.ConvertFromPrimaryStoreCurrency(priceAdjustmentBase, _workContext.WorkingCurrency); if (priceAdjustmentBase > 0) { string priceAdjustmentStr = _priceFormatter.FormatPrice(priceAdjustment, false, false); formattedAttribute += string.Format(" [+{0}]", priceAdjustmentStr); } else if (priceAdjustmentBase < decimal.Zero) { string priceAdjustmentStr = _priceFormatter.FormatPrice(-priceAdjustment, false, false); formattedAttribute += string.Format(" [-{0}]", priceAdjustmentStr); } } //display quantity if (_shoppingCartSettings.RenderAssociatedAttributeValueQuantity && attributeValue.AttributeValueType == AttributeValueType.AssociatedToProduct) { //render only when more than 1 if (attributeValue.Quantity > 1) { //TODO localize resource formattedAttribute += string.Format(" - qty {0}", attributeValue.Quantity); } } } else { if (showInAdmin) { formattedAttribute += string.Format("{0}: {1}", productAttribute.GetLocalized(a => a.Name, langId), ""); } } //encode (if required) if (htmlEncode) { formattedAttribute = WebUtility.HtmlEncode(formattedAttribute); } } } if (!string.IsNullOrEmpty(formattedAttribute)) { if (i != 0 || j != 0) { result.Append(serapator); } result.Append(formattedAttribute); } } } return(result); }
private Uri GenerateLocalCallbackUri() { string url = string.Format("{0}Plugins/SmartStore.FacebookAuth/logincallback/", _webHelper.GetStoreLocation()); return(new Uri(url)); }
public void CanGetStoreLocationWithoutSsl() { _webHelper.GetStoreLocation(false).Should().Be($"http://{NopTestsDefaults.HostIpAddress}/"); }
/// <summary> /// Post process payment (used by payment gateways that require redirecting to a third-party URL) /// </summary> /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param> public void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest) { var myUtility = new PayuHelper(); var orderId = postProcessPaymentRequest.Order.Id; var remotePostHelper = new RemotePost(); remotePostHelper.FormName = "PayuForm"; remotePostHelper.Url = _payuPaymentSettings.PayUri; remotePostHelper.Add("key", _payuPaymentSettings.MerchantId.ToString()); remotePostHelper.Add("amount", postProcessPaymentRequest.Order.OrderTotal.ToString(new CultureInfo("en-US", false).NumberFormat)); remotePostHelper.Add("productinfo", "productinfo"); remotePostHelper.Add("Currency", _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId).CurrencyCode); remotePostHelper.Add("Order_Id", orderId.ToString()); var txnId = _payuPaymentSettings.PayUri.Contains("test.payu.in") ? Guid.NewGuid().ToString() : orderId.ToString(); remotePostHelper.Add("txnid", txnId); //remotePostHelper.Add("service_provider", "payu_paisa"); remotePostHelper.Add("surl", _webHelper.GetStoreLocation(false) + "Plugins/PaymentPayu/Return"); remotePostHelper.Add("furl", _webHelper.GetStoreLocation(false) + "Plugins/PaymentPayu/Return"); remotePostHelper.Add("hash", myUtility.getchecksum(_payuPaymentSettings.MerchantId.ToString(), txnId, postProcessPaymentRequest.Order.OrderTotal.ToString(new CultureInfo("en-US", false).NumberFormat), "productinfo", postProcessPaymentRequest.Order.BillingAddress.FirstName.ToString(), postProcessPaymentRequest.Order.BillingAddress.Email.ToString(), _payuPaymentSettings.Key)); //Billing details remotePostHelper.Add("firstname", postProcessPaymentRequest.Order.BillingAddress.FirstName.ToString()); remotePostHelper.Add("billing_cust_address", postProcessPaymentRequest.Order.BillingAddress.Address1); remotePostHelper.Add("phone", postProcessPaymentRequest.Order.BillingAddress.PhoneNumber); remotePostHelper.Add("email", postProcessPaymentRequest.Order.BillingAddress.Email.ToString()); remotePostHelper.Add("billing_cust_city", postProcessPaymentRequest.Order.BillingAddress.City); var billingStateProvince = postProcessPaymentRequest.Order.BillingAddress.StateProvince; if (billingStateProvince != null) { remotePostHelper.Add("billing_cust_state", billingStateProvince.Abbreviation); } else { remotePostHelper.Add("billing_cust_state", ""); } remotePostHelper.Add("billing_zip_code", postProcessPaymentRequest.Order.BillingAddress.ZipPostalCode); var billingCountry = postProcessPaymentRequest.Order.BillingAddress.Country; if (billingCountry != null) { remotePostHelper.Add("billing_cust_country", billingCountry.ThreeLetterIsoCode); } else { remotePostHelper.Add("billing_cust_country", ""); } //Delivery details if (postProcessPaymentRequest.Order.ShippingStatus != ShippingStatus.ShippingNotRequired) { remotePostHelper.Add("delivery_cust_name", postProcessPaymentRequest.Order.ShippingAddress.FirstName); remotePostHelper.Add("delivery_cust_address", postProcessPaymentRequest.Order.ShippingAddress.Address1); remotePostHelper.Add("delivery_cust_notes", string.Empty); remotePostHelper.Add("delivery_cust_tel", postProcessPaymentRequest.Order.ShippingAddress.PhoneNumber); remotePostHelper.Add("delivery_cust_city", postProcessPaymentRequest.Order.ShippingAddress.City); var deliveryStateProvince = postProcessPaymentRequest.Order.ShippingAddress.StateProvince; if (deliveryStateProvince != null) { remotePostHelper.Add("delivery_cust_state", deliveryStateProvince.Abbreviation); } else { remotePostHelper.Add("delivery_cust_state", ""); } remotePostHelper.Add("delivery_zip_code", postProcessPaymentRequest.Order.ShippingAddress.ZipPostalCode); var deliveryCountry = postProcessPaymentRequest.Order.ShippingAddress.Country; if (deliveryCountry != null) { remotePostHelper.Add("delivery_cust_country", deliveryCountry.ThreeLetterIsoCode); } else { remotePostHelper.Add("delivery_cust_country", ""); } } // remotePostHelper.Add("Merchant_Param", _PayuPaymentSettings.MerchantParam); try { remotePostHelper.Post(); } catch (Exception ex) { //Send email SendPaymentFailedStoreOwnerNotification SendEmail(ex.ToString(), postProcessPaymentRequest); throw new Exception(ex.Message); } }
/// <summary> /// Gets a configuration page URL /// </summary> public override string GetConfigurationPageUrl() { return($"{_webHelper.GetStoreLocation()}Admin/FixedByWeightByTotal/Configure"); }
/// <summary> /// Post process payment (used by payment gateways that require redirecting to a third-party URL) /// </summary> /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param> public void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest) { //RemotePost DefaultAopClient client = new DefaultAopClient(_aliPayPaymentSettings.GatewayUrl, _aliPayPaymentSettings.AppID, _aliPayPaymentSettings.PrivateKey, "json", "1.0", _aliPayPaymentSettings.SignType, _aliPayPaymentSettings.AlipayPublicKey, "UTF-8", false); // 外部订单号,商户网站订单系统中唯一的订单号 string out_trade_no = postProcessPaymentRequest.Order.Id.ToString(); // 订单名称 string subject = _storeContext.CurrentStore.Name; //订单原始价格按主货币, var CNY = _currencyService.GetCurrencyByCode("CNY"); var primaryExchangeCurrency = _currencyService.GetCurrencyById(_currencySettings.PrimaryExchangeRateCurrencyId); if (primaryExchangeCurrency == null) { throw new NopException("Primary exchange rate currency is not set"); } // 付款金额 ,换算成 人民币 decimal cur_total = postProcessPaymentRequest.Order.OrderTotal; cur_total = cur_total / primaryExchangeCurrency.Rate * CNY.Rate; string total_amout = cur_total.ToString("0.00", CultureInfo.InvariantCulture); // 商品描述 string body = "Order from " + _storeContext.CurrentStore.Name; AopResponse response = null; string s = _httpContext.Request.UserAgent; Regex b = new Regex(@"android.+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino", RegexOptions.IgnoreCase | RegexOptions.Multiline); Regex v = new Regex(@"1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-", RegexOptions.IgnoreCase | RegexOptions.Multiline); if (!(b.IsMatch(s) || v.IsMatch(s.Substring(0, 4)))) { AlipayTradePagePayRequest request = new AlipayTradePagePayRequest(); // 设置同步回调地址 request.SetReturnUrl(_webHelper.GetStoreLocation(false) + "Plugins/PaymentAliPay/Return"); // 设置异步通知接收地址 request.SetNotifyUrl(_webHelper.GetStoreLocation(false) + "Plugins/PaymentAliPay/Notify"); // 将业务model载入到request request.SetBizModel(new AlipayTradePagePayModel() { Body = body, Subject = subject, TotalAmount = total_amout, OutTradeNo = out_trade_no, GoodsType = "0", TimeoutExpress = "15m", ProductCode = "FAST_INSTANT_TRADE_PAY" }); try { response = client.pageExecute(request, null, "post"); } catch (Exception exp) { _logger.Warning($"{DateTime.Now.ToString()}Ali Page PayError:{exp.Message}"); } } else { AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest(); // 设置同步回调地址 request.SetReturnUrl(_webHelper.GetStoreLocation(false) + "Plugins/PaymentAliPay/Return"); // 设置异步通知接收地址 request.SetNotifyUrl(_webHelper.GetStoreLocation(false) + "Plugins/PaymentAliPay/Notify"); // 将业务model载入到request request.SetBizModel(new AlipayTradeWapPayModel() { Body = body, Subject = subject, TotalAmount = total_amout, OutTradeNo = out_trade_no, GoodsType = "0", TimeoutExpress = "15m", ProductCode = "FAST_INSTANT_TRADE_PAY" }); try { response = client.pageExecute(request, null, "post"); } catch (Exception exp) { _logger.Warning($"{DateTime.Now.ToString()}Ali Wap PayError:{exp.Message}"); } } _httpContext.Response.Clear(); _httpContext.Response.Write("<html><head><meta http-equiv=\"Content - Type\" content=\"text / html; charset = utf - 8\"/></head><body style=\"display:none\">"); _httpContext.Response.Write(response.Body); _httpContext.Response.Write("</body></html>"); _httpContext.Response.End(); }
public IActionResult Warnings() { var model = new List <SystemWarningModel>(); //store URL var currentStoreUrl = _storeContext.CurrentStore.Url; if (!String.IsNullOrEmpty(currentStoreUrl) && (currentStoreUrl.Equals(_webHelper.GetStoreLocation(false), StringComparison.OrdinalIgnoreCase) || currentStoreUrl.Equals(_webHelper.GetStoreLocation(true), StringComparison.OrdinalIgnoreCase) )) { model.Add(new SystemWarningModel { Level = SystemWarningLevel.Pass, Text = _localizationService.GetResource("Admin.System.Warnings.URL.Match") }); } else { model.Add(new SystemWarningModel { Level = SystemWarningLevel.Warning, Text = string.Format(_localizationService.GetResource("Admin.System.Warnings.URL.NoMatch"), currentStoreUrl, _webHelper.GetStoreLocation(false)) }); } //primary exchange rate currency var perCurrency = _currencyService.GetCurrencyById(_currencySettings.PrimaryExchangeRateCurrencyId); if (perCurrency != null) { model.Add(new SystemWarningModel { Level = SystemWarningLevel.Pass, Text = _localizationService.GetResource("Admin.System.Warnings.ExchangeCurrency.Set"), }); if (perCurrency.Rate != 1) { model.Add(new SystemWarningModel { Level = SystemWarningLevel.Fail, Text = _localizationService.GetResource("Admin.System.Warnings.ExchangeCurrency.Rate1") }); } } else { model.Add(new SystemWarningModel { Level = SystemWarningLevel.Fail, Text = _localizationService.GetResource("Admin.System.Warnings.ExchangeCurrency.NotSet") }); } //primary store currency var pscCurrency = _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId); if (pscCurrency != null) { model.Add(new SystemWarningModel { Level = SystemWarningLevel.Pass, Text = _localizationService.GetResource("Admin.System.Warnings.PrimaryCurrency.Set"), }); } else { model.Add(new SystemWarningModel { Level = SystemWarningLevel.Fail, Text = _localizationService.GetResource("Admin.System.Warnings.PrimaryCurrency.NotSet") }); } //base measure weight var bWeight = _measureService.GetMeasureWeightById(_measureSettings.BaseWeightId); if (bWeight != null) { model.Add(new SystemWarningModel { Level = SystemWarningLevel.Pass, Text = _localizationService.GetResource("Admin.System.Warnings.DefaultWeight.Set"), }); if (bWeight.Ratio != 1) { model.Add(new SystemWarningModel { Level = SystemWarningLevel.Fail, Text = _localizationService.GetResource("Admin.System.Warnings.DefaultWeight.Ratio1") }); } } else { model.Add(new SystemWarningModel { Level = SystemWarningLevel.Fail, Text = _localizationService.GetResource("Admin.System.Warnings.DefaultWeight.NotSet") }); } //base dimension weight var bDimension = _measureService.GetMeasureDimensionById(_measureSettings.BaseDimensionId); if (bDimension != null) { model.Add(new SystemWarningModel { Level = SystemWarningLevel.Pass, Text = _localizationService.GetResource("Admin.System.Warnings.DefaultDimension.Set"), }); if (bDimension.Ratio != 1) { model.Add(new SystemWarningModel { Level = SystemWarningLevel.Fail, Text = _localizationService.GetResource("Admin.System.Warnings.DefaultDimension.Ratio1") }); } } else { model.Add(new SystemWarningModel { Level = SystemWarningLevel.Fail, Text = _localizationService.GetResource("Admin.System.Warnings.DefaultDimension.NotSet") }); } //shipping rate coputation methods var srcMethods = _shippingService.LoadActiveShippingRateComputationMethods(); if (srcMethods.Count == 0) { model.Add(new SystemWarningModel { Level = SystemWarningLevel.Fail, Text = _localizationService.GetResource("Admin.System.Warnings.Shipping.NoComputationMethods") }); } if (srcMethods.Count(x => x.ShippingRateComputationMethodType == ShippingRateComputationMethodType.Offline) > 1) { model.Add(new SystemWarningModel { Level = SystemWarningLevel.Warning, Text = _localizationService.GetResource("Admin.System.Warnings.Shipping.OnlyOneOffline") }); } //payment methods if (_paymentService.LoadActivePaymentMethods().Any()) { model.Add(new SystemWarningModel { Level = SystemWarningLevel.Pass, Text = _localizationService.GetResource("Admin.System.Warnings.PaymentMethods.OK") }); } else { model.Add(new SystemWarningModel { Level = SystemWarningLevel.Fail, Text = _localizationService.GetResource("Admin.System.Warnings.PaymentMethods.NoActive") }); } //incompatible plugins if (PluginManager.IncompatiblePlugins != null) { foreach (var pluginName in PluginManager.IncompatiblePlugins) { model.Add(new SystemWarningModel { Level = SystemWarningLevel.Warning, Text = string.Format(_localizationService.GetResource("Admin.System.Warnings.IncompatiblePlugin"), pluginName) }); } } //performance settings if (!_catalogSettings.IgnoreStoreLimitations && _storeService.GetAllStores().Count == 1) { model.Add(new SystemWarningModel { Level = SystemWarningLevel.Warning, Text = _localizationService.GetResource("Admin.System.Warnings.Performance.IgnoreStoreLimitations") }); } if (!_catalogSettings.IgnoreAcl) { model.Add(new SystemWarningModel { Level = SystemWarningLevel.Warning, Text = _localizationService.GetResource("Admin.System.Warnings.Performance.IgnoreAcl") }); } //validate write permissions (the same procedure like during installation) var dirPermissionsOk = true; var dirsToCheck = FilePermissionHelper.GetDirectoriesWrite(); foreach (string dir in dirsToCheck) { if (!FilePermissionHelper.CheckPermissions(dir, false, true, true, false)) { model.Add(new SystemWarningModel { Level = SystemWarningLevel.Warning, Text = string.Format(_localizationService.GetResource("Admin.System.Warnings.DirectoryPermission.Wrong"), WindowsIdentity.GetCurrent().Name, dir) }); dirPermissionsOk = false; } } if (dirPermissionsOk) { model.Add(new SystemWarningModel { Level = SystemWarningLevel.Pass, Text = _localizationService.GetResource("Admin.System.Warnings.DirectoryPermission.OK") }); } var filePermissionsOk = true; var filesToCheck = FilePermissionHelper.GetFilesWrite(); foreach (string file in filesToCheck) { if (!FilePermissionHelper.CheckPermissions(file, false, true, true, true)) { model.Add(new SystemWarningModel { Level = SystemWarningLevel.Warning, Text = string.Format(_localizationService.GetResource("Admin.System.Warnings.FilePermission.Wrong"), WindowsIdentity.GetCurrent().Name, file) }); filePermissionsOk = false; } } if (filePermissionsOk) { model.Add(new SystemWarningModel { Level = SystemWarningLevel.Pass, Text = _localizationService.GetResource("Admin.System.Warnings.FilePermission.OK") }); } return(View(model)); }
public async Task <IActionResult> Configure() { var model = new FeedGoogleShoppingModel(); model.ProductPictureSize = _GoogleShoppingSettings.ProductPictureSize; model.PassShippingInfoWeight = _GoogleShoppingSettings.PassShippingInfoWeight; model.PassShippingInfoDimensions = _GoogleShoppingSettings.PassShippingInfoDimensions; model.PricesConsiderPromotions = _GoogleShoppingSettings.PricesConsiderPromotions; //stores model.StoreId = _GoogleShoppingSettings.StoreId; model.AvailableStores.Add(new SelectListItem { Text = _localizationService.GetResource("Admin.Common.All"), Value = "" }); foreach (var s in await _storeService.GetAllStores()) { model.AvailableStores.Add(new SelectListItem { Text = s.Shortcut, Value = s.Id.ToString() }); } //currencies model.CurrencyId = _GoogleShoppingSettings.CurrencyId; foreach (var c in await _currencyService.GetAllCurrencies()) { model.AvailableCurrencies.Add(new SelectListItem { Text = c.Name, Value = c.Id.ToString() }); } //Google categories model.DefaultGoogleCategory = _GoogleShoppingSettings.DefaultGoogleCategory; model.AvailableGoogleCategories.Add(new SelectListItem { Text = "Select a category", Value = "" }); foreach (var gc in await _googleService.GetTaxonomyList()) { model.AvailableGoogleCategories.Add(new SelectListItem { Text = gc, Value = gc }); } //file paths foreach (var store in await _storeService.GetAllStores()) { var appPath = CommonHelper.MapPath("wwwroot/content/files/exportimport"); var localFilePath = System.IO.Path.Combine(appPath, store.Id + "-" + _GoogleShoppingSettings.StaticFileName); if (System.IO.File.Exists(localFilePath)) { model.GeneratedFiles.Add(new FeedGoogleShoppingModel.GeneratedFileModel { StoreName = store.Shortcut, FileUrl = string.Format("{0}content/files/exportimport/{1}-{2}", _webHelper.GetStoreLocation(false), store.Id, _GoogleShoppingSettings.StaticFileName) }); } } return(View("~/Plugins/Feed.GoogleShopping/Views/FeedGoogleShopping/Configure.cshtml", model)); }