/// <summary>
 /// Get address line
 /// </summary>
 /// <param name="address">Address</param>
 /// <returns>Address line</returns>
 private string GetAddressLine(Address address)
 {
     return(WebUtility.HtmlEncode($"{(!string.IsNullOrEmpty(address.Address1) ? $"{address.Address1}, " : string.Empty)}" +
                                  $"{(!string.IsNullOrEmpty(address.Address2) ? $"{address.Address2}, " : string.Empty)}" +
                                  $"{(!string.IsNullOrEmpty(address.City) ? $"{address.City}, " : string.Empty)}" +
                                  $"{(_stateProvinceService.GetStateProvinceByAddress(address) is StateProvince stateProvince ? $"{stateProvince.Name}, " : string.Empty)}" +
                                  $"{(_countryService.GetCountryByAddress(address) is Country country ? $"{country.Name}, " : string.Empty)}" +
                                  $"{(!string.IsNullOrEmpty(address.ZipPostalCode) ? $"{address.ZipPostalCode}, " : string.Empty)}"
                                  .TrimEnd(' ').TrimEnd(',')));
 }
Esempio n. 2
0
        public static OrderRequest MollieOrderRequest(
            PostProcessPaymentRequest postProcessPaymentRequest,
            List <OrderLineRequest> orderLines,
            string redirectUrl,
            Address orderAddress,
            Address billingAddress,
            Core.Domain.Directory.Currency selectCurrency,
            IStateProvinceService stateProvinceService,
            ICountryService countryService,
            string url)
        {
            var orderRequest = new OrderRequest()
            {
                Amount      = new Amount(selectCurrency.CurrencyCode, postProcessPaymentRequest.Order.OrderTotal),
                OrderNumber = postProcessPaymentRequest.Order.CustomOrderNumber,
                Methods     = new List <string>()
                {
                    PaymentMethod.Ideal,
                    PaymentMethod.CreditCard,
                    PaymentMethod.PayPal,
                    PaymentMethod.Bancontact
                },
                Lines          = orderLines,
                BillingAddress = new OrderAddressDetails()
                {
                    GivenName       = billingAddress?.FirstName,
                    FamilyName      = billingAddress?.LastName,
                    Email           = billingAddress?.Email,
                    City            = billingAddress?.City,
                    Country         = countryService.GetCountryByAddress(orderAddress)?.TwoLetterIsoCode,
                    PostalCode      = billingAddress?.ZipPostalCode,
                    Region          = stateProvinceService.GetStateProvinceByAddress(orderAddress)?.Abbreviation,
                    StreetAndNumber = billingAddress?.Address1
                },
                ShippingAddress = new OrderAddressDetails()
                {
                    GivenName       = orderAddress?.FirstName,
                    FamilyName      = orderAddress?.LastName,
                    Email           = orderAddress?.Email,
                    City            = orderAddress?.City,
                    Country         = countryService.GetCountryByAddress(orderAddress)?.TwoLetterIsoCode,
                    PostalCode      = orderAddress?.ZipPostalCode,
                    Region          = stateProvinceService.GetStateProvinceByAddress(orderAddress)?.Abbreviation,
                    StreetAndNumber = orderAddress?.Address1
                },
                ShopperCountryMustMatchBillingCountry = true,
                RedirectUrl = redirectUrl,
                Locale      = Locale.nl_NL,
                WebhookUrl  = url + "/PaymentMolliePayments/MollieWebHook"
            };

            return(orderRequest);
        }
        private void LoadingShipping(PostProcessPaymentRequest postProcessPaymentRequest, PaymentRequest payment)
        {
            var customer        = _customerService.GetCustomerById(postProcessPaymentRequest.Order.CustomerId);
            var shippingAddress = _customerService.GetCustomerShippingAddress(customer);

            payment.Shipping = new Shipping();
            payment.Shipping.ShippingType = ShippingType.NotSpecified;
            Address adress = new Address();

            adress.Complement = string.Empty;
            adress.District   = string.Empty;
            adress.Number     = string.Empty;
            if (shippingAddress != null)
            {
                var country       = _countryService.GetCountryByAddress(shippingAddress);
                var stateProvince = _stateProvinceService.GetStateProvinceByAddress(shippingAddress);

                adress.City       = shippingAddress.City;
                adress.Country    = country.Name;
                adress.PostalCode = shippingAddress.ZipPostalCode;
                adress.State      = stateProvince.Name;
                adress.Street     = shippingAddress.Address1;
            }
            payment.Shipping.Cost = Math.Round(GetConvertedRate(postProcessPaymentRequest.Order.OrderShippingInclTax), 2);
        }
        /// <summary>
        /// Prepare paged affiliate list model
        /// </summary>
        /// <param name="searchModel">Affiliate search model</param>
        /// <returns>Affiliate list model</returns>
        public virtual AffiliateListModel PrepareAffiliateListModel(AffiliateSearchModel searchModel)
        {
            if (searchModel == null)
            {
                throw new ArgumentNullException(nameof(searchModel));
            }

            //get affiliates
            var affiliates = _affiliateService.GetAllAffiliates(searchModel.SearchFriendlyUrlName,
                                                                searchModel.SearchFirstName,
                                                                searchModel.SearchLastName,
                                                                searchModel.LoadOnlyWithOrders,
                                                                searchModel.OrdersCreatedFromUtc,
                                                                searchModel.OrdersCreatedToUtc,
                                                                searchModel.Page - 1, searchModel.PageSize, true);

            //prepare list model
            var model = new AffiliateListModel().PrepareToGrid(searchModel, affiliates, () =>
            {
                //fill in model values from the entity
                return(affiliates.Select(affiliate =>
                {
                    var address = _addressService.GetAddressById(affiliate.AddressId);

                    var affiliateModel = affiliate.ToModel <AffiliateModel>();
                    affiliateModel.Address = address.ToModel <AddressModel>();
                    affiliateModel.Address.CountryName = _countryService.GetCountryByAddress(address)?.Name;
                    affiliateModel.Address.StateProvinceName = _stateProvinceService.GetStateProvinceByAddress(address)?.Name;

                    return affiliateModel;
                }));
            });

            return(model);
        }
        /// <summary>
        /// Create common query parameters for the request
        /// </summary>
        /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
        /// <returns>Created query parameters</returns>
        private IDictionary <string, string> CreateQueryParameters(PostProcessPaymentRequest postProcessPaymentRequest)
        {
            //get store location
            var storeLocation = _webHelper.GetStoreLocation();

            //choosing correct order address
            var orderAddress = _addressService.GetAddressById(
                (postProcessPaymentRequest.Order.PickupInStore ? postProcessPaymentRequest.Order.PickupAddressId : postProcessPaymentRequest.Order.ShippingAddressId) ?? 0);

            //create query parameters
            return(new Dictionary <string, string>
            {
                //PayPal ID or an email address associated with your PayPal account
                ["business"] = _payPalStandardPaymentSettings.BusinessEmail,

                //the character set and character encoding
                ["charset"] = "utf-8",

                //set return method to "2" (the customer redirected to the return URL by using the POST method, and all payment variables are included)
                ["rm"] = "2",

                ["bn"] = PayPalHelper.NopCommercePartnerCode,
                ["currency_code"] = _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId)?.CurrencyCode,

                //order identifier
                ["invoice"] = postProcessPaymentRequest.Order.CustomOrderNumber,
                ["custom"] = postProcessPaymentRequest.Order.OrderGuid.ToString(),

                //PDT, IPN and cancel URL
                ["return"] = $"{storeLocation}Plugins/PaymentPayPalStandard/PDTHandler",
                ["notify_url"] = $"{storeLocation}Plugins/PaymentPayPalStandard/IPNHandler",
                ["cancel_return"] = $"{storeLocation}Plugins/PaymentPayPalStandard/CancelOrder",

                //shipping address, if exists
                ["no_shipping"] = postProcessPaymentRequest.Order.ShippingStatus == ShippingStatus.ShippingNotRequired ? "1" : "2",
                ["address_override"] = postProcessPaymentRequest.Order.ShippingStatus == ShippingStatus.ShippingNotRequired ? "0" : "1",
                ["first_name"] = orderAddress?.FirstName,
                ["last_name"] = orderAddress?.LastName,
                ["address1"] = orderAddress?.Address1,
                ["address2"] = orderAddress?.Address2,
                ["city"] = orderAddress?.City,
                ["state"] = _stateProvinceService.GetStateProvinceByAddress(orderAddress)?.Abbreviation,
                ["country"] = _countryService.GetCountryByAddress(orderAddress)?.TwoLetterIsoCode,
                ["zip"] = orderAddress?.ZipPostalCode,
                ["email"] = orderAddress?.Email
            });
        }
Esempio n. 6
0
        /// <summary>
        /// Get pickup points for the address
        /// </summary>
        /// <param name="address">Address</param>
        /// <returns>Represents a response of getting pickup points</returns>
        public GetPickupPointsResponse GetPickupPoints(Address address)
        {
            var result = new GetPickupPointsResponse();

            foreach (var point in _storePickupPointService.GetAllStorePickupPoints(_storeContext.CurrentStore.Id))
            {
                var pointAddress = _addressService.GetAddressById(point.AddressId);
                if (pointAddress == null)
                {
                    continue;
                }

                result.PickupPoints.Add(new PickupPoint
                {
                    Id                 = point.Id.ToString(),
                    Name               = point.Name,
                    Description        = point.Description,
                    Address            = pointAddress.Address1,
                    City               = pointAddress.City,
                    County             = pointAddress.County,
                    StateAbbreviation  = _stateProvinceService.GetStateProvinceByAddress(pointAddress)?.Abbreviation ?? string.Empty,
                    CountryCode        = _countryService.GetCountryByAddress(pointAddress)?.TwoLetterIsoCode ?? string.Empty,
                    ZipPostalCode      = pointAddress.ZipPostalCode,
                    OpeningHours       = point.OpeningHours,
                    PickupFee          = point.PickupFee,
                    DisplayOrder       = point.DisplayOrder,
                    ProviderSystemName = PluginDescriptor.SystemName,
                    Latitude           = point.Latitude,
                    Longitude          = point.Longitude,
                    TransitDays        = point.TransitDays
                });
            }

            if (!result.PickupPoints.Any())
            {
                result.AddError(_localizationService.GetResource("Plugins.Pickup.PickupInStore.NoPickupPoints"));
            }

            return(result);
        }
Esempio n. 7
0
        /// <summary>
        /// Prepare address model
        /// </summary>
        /// <param name="model">Address model</param>
        /// <param name="address">Address entity</param>
        /// <param name="excludeProperties">Whether to exclude populating of model properties from the entity</param>
        /// <param name="addressSettings">Address settings</param>
        /// <param name="loadCountries">Countries loading function; pass null if countries do not need to load</param>
        /// <param name="prePopulateWithCustomerFields">Whether to populate model properties with the customer fields (used with the customer entity)</param>
        /// <param name="customer">Customer entity; required if prePopulateWithCustomerFields is true</param>
        /// <param name="overrideAttributesXml">Overridden address attributes in XML format; pass null to use CustomAttributes of the address entity</param>
        public virtual void PrepareAddressModel(AddressModel model,
                                                Address address, bool excludeProperties,
                                                AddressSettings addressSettings,
                                                Func <IList <Country> > loadCountries = null,
                                                bool prePopulateWithCustomerFields    = false,
                                                Customer customer            = null,
                                                string overrideAttributesXml = "")
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            if (addressSettings == null)
            {
                throw new ArgumentNullException(nameof(addressSettings));
            }

            if (!excludeProperties && address != null)
            {
                model.Id          = address.Id;
                model.FirstName   = address.FirstName;
                model.LastName    = address.LastName;
                model.Email       = address.Email;
                model.Company     = address.Company;
                model.CountryId   = address.CountryId;
                model.CountryName = _countryService.GetCountryByAddress(address) is Country country?_localizationService.GetLocalized(country, x => x.Name) : null;

                model.StateProvinceId   = address.StateProvinceId;
                model.StateProvinceName = _stateProvinceService.GetStateProvinceByAddress(address) is StateProvince stateProvince?_localizationService.GetLocalized(stateProvince, x => x.Name) : null;

                model.County        = address.County;
                model.City          = address.City;
                model.Address1      = address.Address1;
                model.Address2      = address.Address2;
                model.ZipPostalCode = address.ZipPostalCode;
                model.PhoneNumber   = address.PhoneNumber;
                model.FaxNumber     = address.FaxNumber;
            }

            if (address == null && prePopulateWithCustomerFields)
            {
                if (customer == null)
                {
                    throw new Exception("Customer cannot be null when prepopulating an address");
                }
                model.Email         = customer.Email;
                model.FirstName     = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.FirstNameAttribute);
                model.LastName      = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.LastNameAttribute);
                model.Company       = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.CompanyAttribute);
                model.Address1      = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.StreetAddressAttribute);
                model.Address2      = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.StreetAddress2Attribute);
                model.ZipPostalCode = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.ZipPostalCodeAttribute);
                model.City          = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.CityAttribute);
                model.County        = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.CountyAttribute);
                //TODO: ignore country and state for prepopulation. it can cause some issues when posting pack with errors, etc
                //model.CountryId = _genericAttributeService.GetAttribute<int>(SystemCustomerAttributeNames.CountryId);
                //model.StateProvinceId = _genericAttributeService.GetAttribute<int>(SystemCustomerAttributeNames.StateProvinceId);
                model.PhoneNumber = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.PhoneAttribute);
                model.FaxNumber   = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.FaxAttribute);
            }

            //countries and states
            if (addressSettings.CountryEnabled && loadCountries != null)
            {
                var countries = loadCountries();

                if (_addressSettings.PreselectCountryIfOnlyOne && countries.Count == 1)
                {
                    model.CountryId = countries[0].Id;
                }
                else
                {
                    model.AvailableCountries.Add(new SelectListItem {
                        Text = _localizationService.GetResource("Address.SelectCountry"), Value = "0"
                    });
                }

                foreach (var c in countries)
                {
                    model.AvailableCountries.Add(new SelectListItem
                    {
                        Text     = _localizationService.GetLocalized(c, x => x.Name),
                        Value    = c.Id.ToString(),
                        Selected = c.Id == model.CountryId
                    });
                }

                if (addressSettings.StateProvinceEnabled)
                {
                    var languageId = EngineContext.Current.Resolve <IWorkContext>().WorkingLanguage.Id;
                    var states     = _stateProvinceService
                                     .GetStateProvincesByCountryId(model.CountryId.HasValue ? model.CountryId.Value : 0, languageId)
                                     .ToList();
                    if (states.Any())
                    {
                        model.AvailableStates.Add(new SelectListItem {
                            Text = _localizationService.GetResource("Address.SelectState"), Value = "0"
                        });

                        foreach (var s in states)
                        {
                            model.AvailableStates.Add(new SelectListItem
                            {
                                Text     = _localizationService.GetLocalized(s, x => x.Name),
                                Value    = s.Id.ToString(),
                                Selected = (s.Id == model.StateProvinceId)
                            });
                        }
                    }
                    else
                    {
                        var anyCountrySelected = model.AvailableCountries.Any(x => x.Selected);
                        model.AvailableStates.Add(new SelectListItem
                        {
                            Text  = _localizationService.GetResource(anyCountrySelected ? "Address.OtherNonUS" : "Address.SelectState"),
                            Value = "0"
                        });
                    }
                }
            }

            //form fields
            model.CompanyEnabled         = addressSettings.CompanyEnabled;
            model.CompanyRequired        = addressSettings.CompanyRequired;
            model.StreetAddressEnabled   = addressSettings.StreetAddressEnabled;
            model.StreetAddressRequired  = addressSettings.StreetAddressRequired;
            model.StreetAddress2Enabled  = addressSettings.StreetAddress2Enabled;
            model.StreetAddress2Required = addressSettings.StreetAddress2Required;
            model.ZipPostalCodeEnabled   = addressSettings.ZipPostalCodeEnabled;
            model.ZipPostalCodeRequired  = addressSettings.ZipPostalCodeRequired;
            model.CityEnabled            = addressSettings.CityEnabled;
            model.CityRequired           = addressSettings.CityRequired;
            model.CountyEnabled          = addressSettings.CountyEnabled;
            model.CountyRequired         = addressSettings.CountyRequired;
            model.CountryEnabled         = addressSettings.CountryEnabled;
            model.StateProvinceEnabled   = addressSettings.StateProvinceEnabled;
            model.PhoneEnabled           = addressSettings.PhoneEnabled;
            model.PhoneRequired          = addressSettings.PhoneRequired;
            model.FaxEnabled             = addressSettings.FaxEnabled;
            model.FaxRequired            = addressSettings.FaxRequired;

            //customer attribute services
            if (_addressAttributeService != null && _addressAttributeParser != null)
            {
                PrepareCustomAddressAttributes(model, address, overrideAttributesXml);
            }
            if (_addressAttributeFormatter != null && address != null)
            {
                model.FormattedCustomAddressAttributes = _addressAttributeFormatter.FormatAttributes(address.CustomAttributes);
            }
        }
Esempio n. 8
0
        /// <summary>
        /// Post process payment (used by payment gateways that require redirecting to a third-party URL)
        /// </summary>
        /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
        public void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
        {
            //choosing correct order address
            var orderAddress = _addressService.GetAddressById(
                (postProcessPaymentRequest.Order.PickupInStore ? postProcessPaymentRequest.Order.PickupAddressId : postProcessPaymentRequest.Order.ShippingAddressId) ?? 0);
            var orderShippingAddress = _addressService.GetAddressById((int)postProcessPaymentRequest.Order.ShippingAddressId);

            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());
            remotePostHelper.Add("txnid", orderId.ToString());
            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(),
                                                               postProcessPaymentRequest.Order.Id.ToString(), postProcessPaymentRequest.Order.OrderTotal.ToString(new CultureInfo("en-US", false).NumberFormat),
                                                               "productinfo", orderAddress?.FirstName,
                                                               orderAddress?.Email.ToString(), _PayuPaymentSettings.Key));


            //Billing details
            remotePostHelper.Add("firstname", orderAddress?.FirstName.ToString());
            remotePostHelper.Add("billing_cust_address", orderAddress?.Address1);
            remotePostHelper.Add("phone", orderAddress?.PhoneNumber);
            remotePostHelper.Add("email", orderAddress?.Email.ToString());
            remotePostHelper.Add("billing_cust_city", orderAddress?.City);
            var billingStateProvince = _stateProvinceService.GetStateProvinceByAddress(orderAddress)?.Abbreviation;

            if (billingStateProvince != null)
            {
                remotePostHelper.Add("billing_cust_state", _stateProvinceService.GetStateProvinceByAddress(orderAddress)?.Abbreviation);
            }
            else
            {
                remotePostHelper.Add("billing_cust_state", "");
            }
            remotePostHelper.Add("billing_zip_code", orderAddress?.ZipPostalCode);
            var billingCountry = _countryService.GetCountryByAddress(orderAddress)?.TwoLetterIsoCode;

            if (billingCountry != null)
            {
                remotePostHelper.Add("billing_cust_country", _countryService.GetCountryByAddress(orderAddress)?.TwoLetterIsoCode);
            }
            else
            {
                remotePostHelper.Add("billing_cust_country", "");
            }

            //Delivery details

            if (postProcessPaymentRequest.Order.ShippingStatus != ShippingStatus.ShippingNotRequired)
            {
                remotePostHelper.Add("delivery_cust_name", orderShippingAddress.FirstName);
                remotePostHelper.Add("delivery_cust_address", orderShippingAddress.Address1);
                remotePostHelper.Add("delivery_cust_notes", string.Empty);
                remotePostHelper.Add("delivery_cust_tel", orderShippingAddress.PhoneNumber);
                remotePostHelper.Add("delivery_cust_city", orderShippingAddress.City);
                var deliveryStateProvince = _stateProvinceService.GetStateProvinceByAddress(orderShippingAddress);
                if (deliveryStateProvince != null)
                {
                    remotePostHelper.Add("delivery_cust_state", deliveryStateProvince.Abbreviation);
                }
                else
                {
                    remotePostHelper.Add("delivery_cust_state", "");
                }
                remotePostHelper.Add("delivery_zip_code", orderShippingAddress.ZipPostalCode);
                var deliveryCountry = _countryService.GetCountryByAddress(orderShippingAddress); // 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);
            remotePostHelper.Post();
        }
        /// <summary>
        /// Invoke view component
        /// </summary>
        /// <param name="widgetZone">Widget zone name</param>
        /// <param name="additionalData">Additional data</param>
        /// <returns>View component result</returns>
        public IViewComponentResult Invoke(string widgetZone, object additionalData)
        {
            var model = new PaymentInfoModel
            {
                //whether current customer is guest
                IsGuest = _customerService.IsGuest(_workContext.CurrentCustomer),

                //get postal code from the billing address or from the shipping one
                PostalCode = _customerService.GetCustomerBillingAddress(_workContext.CurrentCustomer)?.ZipPostalCode
                             ?? _customerService.GetCustomerShippingAddress(_workContext.CurrentCustomer)?.ZipPostalCode
            };

            //whether customer already has stored cards in current store
            var storeId    = _storeContext.CurrentStore.Id;
            var customerId = _genericAttributeService
                             .GetAttribute <string>(_workContext.CurrentCustomer, SquarePaymentDefaults.CustomerIdAttribute) ?? string.Empty;
            var customer = _squarePaymentManager.GetCustomer(customerId, storeId);

            if (customer?.Cards != null)
            {
                var cardNumberMask = _localizationService.GetResource("Plugins.Payments.Square.Fields.StoredCard.Mask");
                model.StoredCards = customer.Cards
                                    .Select(card => new SelectListItem {
                    Text = string.Format(cardNumberMask, card.Last4), Value = card.Id
                })
                                    .ToList();
            }

            //add the special item for 'select card' with empty GUID value
            if (model.StoredCards.Any())
            {
                var selectCardText = _localizationService.GetResource("Plugins.Payments.Square.Fields.StoredCard.SelectCard");
                model.StoredCards.Insert(0, new SelectListItem {
                    Text = selectCardText, Value = Guid.Empty.ToString()
                });
            }

            //set verfication details
            if (_squarePaymentSettings.Use3ds)
            {
                var cart = _shoppingCartService.GetShoppingCart(_workContext.CurrentCustomer,
                                                                ShoppingCartType.ShoppingCart, _storeContext.CurrentStore.Id);
                model.OrderTotal = _orderTotalCalculationService.GetShoppingCartTotal(cart, false, false) ?? decimal.Zero;

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

                var billingAddress = _customerService.GetCustomerBillingAddress(_workContext.CurrentCustomer);
                var country        = _countryService.GetCountryByAddress(billingAddress);
                var stateProvince  = _stateProvinceService.GetStateProvinceByAddress(billingAddress);

                model.BillingFirstName  = billingAddress?.FirstName;
                model.BillingLastName   = billingAddress?.LastName;
                model.BillingEmail      = billingAddress?.Email;
                model.BillingCountry    = country?.TwoLetterIsoCode;
                model.BillingState      = stateProvince?.Name;
                model.BillingCity       = billingAddress?.City;
                model.BillingPostalCode = billingAddress?.ZipPostalCode;
            }

            return(View("~/Plugins/Payments.Square/Views/PaymentInfo.cshtml", model));
        }
Esempio n. 10
0
        private void ProcessOrderEvent(Order order, bool add)
        {
            try
            {
                //settings per store
                var store = _storeService.GetStoreById(order.StoreId) ?? _storeContext.CurrentStore;
                var googleAnalyticsSettings = _settingService.LoadSetting <GoogleAnalyticsSettings>(store.Id);

                var request = new GoogleRequest
                {
                    AccountCode = googleAnalyticsSettings.GoogleId,
                    Culture     = "en-US",
                    HostName    = new Uri(_webHelper.GetThisPageUrl(false)).Host,
                    PageTitle   = add ? "AddTransaction" : "CancelTransaction"
                };

                var orderId       = order.CustomOrderNumber;
                var orderShipping = googleAnalyticsSettings.IncludingTax ? order.OrderShippingInclTax : order.OrderShippingExclTax;
                var orderTax      = order.OrderTax;
                var orderTotal    = order.OrderTotal;
                if (!add)
                {
                    orderShipping = -orderShipping;
                    orderTax      = -orderTax;
                    orderTotal    = -orderTotal;
                }

                var billingAddress = _addressService.GetAddressById(order.BillingAddressId);

                var trans = new Transaction(FixIllegalJavaScriptChars(orderId),
                                            FixIllegalJavaScriptChars(billingAddress.City),
                                            _countryService.GetCountryByAddress(billingAddress) is Country country ? FixIllegalJavaScriptChars(country.Name) : string.Empty,
                                            _stateProvinceService.GetStateProvinceByAddress(billingAddress) is StateProvince stateProvince ? FixIllegalJavaScriptChars(stateProvince.Name) : string.Empty,
                                            store.Name,
                                            orderShipping,
                                            orderTax,
                                            orderTotal);

                foreach (var item in _orderService.GetOrderItems(order.Id))
                {
                    var product = _productService.GetProductById(item.ProductId);
                    //get category
                    var category  = _categoryService.GetCategoryById(_categoryService.GetProductCategoriesByProductId(product.Id).FirstOrDefault()?.CategoryId ?? 0)?.Name;
                    var unitPrice = googleAnalyticsSettings.IncludingTax ? item.UnitPriceInclTax : item.UnitPriceExclTax;
                    var qty       = item.Quantity;
                    if (!add)
                    {
                        qty = -qty;
                    }

                    var sku = _productService.FormatSku(product, item.AttributesXml);
                    if (string.IsNullOrEmpty(sku))
                    {
                        sku = product.Id.ToString();
                    }

                    var productItem = new TransactionItem(FixIllegalJavaScriptChars(orderId),
                                                          FixIllegalJavaScriptChars(sku),
                                                          FixIllegalJavaScriptChars(product.Name),
                                                          unitPrice,
                                                          qty,
                                                          FixIllegalJavaScriptChars(category));

                    trans.Items.Add(productItem);
                }

                request.SendRequest(trans, _httpClientFactory.CreateClient(NopHttpDefaults.DefaultHttpClient));
            }
            catch (Exception ex)
            {
                _logger.InsertLog(LogLevel.Error, "Google Analytics. Error canceling transaction from server side", ex.ToString());
            }
        }
        /// <summary>
        /// Get Checkout Request
        /// </summary>
        /// <param name="postProcessPaymentRequest">Order reference id</param>
        /// <returns>The asynchronous task whose result contains the checkout payload</returns>
        public string GetCheckoutRequest(PostProcessPaymentRequest postProcessPaymentRequest)
        {
            _genericAttributeService.SaveAttribute <string>(postProcessPaymentRequest.Order,
                                                            SezzleHelper.OrderReferenceId,
                                                            postProcessPaymentRequest.Order.OrderGuid.ToString());

            //get store location
            var storeLocation   = _webHelper.GetStoreLocation();
            var currentCustomer = EngineContext.Current.Resolve <IWorkContext>().CurrentCustomer;

            var billingAddress  = _addressService.GetAddressById(postProcessPaymentRequest.Order.BillingAddressId);
            var shippingAddress = _addressService.GetAddressById(postProcessPaymentRequest.Order.ShippingAddressId ?? 0);

            var orderItems = new List <ItemPayload>();

            foreach (var item in _orderService.GetOrderItems(postProcessPaymentRequest.Order.Id))
            {
                var product = _productService.GetProductById(item.ProductId);
                orderItems.Add(
                    new ItemPayload
                {
                    Name     = product.Name,
                    Sku      = product.Sku,
                    Quantity = item.Quantity,
                    Price    = new PricePayload
                    {
                        AmountInCents = (long)Math.Round((item.PriceExclTax * 100), 2),
                        Currency      = _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId)?.CurrencyCode
                    }
                }
                    );
            }

            var request = new ObtainCheckoutRequest
            {
                AmountInCents       = (long)Math.Round((postProcessPaymentRequest.Order.OrderTotal * 100), 2),
                OrderDescription    = SezzleHelper.OrderDescription,
                CurrencyCode        = _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId)?.CurrencyCode,
                OrderReferenceId    = postProcessPaymentRequest.Order.OrderGuid.ToString(),
                CheckoutCancelUrl   = new Uri($"{storeLocation}Plugins/PaymentSezzle/CancelOrder?reference_id={postProcessPaymentRequest.Order.OrderGuid.ToString()}"),
                CheckoutCompleteUrl = new Uri($"{storeLocation}Plugins/PaymentSezzle/CompleteOrder?reference_id={postProcessPaymentRequest.Order.OrderGuid.ToString()}"),
                CustomerDetails     = new CustomerPayload
                {
                    FirstName = billingAddress?.FirstName,
                    LastName  = billingAddress?.LastName,
                    Email     = currentCustomer.Email,
                    Phone     = billingAddress?.PhoneNumber
                },
                BillingAddress = new AddressPayload
                {
                    Name        = String.Concat(billingAddress?.FirstName, " ", billingAddress?.LastName),
                    Street      = billingAddress?.Address1,
                    Street2     = billingAddress?.Address2,
                    City        = billingAddress?.City,
                    State       = _stateProvinceService.GetStateProvinceByAddress(billingAddress)?.Abbreviation,
                    CountryCode = _countryService.GetCountryByAddress(billingAddress)?.TwoLetterIsoCode,
                    PostalCode  = billingAddress?.ZipPostalCode,
                    PhoneNumber = billingAddress?.PhoneNumber
                },
                ShippingAddress = new AddressPayload
                {
                    Name        = String.Concat(shippingAddress?.FirstName, " ", shippingAddress?.LastName),
                    Street      = shippingAddress?.Address1,
                    Street2     = shippingAddress?.Address2,
                    City        = shippingAddress?.City,
                    State       = _stateProvinceService.GetStateProvinceByAddress(shippingAddress)?.Abbreviation,
                    CountryCode = _countryService.GetCountryByAddress(shippingAddress)?.TwoLetterIsoCode,
                    PostalCode  = shippingAddress?.ZipPostalCode,
                    PhoneNumber = shippingAddress?.PhoneNumber
                },
                RequiresShippingInfo = false,
                Items     = orderItems,
                Discounts = new List <DiscountPayload>
                {
                    new DiscountPayload
                    {
                        Name   = postProcessPaymentRequest.Order.OrderDiscount.ToString(),
                        Amount = new PricePayload
                        {
                            AmountInCents = (long)Math.Round((postProcessPaymentRequest.Order.OrderDiscount * 100), 2),
                            Currency      = _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId)?.CurrencyCode
                        }
                    }
                },
                TaxAmount = new PricePayload
                {
                    AmountInCents = (long)Math.Round((postProcessPaymentRequest.Order.OrderTax * 100), 2),
                    Currency      = _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId)?.CurrencyCode
                },
                ShippingAmount = new PricePayload
                {
                    AmountInCents = (long)Math.Round((postProcessPaymentRequest.Order.OrderShippingExclTax * 100), 2),
                    Currency      = _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId)?.CurrencyCode
                },
                MerchantCompletes = true
            };

            var jsonRequest = JsonConvert.SerializeObject(request);

            return(jsonRequest);
        }
Esempio n. 12
0
        public void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
        {
            /*
             * Dati transazione inviati verso GestPay
             * Alcuni dei parametri "importanti/principali" per creazione della stringa
             * "ShopLogin"         :VarChar (30) - Obbligatorio - Codice Esercente (Shop Login)
             * "Currency"          :Num (3) - Obbligatorio - Codice Identificativo della divisa per l'importo della transazione
             * "Amount"            :Num (9) - Obbligatorio - [ll separatore delle migliaia non deve essere inserito. I decimali (max 2 cifre) sono opzionali ed il separatore è il punto.]
             * "ShopTransactionID" :VarChar (50) - Obbligatorio - Identificativo attribuito alla transazione dall'esercente.
             * "BuyerName"         :VarChar (50) - Facoltativo - Nome e cognome dell'acquirente
             * "BuyerEmail"        :VarChar (50) - Facoltativo - Indirizzo e-mail dell'acquirente
             * "Language"          :Num (2) - Facoltativo - Codice che identifica la lingua utilizzata nella comunicazione con l'acquirente (vedi tabella Codici lingua).
             */
            var encryptedString  = "";
            var errorDescription = "";

            var nopBillingAddress = _addressService.GetAddressById(postProcessPaymentRequest.Order.BillingAddressId);

            var amount            = Math.Round(postProcessPaymentRequest.Order.OrderTotal, 2);
            var shopTransactionId = postProcessPaymentRequest.Order.OrderGuid.ToString();
            var buyerName         = String.Format(
                "{0} {1}",
                nopBillingAddress?.FirstName,
                nopBillingAddress?.LastName
                );

            var endpoint        = _gestPayPaymentSettings.UseSandbox ? EndpointConfiguration.WSCryptDecryptSoap12Test : EndpointConfiguration.WSCryptDecryptSoap12;
            var objCryptDecrypt = new WSCryptDecryptSoapClient(endpoint);

            var billingCountry       = _countryService.GetCountryById(Convert.ToInt32(nopBillingAddress.CountryId));
            var billingStateProvince = _stateProvinceService.GetStateProvinceByAddress(nopBillingAddress);

            Address       nopShippingAddress    = null;
            Country       shippingCountry       = null;
            StateProvince shippingStateProvince = null;

            if (postProcessPaymentRequest.Order.ShippingAddressId != null)
            {
                nopShippingAddress    = _addressService.GetAddressById((int)postProcessPaymentRequest.Order.ShippingAddressId);
                shippingCountry       = _countryService.GetCountryById((int)nopShippingAddress.CountryId);
                shippingStateProvince = _stateProvinceService.GetStateProvinceByAddress(nopShippingAddress);
            }

            XmlNode xmlResponse;
            EcommGestpayPaymentDetails paymentDetails = new EcommGestpayPaymentDetails();

            if (_gestPayPaymentSettings.EnableGuaranteedPayment)
            {
                FraudPrevention fraudPrevention = new FraudPrevention();
                fraudPrevention.BeaconSessionID  = _httpContextAccessor.HttpContext.Session.Id;
                fraudPrevention.SubmitForReview  = "1";
                fraudPrevention.OrderDateTime    = postProcessPaymentRequest.Order.CreatedOnUtc.ToString();
                fraudPrevention.Source           = "desktop_web";
                fraudPrevention.SubmissionReason = "rule_decision";
                fraudPrevention.VendorName       = _storeContext.CurrentStore.Name;
                paymentDetails.FraudPrevention   = fraudPrevention;

                //var logger = Nop.Core.Infrastructure.EngineContext.Current.Resolve<Nop.Services.Logging.ILogger>();
                //logger.Information("Gestpay BeaconId = " + _httpContextAccessor.HttpContext.Session.Id);

                var            customer       = _customerService.GetCustomerById(postProcessPaymentRequest.Order.CustomerId);
                CustomerDetail customerDetail = new CustomerDetail();
                customerDetail.PrimaryEmail       = nopBillingAddress?.Email;
                customerDetail.MerchantCustomerID = postProcessPaymentRequest.Order.CustomerId.ToString();
                customerDetail.FirstName          = nopBillingAddress?.FirstName;
                customerDetail.Lastname           = nopBillingAddress?.LastName;
                customerDetail.PrimaryPhone       = nopBillingAddress?.PhoneNumber;
                customerDetail.Company            = nopBillingAddress?.Company;
                customerDetail.CreatedAtDate      = customer?.CreatedOnUtc.ToString();
                customerDetail.VerifiedEmail      = "true";
                customerDetail.AccountType        = "normal";
                paymentDetails.CustomerDetail     = customerDetail;

                if (nopShippingAddress != null)
                {
                    ShippingAddress shippingAddress = new ShippingAddress();
                    shippingAddress.ProfileID      = postProcessPaymentRequest.Order.ShippingAddressId.ToString();
                    shippingAddress.FirstName      = nopShippingAddress.FirstName;
                    shippingAddress.Lastname       = nopShippingAddress.LastName;
                    shippingAddress.StreetName     = nopShippingAddress.Address1;
                    shippingAddress.Streetname2    = nopShippingAddress.Address2;
                    shippingAddress.City           = nopShippingAddress.City;
                    shippingAddress.ZipCode        = nopShippingAddress.ZipPostalCode;
                    shippingAddress.State          = shippingStateProvince?.Name;
                    shippingAddress.CountryCode    = shippingCountry?.TwoLetterIsoCode;
                    shippingAddress.Email          = nopShippingAddress.Email;
                    shippingAddress.PrimaryPhone   = nopShippingAddress.PhoneNumber;
                    shippingAddress.Company        = nopShippingAddress.Company;
                    shippingAddress.StateCode      = shippingStateProvince?.Abbreviation;
                    paymentDetails.ShippingAddress = shippingAddress;
                }

                BillingAddress billingAddress = new BillingAddress();
                billingAddress.ProfileID      = postProcessPaymentRequest.Order.BillingAddressId.ToString();
                billingAddress.FirstName      = nopBillingAddress?.FirstName;
                billingAddress.Lastname       = nopBillingAddress?.LastName;
                billingAddress.StreetName     = nopBillingAddress?.Address1;
                billingAddress.Streetname2    = nopBillingAddress?.Address2;
                billingAddress.City           = nopBillingAddress?.City;
                billingAddress.ZipCode        = nopBillingAddress?.ZipPostalCode;
                billingAddress.State          = billingStateProvince?.Name;
                billingAddress.CountryCode    = billingCountry?.TwoLetterIsoCode;
                billingAddress.Email          = nopBillingAddress?.Email;
                billingAddress.PrimaryPhone   = nopBillingAddress?.PhoneNumber;
                billingAddress.Company        = nopBillingAddress?.Company;
                billingAddress.StateCode      = billingStateProvince?.Abbreviation;
                paymentDetails.BillingAddress = billingAddress;

                var     orderItems        = _orderService.GetOrderItems(postProcessPaymentRequest.Order.Id);
                var     productDetails    = new List <ProductDetail>();
                decimal itemsTotalInclTax = 0;
                foreach (var item in orderItems)
                {
                    var product = _productService.GetProductById(item.ProductId);

                    if (product != null)
                    {
                        var productDetail = new ProductDetail();
                        productDetail.ProductCode = product.ManufacturerPartNumber;
                        productDetail.SKU         = product.Sku;
                        productDetail.Name        = product.Name;
                        productDetail.Description = product.ShortDescription;
                        productDetail.Quantity    = item.Quantity.ToString();
                        productDetail.Price       = item.PriceInclTax.ToString("0.00", CultureInfo.InvariantCulture);
                        productDetail.UnitPrice   = item.UnitPriceInclTax.ToString("0.00", CultureInfo.InvariantCulture);

                        if ((!product.IsGiftCard && product.IsShipEnabled) || (product.IsGiftCard && product.GiftCardType == Core.Domain.Catalog.GiftCardType.Physical))
                        {
                            productDetail.Type             = "physical";
                            productDetail.RequiresShipping = "true";
                        }
                        else
                        {
                            productDetail.Type             = "digital";
                            productDetail.RequiresShipping = "false";

                            if (product.IsGiftCard)
                            {
                                DigitalGiftCardDetails giftcardDetails = new DigitalGiftCardDetails();
                                var associatedGiftCards = _giftCardService.GetAllGiftCards(postProcessPaymentRequest.Order.Id);
                                foreach (var giftcard in associatedGiftCards)
                                {
                                    giftcardDetails.SenderName      = giftcard.SenderName;
                                    giftcardDetails.DisplayName     = giftcard.SenderName;
                                    giftcardDetails.GreetingMessage = giftcard.Message;

                                    Recipient recipient = new Recipient();
                                    recipient.Email           = giftcard.RecipientEmail;
                                    giftcardDetails.Recipient = recipient;

                                    break;
                                }
                                productDetail.DigitalGiftCardDetails = giftcardDetails;
                            }
                        }

                        productDetail.Vat       = item.PriceInclTax > 0 ? "22" : "0";
                        productDetail.Condition = "new";

                        var productManufacturers = _manufacturerService.GetProductManufacturersByProductId(product.Id);
                        productDetail.Brand = _manufacturerService.GetManufacturerById((int)productManufacturers.FirstOrDefault()?.ManufacturerId)?.Name;
                        //productDetail.DeliveryAt = "home";
                        productDetails.Add(productDetail);

                        itemsTotalInclTax += item.UnitPriceInclTax * item.Quantity;
                    }
                }
                paymentDetails.ProductDetails = productDetails.ToArray();

                IList <DiscountCode> discountCodes = new List <DiscountCode>();
                IList <ShippingLine> shippingLines = new List <ShippingLine>();

                //  Discount on Sub Total
                var subTotalDiscountCode = new DiscountCode();
                subTotalDiscountCode.Code   = "Order subtotal discount";
                subTotalDiscountCode.Amount = postProcessPaymentRequest.Order.OrderSubTotalDiscountInclTax.ToString("0.00", CultureInfo.InvariantCulture);
                discountCodes.Add(subTotalDiscountCode);

                //  Discount on Total
                var discountCode = new DiscountCode();
                discountCode.Code   = "Order total discount";
                discountCode.Amount = postProcessPaymentRequest.Order.OrderDiscount.ToString("0.00", CultureInfo.InvariantCulture);
                discountCodes.Add(discountCode);

                //  Shipping
                var shipping = new ShippingLine();
                shipping.Code  = postProcessPaymentRequest.Order.ShippingRateComputationMethodSystemName;
                shipping.Title = postProcessPaymentRequest.Order.ShippingRateComputationMethodSystemName;
                shipping.Price = postProcessPaymentRequest.Order.OrderShippingInclTax.ToString("0.00", CultureInfo.InvariantCulture);
                shippingLines.Add(shipping);

                //  Additional Charges / GiftWrap / GiftCard
                var extraAdjustment = postProcessPaymentRequest.Order.OrderTotal - (itemsTotalInclTax + postProcessPaymentRequest.Order.OrderShippingInclTax - postProcessPaymentRequest.Order.OrderDiscount - postProcessPaymentRequest.Order.OrderSubTotalDiscountInclTax);
                if (extraAdjustment > 0)
                {
                    var additionalShipping = new ShippingLine();
                    additionalShipping.Code  = "Additional Charge/Giftwrap";
                    additionalShipping.Title = "Additional Charge/Giftwrap";
                    additionalShipping.Price = extraAdjustment.ToString("0.00", CultureInfo.InvariantCulture);
                    shippingLines.Add(additionalShipping);
                }
                else
                {
                    var additionalDiscount = new DiscountCode();
                    additionalDiscount.Code   = "Giftcard/Additional Discount";
                    additionalDiscount.Amount = (extraAdjustment * -1).ToString("0.00", CultureInfo.InvariantCulture);      // * -1 converts into positive number
                    discountCodes.Add(additionalDiscount);
                }

                paymentDetails.DiscountCodes = discountCodes.ToArray();
                paymentDetails.ShippingLines = shippingLines.ToArray();
            }

            //  3DS
            var threeDSTransDetails = new ThreeDSEncryptTransDetails();

            threeDSTransDetails.type = "EC";
            threeDSTransDetails.authenticationAmount = amount.ToString("0.00", CultureInfo.InvariantCulture);

            var threeDSContainer = new EncryptThreeDsContainer();

            threeDSContainer.transTypeReq = "P";
            //threeDSContainer.exemption = "SKIP";  As asked by Gestpay Support

            BuyerDetails buyerDetails = new BuyerDetails();

            ThreeDSBillingAddress threeDSBillingAddress = new ThreeDSBillingAddress();

            threeDSBillingAddress.line1    = nopBillingAddress?.Address1;
            threeDSBillingAddress.line2    = nopBillingAddress?.Address2;
            threeDSBillingAddress.city     = nopBillingAddress?.City;
            threeDSBillingAddress.postCode = nopBillingAddress?.ZipPostalCode;
            threeDSBillingAddress.state    = billingStateProvince?.Name;
            threeDSBillingAddress.country  = billingCountry?.TwoLetterIsoCode;
            buyerDetails.billingAddress    = threeDSBillingAddress;

            if (nopShippingAddress != null)
            {
                ThreeDSShippingAddress threeDSShippingAddress = new ThreeDSShippingAddress();
                threeDSShippingAddress.line1    = nopShippingAddress?.Address1;
                threeDSShippingAddress.line2    = nopShippingAddress?.Address2;
                threeDSShippingAddress.city     = nopShippingAddress?.City;
                threeDSShippingAddress.postCode = nopShippingAddress?.ZipPostalCode;
                threeDSShippingAddress.state    = shippingStateProvince?.Name;
                threeDSShippingAddress.country  = shippingCountry?.TwoLetterIsoCode;
                buyerDetails.shippingAddress    = threeDSShippingAddress;
            }

            buyerDetails.addrMatch = "N";

            threeDSContainer.buyerDetails        = buyerDetails;
            threeDSTransDetails.threeDsContainer = threeDSContainer;

            xmlResponse = objCryptDecrypt.EncryptAsync(
                _gestPayPaymentSettings.ShopOperatorCode,
                _gestPayPaymentSettings.CurrencyUiCcode.ToString(),
                amount.ToString("0.00", CultureInfo.InvariantCulture),
                shopTransactionId,
                "", "", "", buyerName, nopBillingAddress.Email,
                _gestPayPaymentSettings.LanguageCode.ToString(), "",
                "Order Number = " + postProcessPaymentRequest.Order.CustomOrderNumber, "", "", "",
                null,
                null,
                null, "",
                null, null, null, null, null, null, "", null, "", "",
                paymentDetails, _gestPayPaymentSettings.ApiKey, threeDSTransDetails).Result.EncryptResult;

            XmlDocument xmlReturn = new XmlDocument();

            xmlReturn.LoadXml(xmlResponse.OuterXml);

            string errorCode = xmlReturn.SelectSingleNode("/GestPayCryptDecrypt/ErrorCode")?.InnerText;

            if (errorCode == "0")
            {
                encryptedString = xmlReturn.SelectSingleNode("/GestPayCryptDecrypt/CryptDecryptString")?.InnerText;
            }
            else
            {
                //Put error handle code HERE
                errorDescription = xmlReturn.SelectSingleNode("/GestPayCryptDecrypt/ErrorDescription")?.InnerText;
            }

            var builder = new StringBuilder();

            if (!String.IsNullOrEmpty(encryptedString))
            {
                builder.Append(GetGestPayUrl());
                builder.AppendFormat("?a={0}&b={1}", _gestPayPaymentSettings.ShopOperatorCode, encryptedString);
            }
            else
            {
                //Errore
                builder.Append(_webHelper.GetStoreLocation(false) + "Plugins/PaymentGestPay/Error");
                builder.AppendFormat("?type=0&errc={0}&errd={1}", HttpUtility.UrlEncode(errorCode), HttpUtility.UrlEncode(errorDescription));
            }
            _httpContextAccessor.HttpContext.Response.Redirect(builder.ToString());
        }
Esempio n. 13
0
        /// <summary>
        /// Create request details to get shipping rates
        /// </summary>
        /// <param name="shippingOptionRequest">Shipping option request</param>
        /// <param name="saturdayDelivery">Whether to get rates for Saturday Delivery</param>
        /// <returns>Rate request details</returns>
        private UPSRate.RateRequest CreateRateRequest(GetShippingOptionRequest shippingOptionRequest, bool saturdayDelivery = false)
        {
            //set request details
            var request = new UPSRate.RateRequest
            {
                Request = new UPSRate.RequestType
                {
                    //used to define the request type
                    //Shop - the server validates the shipment, and returns rates for all UPS products from the ShipFrom to the ShipTo addresses
                    RequestOption = new[] { "Shop" }
                }
            };

            //prepare addresses details
            var stateCodeTo     = _stateProvinceService.GetStateProvinceByAddress(shippingOptionRequest.ShippingAddress)?.Abbreviation;
            var stateCodeFrom   = shippingOptionRequest.StateProvinceFrom?.Abbreviation;
            var countryCodeFrom = (shippingOptionRequest.CountryFrom ?? _countryService.GetAllCountries().FirstOrDefault())
                                  .TwoLetterIsoCode ?? string.Empty;

            var addressFromDetails = new UPSRate.ShipAddressType
            {
                AddressLine       = new[] { shippingOptionRequest.AddressFrom },
                City              = shippingOptionRequest.CityFrom,
                StateProvinceCode = stateCodeFrom,
                CountryCode       = countryCodeFrom,
                PostalCode        = shippingOptionRequest.ZipPostalCodeFrom
            };
            var addressToDetails = new UPSRate.ShipToAddressType
            {
                AddressLine                 = new[] { shippingOptionRequest.ShippingAddress.Address1, shippingOptionRequest.ShippingAddress.Address2 },
                City                        = shippingOptionRequest.ShippingAddress.City,
                StateProvinceCode           = stateCodeTo,
                CountryCode                 = _countryService.GetCountryByAddress(shippingOptionRequest.ShippingAddress)?.TwoLetterIsoCode,
                PostalCode                  = shippingOptionRequest.ShippingAddress.ZipPostalCode,
                ResidentialAddressIndicator = string.Empty
            };

            //set shipment details
            request.Shipment = new UPSRate.ShipmentType
            {
                Shipper = new UPSRate.ShipperType
                {
                    ShipperNumber = _upsSettings.AccountNumber,
                    Address       = addressFromDetails
                },
                ShipFrom = new UPSRate.ShipFromType
                {
                    Address = addressFromDetails
                },
                ShipTo = new UPSRate.ShipToType
                {
                    Address = addressToDetails
                }
            };

            //set pickup options and customer classification for US shipments
            if (countryCodeFrom.Equals("US", StringComparison.InvariantCultureIgnoreCase))
            {
                request.PickupType = new UPSRate.CodeDescriptionType
                {
                    Code = GetUpsCode(_upsSettings.PickupType)
                };
                request.CustomerClassification = new UPSRate.CodeDescriptionType
                {
                    Code = GetUpsCode(_upsSettings.CustomerClassification)
                };
            }

            //set negotiated rates details
            if (!string.IsNullOrEmpty(_upsSettings.AccountNumber) && !string.IsNullOrEmpty(stateCodeFrom) && !string.IsNullOrEmpty(stateCodeTo))
            {
                request.Shipment.ShipmentRatingOptions = new UPSRate.ShipmentRatingOptionsType
                {
                    NegotiatedRatesIndicator   = string.Empty,
                    UserLevelDiscountIndicator = string.Empty
                };
            }

            //set Saturday delivery details
            if (saturdayDelivery)
            {
                request.Shipment.ShipmentServiceOptions = new UPSRate.ShipmentServiceOptionsType
                {
                    SaturdayDeliveryIndicator = string.Empty
                };
            }

            //set packages details
            request.Shipment.Package = _upsSettings.PackingType switch
            {
                PackingType.PackByOneItemPerPackage => GetPackagesForOneItemPerPackage(shippingOptionRequest).ToArray(),
                PackingType.PackByVolume => GetPackagesByCubicRoot(shippingOptionRequest).ToArray(),
                _ => GetPackagesByDimensions(shippingOptionRequest).ToArray(),
            };
            return(request);
        }
Esempio n. 14
0
        public CreateRecurringPaymentsProfileRequestDetailsType GetCreateRecurringPaymentProfileRequestDetails(
            ProcessPaymentRequest processPaymentRequest)
        {
            var details = new CreateRecurringPaymentsProfileRequestDetailsType
            {
                Token = processPaymentRequest.CustomValues[Defaults.PaypalTokenKey].ToString()
            };

            var customer = _customerService.GetCustomerById(processPaymentRequest.CustomerId);

            if (customer is null)
            {
                throw new NopException("Customer is not found");
            }

            if ((customer.BillingAddressId ?? 0) == 0)
            {
                throw new NopException("Customer doesn't have a billing address");
            }

            var billingAddress = _addressService.GetAddressById(customer.BillingAddressId.Value);

            var country = _countryService.GetCountryByAddress(billingAddress);

            details.CreditCard = new CreditCardDetailsType
            {
                CreditCardNumber  = processPaymentRequest.CreditCardNumber,
                CreditCardType    = GetPaypalCreditCardType(processPaymentRequest.CreditCardType),
                ExpMonthSpecified = true,
                ExpMonth          = processPaymentRequest.CreditCardExpireMonth,
                ExpYearSpecified  = true,
                ExpYear           = processPaymentRequest.CreditCardExpireYear,
                CVV2      = processPaymentRequest.CreditCardCvv2,
                CardOwner = new PayerInfoType
                {
                    PayerCountry = GetPaypalCountryCodeType(country)
                },
                CreditCardTypeSpecified = true
            };



            details.CreditCard.CardOwner.Address = new AddressType
            {
                CountrySpecified = true,
                Street1          = billingAddress.Address1,
                Street2          = billingAddress.Address2,
                CityName         = billingAddress.City,
                StateOrProvince  = _stateProvinceService.GetStateProvinceByAddress(billingAddress)?.Abbreviation ?? "CA",
                Country          = GetPaypalCountryCodeType(country),
                PostalCode       = billingAddress.ZipPostalCode
            };
            details.CreditCard.CardOwner.Payer     = billingAddress.Email;
            details.CreditCard.CardOwner.PayerName = new PersonNameType
            {
                FirstName = billingAddress.FirstName,
                LastName  = billingAddress.LastName
            };

            //start date
            details.RecurringPaymentsProfileDetails = new RecurringPaymentsProfileDetailsType
            {
                BillingStartDate = DateTime.UtcNow,
                ProfileReference = processPaymentRequest.OrderGuid.ToString()
            };

            //schedule
            details.ScheduleDetails = new ScheduleDetailsType();
            var store     = _storeService.GetStoreById(processPaymentRequest.StoreId);
            var storeName = store == null ? string.Empty : store.Name;

            details.ScheduleDetails.Description = $"{storeName} - recurring payment";
            var currencyCodeType = _payPalCurrencyCodeParser.GetCurrencyCodeType(_workContext.WorkingCurrency);

            details.ScheduleDetails.PaymentPeriod = new BillingPeriodDetailsType
            {
                Amount           = processPaymentRequest.OrderTotal.GetBasicAmountType(currencyCodeType),
                BillingFrequency = processPaymentRequest.RecurringCycleLength
            };

            details.ScheduleDetails.PaymentPeriod.BillingPeriod = processPaymentRequest.RecurringCyclePeriod switch
            {
                RecurringProductCyclePeriod.Days => BillingPeriodType.Day,
                RecurringProductCyclePeriod.Weeks => BillingPeriodType.Week,
                RecurringProductCyclePeriod.Months => BillingPeriodType.Month,
                RecurringProductCyclePeriod.Years => BillingPeriodType.Year,
                _ => throw new NopException("Not supported cycle period"),
            };
            details.ScheduleDetails.PaymentPeriod.TotalBillingCycles          = processPaymentRequest.RecurringTotalCycles;
            details.ScheduleDetails.PaymentPeriod.TotalBillingCyclesSpecified = true;

            return(details);
        }
Esempio n. 15
0
        /// <summary>
        /// Create shipment packages (requests) from shopping cart
        /// </summary>
        /// <param name="cart">Shopping cart</param>
        /// <param name="shippingAddress">Shipping address</param>
        /// <param name="storeId">Load records allowed only in a specified store; pass 0 to load all records</param>
        /// <param name="shippingFromMultipleLocations">Value indicating whether shipping is done from multiple locations (warehouses)</param>
        /// <returns>Shipment packages (requests)</returns>
        public virtual IList <GetShippingOptionRequest> CreateShippingOptionRequests(IList <ShoppingCartItem> cart,
                                                                                     Address shippingAddress, int storeId, out bool shippingFromMultipleLocations)
        {
            //if we always ship from the default shipping origin, then there's only one request
            //if we ship from warehouses ("ShippingSettings.UseWarehouseLocation" enabled),
            //then there could be several requests

            //key - warehouse identifier (0 - default shipping origin)
            //value - request
            var requests = new Dictionary <int, GetShippingOptionRequest>();

            //a list of requests with products which should be shipped separately
            var separateRequests = new List <GetShippingOptionRequest>();

            foreach (var sci in cart)
            {
                if (!IsShipEnabled(sci))
                {
                    continue;
                }

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

                //TODO properly create requests for the associated products
                if (product == null || !product.IsShipEnabled)
                {
                    var associatedProducts = _productAttributeParser.ParseProductAttributeValues(sci.AttributesXml)
                                             .Where(attributeValue => attributeValue.AttributeValueType == AttributeValueType.AssociatedToProduct)
                                             .Select(attributeValue => _productService.GetProductById(attributeValue.AssociatedProductId));
                    product = associatedProducts.FirstOrDefault(associatedProduct => associatedProduct != null && associatedProduct.IsShipEnabled);
                }

                if (product == null)
                {
                    continue;
                }

                //warehouses
                Warehouse warehouse = null;
                if (_shippingSettings.UseWarehouseLocation)
                {
                    if (product.ManageInventoryMethod == ManageInventoryMethod.ManageStock &&
                        product.UseMultipleWarehouses)
                    {
                        var allWarehouses = new List <Warehouse>();
                        //multiple warehouses supported
                        foreach (var pwi in _productService.GetAllProductWarehouseInventoryRecords(product.Id))
                        {
                            //TODO validate stock quantity when backorder is not allowed?
                            var tmpWarehouse = GetWarehouseById(pwi.WarehouseId);
                            if (tmpWarehouse != null)
                            {
                                allWarehouses.Add(tmpWarehouse);
                            }
                        }

                        warehouse = GetNearestWarehouse(shippingAddress, allWarehouses);
                    }
                    else
                    {
                        //multiple warehouses are not supported
                        warehouse = GetWarehouseById(product.WarehouseId);
                    }
                }

                var warehouseId = warehouse?.Id ?? 0;

                if (requests.ContainsKey(warehouseId) && !product.ShipSeparately)
                {
                    //add item to existing request
                    requests[warehouseId].Items.Add(new GetShippingOptionRequest.PackageItem(sci, product));
                }
                else
                {
                    //create a new request
                    var request = new GetShippingOptionRequest
                    {
                        //store
                        StoreId = storeId
                    };
                    //customer
                    request.Customer = _customerService.GetShoppingCartCustomer(cart);

                    //ship to
                    request.ShippingAddress = shippingAddress;
                    //ship from
                    Address originAddress = null;
                    if (warehouse != null)
                    {
                        //warehouse address
                        originAddress         = _addressService.GetAddressById(warehouse.AddressId);
                        request.WarehouseFrom = warehouse;
                    }

                    if (originAddress == null)
                    {
                        //no warehouse address. in this case use the default shipping origin
                        originAddress = _addressService.GetAddressById(_shippingSettings.ShippingOriginAddressId);
                    }

                    if (originAddress != null)
                    {
                        request.CountryFrom       = _countryService.GetCountryByAddress(originAddress);
                        request.StateProvinceFrom = _stateProvinceService.GetStateProvinceByAddress(originAddress);
                        request.ZipPostalCodeFrom = originAddress.ZipPostalCode;
                        request.CountyFrom        = originAddress.County;
                        request.CityFrom          = originAddress.City;
                        request.AddressFrom       = originAddress.Address1;
                    }

                    //whether this product should be shipped separately from other ones
                    if (product.ShipSeparately)
                    {
                        //whether product items should be shipped separately
                        if (_shippingSettings.ShipSeparatelyOneItemEach)
                        {
                            //add item with overridden quantity 1
                            request.Items.Add(new GetShippingOptionRequest.PackageItem(sci, product, 1));

                            //create separate requests for all product quantity
                            for (var i = 0; i < sci.Quantity; i++)
                            {
                                separateRequests.Add(request);
                            }
                        }
                        else
                        {
                            //all of product items should be shipped in a single box, so create the single separate request
                            request.Items.Add(new GetShippingOptionRequest.PackageItem(sci, product));
                            separateRequests.Add(request);
                        }
                    }
                    else
                    {
                        //usual request
                        request.Items.Add(new GetShippingOptionRequest.PackageItem(sci, product));
                        requests.Add(warehouseId, request);
                    }
                }
            }

            //multiple locations?
            //currently we just compare warehouses
            //but we should also consider cases when several warehouses are located in the same address
            shippingFromMultipleLocations = requests.Select(x => x.Key).Distinct().Count() > 1;

            var result = requests.Values.ToList();

            result.AddRange(separateRequests);

            return(result);
        }
Esempio n. 16
0
        /// <summary>
        /// Handle order completed event
        /// </summary>
        /// <param name="order">Order</param>
        public void HandleOrderCompletedEvent(Order order)
        {
            //whether marketing automation is enabled
            if (!_sendinBlueSettings.UseMarketingAutomation)
            {
                return;
            }

            if (order is null)
            {
                throw new ArgumentNullException(nameof(order));
            }

            var customer = _customerService.GetCustomerById(order.CustomerId);

            try
            {
                //create API client
                var client = CreateMarketingAutomationClient();

                //first, try to identify current customer
                client.Identify(new Identify(customer.Email));

                //get URL helper
                var urlHelper = _urlHelperFactory.GetUrlHelper(_actionContextAccessor.ActionContext);

                //get products data by order items
                var itemsData = _orderService.GetOrderItems(order.Id).Select(item =>
                {
                    var product = _productService.GetProductById(item.ProductId);

                    //try to get product attribute combination
                    var combination = _productAttributeParser.FindProductAttributeCombination(product, item.AttributesXml);

                    //get default product picture
                    var picture = _pictureService.GetProductPicture(product, item.AttributesXml);

                    //get product SEO slug name
                    var seName = _urlRecordService.GetSeName(product);

                    //create product data
                    return(new
                    {
                        id = product.Id,
                        name = product.Name,
                        variant_id = combination?.Id ?? product.Id,
                        variant_name = combination?.Sku ?? product.Name,
                        sku = combination?.Sku ?? product.Sku,
                        category = _categoryService.GetProductCategoriesByProductId(item.ProductId).Aggregate(",", (all, pc) =>
                        {
                            var res = _categoryService.GetCategoryById(pc.CategoryId).Name;
                            res = all == "," ? res : all + ", " + res;
                            return res;
                        }),
                        url = urlHelper.RouteUrl("Product", new { SeName = seName }, _webHelper.CurrentRequestProtocol),
                        image = _pictureService.GetPictureUrl(ref picture),
                        quantity = item.Quantity,
                        price = item.PriceInclTax,
                    });
                }).ToArray();

                var shippingAddress = _addressService.GetAddressById(order.ShippingAddressId ?? 0);
                var billingAddress  = _addressService.GetAddressById(order.BillingAddressId);

                var shippingAddressData = new
                {
                    firstname = shippingAddress?.FirstName,
                    lastname  = shippingAddress?.LastName,
                    company   = shippingAddress?.Company,
                    phone     = shippingAddress?.PhoneNumber,
                    address1  = shippingAddress?.Address1,
                    address2  = shippingAddress?.Address2,
                    city      = shippingAddress?.City,
                    country   = _countryService.GetCountryByAddress(shippingAddress)?.Name,
                    state     = _stateProvinceService.GetStateProvinceByAddress(shippingAddress)?.Name,
                    zipcode   = shippingAddress?.ZipPostalCode
                };

                var billingAddressData = new
                {
                    firstname = billingAddress?.FirstName,
                    lastname  = billingAddress?.LastName,
                    company   = billingAddress?.Company,
                    phone     = billingAddress?.PhoneNumber,
                    address1  = billingAddress?.Address1,
                    address2  = billingAddress?.Address2,
                    city      = billingAddress?.City,
                    country   = _countryService.GetCountryByAddress(billingAddress)?.Name,
                    state     = _stateProvinceService.GetStateProvinceByAddress(billingAddress)?.Name,
                    zipcode   = billingAddress?.ZipPostalCode
                };

                //prepare cart data
                var cartData = new
                {
                    id               = order.Id,
                    affiliation      = customer.AffiliateId > 0 ? customer.AffiliateId.ToString() : _storeContext.CurrentStore.Name,
                    date             = order.PaidDateUtc?.ToString("yyyy-MM-dd"),
                    subtotal         = order.OrderSubtotalInclTax,
                    shipping         = order.OrderShippingInclTax,
                    total_before_tax = order.OrderSubtotalInclTax + order.OrderShippingInclTax,
                    tax              = order.OrderTax,
                    discount         = order.OrderDiscount,
                    revenue          = order.OrderTotal,
                    url              = urlHelper.RouteUrl("OrderDetails", new { orderId = order.Id }, _webHelper.CurrentRequestProtocol),
                    currency         = order.CustomerCurrencyCode,
                    //gift_wrapping = string.Empty, //currently we can't get this value
                    items            = itemsData,
                    shipping_address = shippingAddressData,
                    billing_address  = billingAddressData
                };

                //get shopping cart GUID
                var shoppingCartGuid = _genericAttributeService.GetAttribute <Guid?>(order,
                                                                                     SendinBlueDefaults.ShoppingCartGuidAttribute) ?? Guid.NewGuid();

                //create track event object
                var trackEvent = new TrackEvent(customer.Email, SendinBlueDefaults.OrderCompletedEventName,
                                                eventData: new { id = $"cart:{shoppingCartGuid}", data = cartData });

                //track event
                client.TrackEvent(trackEvent);

                //update GUID for the current customer's shopping cart
                _genericAttributeService.SaveAttribute <Guid?>(order, SendinBlueDefaults.ShoppingCartGuidAttribute, null);
            }
            catch (Exception exception)
            {
                //log full error
                _logger.Error($"SendinBlue Marketing Automation error: {exception.Message}.", exception, customer);
            }
        }
Esempio n. 17
0
        /// <summary>
        /// Get tracking info
        /// </summary>
        /// <param name="request">Request details</param>
        /// <returns>The asynchronous task whose result contains the tracking info</returns>
        //private async Task<UPSTrack.TrackResponse> TrackAsync(UPSTrack.TrackRequest request)
        //{
        //    try
        //    {
        //        //create client
        //        var trackPort = _jusdaSettings.UseSandbox
        //            ? UPSTrack.TrackPortTypeClient.EndpointConfiguration.TrackPort
        //            : UPSTrack.TrackPortTypeClient.EndpointConfiguration.ProductionTrackPort;

        //        using var client = new UPSTrack.TrackPortTypeClient(trackPort);
        //        //create object to authenticate request
        //        var security = new UPSTrack.UPSSecurity
        //        {
        //            ServiceAccessToken = new UPSTrack.UPSSecurityServiceAccessToken
        //            {
        //                AccessLicenseNumber = _jusdaSettings.AccessKey
        //            },
        //            UsernameToken = new UPSTrack.UPSSecurityUsernameToken
        //            {
        //                Username = _jusdaSettings.Username,
        //                Password = _jusdaSettings.Password
        //            }
        //        };

        //        //save debug info
        //        if (_jusdaSettings.Tracing)
        //            _logger.Information($"UPS shipment tracking. Request: {ToXml(new UPSTrack.TrackRequest1(security, request))}");

        //        //try to get response details
        //        var response = await client.ProcessTrackAsync(security, request);

        //        //save debug info
        //        if (_jusdaSettings.Tracing)
        //            _logger.Information($"UPS shipment tracking. Response: {ToXml(response)}");

        //        return response.TrackResponse;
        //    }
        //    catch (FaultException<UPSTrack.ErrorDetailType[]> ex)
        //    {
        //        //get error details
        //        var message = ex.Message;
        //        if (ex.Detail.Any())
        //        {
        //            message = ex.Detail.Aggregate(message, (details, detail) =>
        //                $"{details}{Environment.NewLine}{detail.Severity} error: {detail.PrimaryErrorCode?.Description}");
        //        }

        //        //rethrow exception
        //        throw new Exception(message, ex);
        //    }
        //}

        /// <summary>
        /// Create request details to track shipment
        /// </summary>
        /// <param name="trackingNumber">Tracking number</param>
        /// <returns>Track request details</returns>
        //private UPSTrack.TrackRequest CreateTrackRequest(string trackingNumber)
        //{
        //    return new UPSTrack.TrackRequest
        //    {
        //        Request = new UPSTrack.RequestType
        //        {
        //            //use the RequestOption field to indicate the specific types of information to receive
        //            //15 = POD, Signature Image, COD, Receiver Address, All Activity (all that's available)
        //            RequestOption = new[] { "15" }
        //        },
        //        InquiryNumber = trackingNumber
        //    };
        //}

        /// <summary>
        /// Prepare shipment status event by the passed track activity
        /// </summary>
        /// <param name="activity">Track activity</param>
        /// <returns>Shipment status event </returns>
        //private ShipmentStatusEvent PrepareShipmentStatusEvent(UPSTrack.ActivityType activity)
        //{
        //    var shipmentStatusEvent = new ShipmentStatusEvent();

        //    try
        //    {
        //        //prepare date
        //        shipmentStatusEvent.Date = DateTime
        //            .ParseExact($"{activity.Date} {activity.Time}", "yyyyMMdd HHmmss", CultureInfo.InvariantCulture);

        //        //prepare address
        //        var addressDetails = new List<string>();
        //        if (!string.IsNullOrEmpty(activity.ActivityLocation?.Address?.CountryCode))
        //            addressDetails.Add(activity.ActivityLocation.Address.CountryCode);
        //        if (!string.IsNullOrEmpty(activity.ActivityLocation?.Address?.StateProvinceCode))
        //            addressDetails.Add(activity.ActivityLocation.Address.StateProvinceCode);
        //        if (!string.IsNullOrEmpty(activity.ActivityLocation?.Address?.City))
        //            addressDetails.Add(activity.ActivityLocation.Address.City);
        //        if (activity.ActivityLocation?.Address?.AddressLine?.Any() ?? false)
        //            addressDetails.AddRange(activity.ActivityLocation.Address.AddressLine);
        //        if (!string.IsNullOrEmpty(activity.ActivityLocation?.Address?.PostalCode))
        //            addressDetails.Add(activity.ActivityLocation.Address.PostalCode);

        //        shipmentStatusEvent.CountryCode = activity.ActivityLocation?.Address?.CountryCode;
        //        shipmentStatusEvent.Location = string.Join(", ", addressDetails);

        //        if (activity.Status == null)
        //            return shipmentStatusEvent;

        //        //prepare description
        //        var eventName = string.Empty;
        //        switch (activity.Status.Type)
        //        {
        //            case "I":
        //                eventName = activity.Status.Code switch
        //                {
        //                    "DP" => "Plugins.Shipping.Tracker.Departed",
        //                    "EP" => "Plugins.Shipping.Tracker.ExportScanned",
        //                    "OR" => "Plugins.Shipping.Tracker.OriginScanned",
        //                    _ => "Plugins.Shipping.Tracker.Arrived",
        //                };
        //                break;

        //            case "X":
        //                eventName = "Plugins.Shipping.Tracker.NotDelivered";
        //                break;

        //            case "M":
        //                eventName = "Plugins.Shipping.Tracker.Booked";
        //                break;

        //            case "D":
        //                eventName = "Plugins.Shipping.Tracker.Delivered";
        //                break;

        //            case "P":
        //                eventName = "Plugins.Shipping.Tracker.Pickup";
        //                break;
        //        }
        //        shipmentStatusEvent.EventName = _localizationService.GetResource(eventName);
        //    }
        //    catch { }

        //    return shipmentStatusEvent;
        //}

        /// <summary>
        /// Get rates
        /// </summary>
        /// <param name="request">Request details</param>
        /// <returns>The asynchronous task whose result contains the rates info</returns>
        //private async Task<UPSRate.RateResponse> GetRatesAsync(UPSRate.RateRequest request)
        //{
        //    try
        //    {
        //        //create client
        //        var ratePort = _jusdaSettings.UseSandbox
        //            ? UPSRate.RatePortTypeClient.EndpointConfiguration.RatePort
        //            : UPSRate.RatePortTypeClient.EndpointConfiguration.ProductionRatePort;

        //        using var client = new UPSRate.RatePortTypeClient(ratePort);
        //        //create object to authenticate request
        //        var security = new UPSRate.UPSSecurity
        //        {
        //            ServiceAccessToken = new UPSRate.UPSSecurityServiceAccessToken
        //            {
        //                AccessLicenseNumber = _jusdaSettings.AccessKey
        //            },
        //            UsernameToken = new UPSRate.UPSSecurityUsernameToken
        //            {
        //                Username = _jusdaSettings.Username,
        //                Password = _jusdaSettings.Password
        //            }
        //        };

        //        //save debug info
        //        if (_jusdaSettings.Tracing)
        //            _logger.Information($"UPS rates. Request: {ToXml(new UPSRate.RateRequest1(security, request))}");

        //        //try to get response details
        //        var response = await client.ProcessRateAsync(security, request);

        //        //save debug info
        //        if (_jusdaSettings.Tracing)
        //            _logger.Information($"UPS rates. Response: {ToXml(response)}");

        //        return response.RateResponse;
        //    }
        //    catch (FaultException<UPSRate.ErrorDetailType[]> ex)
        //    {
        //        //get error details
        //        var message = ex.Message;
        //        if (ex.Detail.Any())
        //        {
        //            message = ex.Detail.Aggregate(message, (details, detail) =>
        //                $"{details}{Environment.NewLine}{detail.Severity} error: {detail.PrimaryErrorCode?.Description}");
        //        }

        //        //rethrow exception
        //        throw new Exception(message, ex);
        //    }
        //}

        /// <summary>
        /// Create request details to get shipping rates
        /// </summary>
        /// <param name="shippingOptionRequest">Shipping option request</param>
        /// <param name="saturdayDelivery">Whether to get rates for Saturday Delivery</param>
        /// <returns>Rate request details</returns>
        private Domain.RateRequest CreateRateRequest(GetShippingOptionRequest shippingOptionRequest, bool saturdayDelivery = false)
        {
            var rateRequest = new Domain.RateRequest()
            {
                Mode = "Parcel",   //LTL,  Parcel, ALL
                //ShipperCity = "Los Angelas",
                //ShipperStateProvince = "CA",
                //ShipperCountry = "US",
                //ShipperPostalCode = "90001",
                //ShipToCity = "Aurora",
                //ShipToPostalCode = "60504",
                //ShipToStateProvince = "IL",
                //ShipToCountry = "US",

                OriginResidential      = false,
                DestinationResidential = false,
                OriginWeekend          = false,
                DestinationWeekend     = false,
                ShipDateTime           = DateTime.Now,
                Description            = "",
                DeclaredValue          = 0,
                ShipperReferenceNo     = "",
                FreightClass           = 1,
                RateRequestItems       = new List <RateRequestItem>(),
                //    {
                //        new RateRequestItem()
                //        {
                //            Description = "",
                //            Pieces = 1,
                //            PackType = null,
                //            Weight = 1,
                //            WeightUnit = "KG",
                //            Length = 1,
                //            Width = 1,
                //            Height = 1,
                //            FreightClass = 1,
                //            Nmfc = null,
                //            DimUnit = "IN",
                //            Hazardous = false
                //        }
                //    }
            };


            //    //set request details
            //    var request = new UPSRate.RateRequest
            //    {
            //        Request = new UPSRate.RequestType
            //        {
            //            //used to define the request type
            //            //Shop - the server validates the shipment, and returns rates for all UPS products from the ShipFrom to the ShipTo addresses
            //            RequestOption = new[] { "Shop" }
            //        }
            //    };

            //    //prepare addresses details
            var stateCodeTo     = _stateProvinceService.GetStateProvinceByAddress(shippingOptionRequest.ShippingAddress)?.Abbreviation;
            var stateCodeFrom   = shippingOptionRequest.StateProvinceFrom?.Abbreviation;
            var countryCodeFrom = (shippingOptionRequest.CountryFrom ?? _countryService.GetAllCountries().FirstOrDefault())
                                  .TwoLetterIsoCode ?? string.Empty;


            //todo:  warehouse logic here???  cause AddressFrom is blank...


            //    var addressfromdetails = new upsrate.shipaddresstype
            //    {
            //        addressline = new[] { shippingoptionrequest.addressfrom },
            //        city = shippingoptionrequest.cityfrom,
            //        stateprovincecode = statecodefrom,
            //        countrycode = countrycodefrom,
            //        postalcode = shippingoptionrequest.zippostalcodefrom
            //    };
            rateRequest.ShipperAddress1      = shippingOptionRequest.AddressFrom;
            rateRequest.ShipperCity          = shippingOptionRequest.CityFrom;
            rateRequest.ShipperStateProvince = stateCodeFrom;
            rateRequest.ShipperCountry       = countryCodeFrom;
            rateRequest.ShipperPostalCode    = shippingOptionRequest.ZipPostalCodeFrom;

            //    var addresstodetails = new upsrate.shiptoaddresstype
            //    {
            //        addressline = new[] { shippingoptionrequest.shippingaddress.address1, shippingoptionrequest.shippingaddress.address2 },
            //        city = shippingOptionRequest.shippingaddress.city,
            //        stateprovincecode = statecodeto,
            //        countrycode = _countryservice.getcountrybyaddress(shippingoptionrequest.shippingaddress)?.twoletterisocode,
            //        postalcode = shippingoptionrequest.shippingaddress.zippostalcode,
            //        residentialaddressindicator = string.empty
            //    };

            rateRequest.ShipToAddress1      = shippingOptionRequest.ShippingAddress.Address1;
            rateRequest.ShipToAddress2      = shippingOptionRequest.ShippingAddress.Address2;
            rateRequest.ShipToCity          = shippingOptionRequest.ShippingAddress.City;
            rateRequest.ShipToStateProvince = stateCodeTo;
            rateRequest.ShipToCountry       = _countryService.GetCountryByAddress(shippingOptionRequest.ShippingAddress)?.TwoLetterIsoCode;
            rateRequest.ShipToPostalCode    = shippingOptionRequest.ShippingAddress.ZipPostalCode;

            //    //set shipment details
            //    request.Shipment = new UPSRate.ShipmentType
            //    {
            //        Shipper = new UPSRate.ShipperType
            //        {
            //            ShipperNumber = _jusdaSettings.AccountNumber,
            //            Address = addressFromDetails
            //        },
            //        ShipFrom = new UPSRate.ShipFromType
            //        {
            //            Address = addressFromDetails
            //        },
            //        ShipTo = new UPSRate.ShipToType
            //        {
            //            Address = addressToDetails
            //        }
            //    };

            //    //set pickup options and customer classification for US shipments
            //    if (countryCodeFrom.Equals("US", StringComparison.InvariantCultureIgnoreCase))
            //    {
            //        request.PickupType = new UPSRate.CodeDescriptionType
            //        {
            //            Code = GetUpsCode(_jusdaSettings.PickupType)
            //        };
            //        request.CustomerClassification = new UPSRate.CodeDescriptionType
            //        {
            //            Code = GetUpsCode(_jusdaSettings.CustomerClassification)
            //        };
            //    }

            //    //set negotiated rates details
            //    if (!string.IsNullOrEmpty(_jusdaSettings.AccountNumber) && !string.IsNullOrEmpty(stateCodeFrom) && !string.IsNullOrEmpty(stateCodeTo))
            //    {
            //        request.Shipment.ShipmentRatingOptions = new UPSRate.ShipmentRatingOptionsType
            //        {
            //            NegotiatedRatesIndicator = string.Empty,
            //            UserLevelDiscountIndicator = string.Empty
            //        };
            //    }

            //    //set Saturday delivery details
            //    if (saturdayDelivery)
            //    {
            //        request.Shipment.ShipmentServiceOptions = new UPSRate.ShipmentServiceOptionsType
            //        {
            //            SaturdayDeliveryIndicator = string.Empty
            //        };
            //    }

            //    //set packages details
            //    request.Shipment.Package = _jusdaSettings.PackingType switch
            //    {
            //        PackingType.PackByOneItemPerPackage => GetPackagesForOneItemPerPackage(shippingOptionRequest).ToArray(),
            //        PackingType.PackByVolume => GetPackagesByCubicRoot(shippingOptionRequest).ToArray(),
            //        _ => GetPackagesByDimensions(shippingOptionRequest).ToArray(),
            //    };

            foreach (var item in shippingOptionRequest.Items)
            {
                var dims = GetDimensionsForSingleItem(item.ShoppingCartItem, item.Product);
                rateRequest.RateRequestItems.Add(new RateRequestItem()
                {
                    Description  = item.Product.ShortDescription,
                    Pieces       = item.GetQuantity(),
                    PackType     = null, //TODO???
                    Weight       = GetWeightForSingleItem(item.ShoppingCartItem, shippingOptionRequest.Customer, item.Product),
                    WeightUnit   = _jusdaSettings.WeightType,
                    Length       = (int)dims.length, //TODO:  decimal to int?
                    Width        = (int)dims.width,  //TODO:  decimal to int?
                    Height       = (int)dims.height, //TODO:  decimal to int?
                    DimUnit      = _jusdaSettings.DimensionsType,
                    FreightClass = 1,                //what is this?!?!?
                    Nmfc         = null,
                    Hazardous    = false
                });
            }

            return(rateRequest);
        }
        /// <summary>
        /// Screen an order transaction for payment fraud
        /// </summary>
        /// <param name="order">NopCommerce order object</param>
        /// <returns>OrderResult</returns>
        public OrderResult ScreenOrder(NopOrder order)
        {
            //whether plugin is configured
            if (string.IsNullOrEmpty(_fraudLabsProSettings.ApiKey))
            {
                throw new NopException($"Plugin not configured");
            }

            try
            {
                // Configure FraudLabs Pro API KEY
                FraudLabsProConfig.APIKey = _fraudLabsProSettings.ApiKey;

                var customer = _customerService.GetCustomerById(order.CustomerId);
                if (customer != null)
                {
                    var shippingAddress = _addressService.GetAddressById(order.ShippingAddressId ?? order.BillingAddressId);
                    var billingAddress  = _addressService.GetAddressById(order.BillingAddressId);

                    //prepare parameters
                    var screenOrderPara = new OrderPara();

                    //customer information
                    screenOrderPara.IPAddress    = customer.LastIpAddress ?? string.Empty;
                    screenOrderPara.FirstName    = ((billingAddress != null) ? billingAddress.FirstName : string.Empty) ?? string.Empty;
                    screenOrderPara.LastName     = ((billingAddress != null) ? billingAddress.LastName : string.Empty) ?? string.Empty;
                    screenOrderPara.UserPhone    = ((billingAddress != null) ? billingAddress.PhoneNumber : string.Empty) ?? string.Empty;
                    screenOrderPara.EmailAddress = ((billingAddress != null) ? billingAddress.Email : string.Empty) ?? string.Empty;
                    screenOrderPara.FLPCheckSum  = GetFLPCheckSum();

                    // Billing Information
                    if (billingAddress != null)
                    {
                        screenOrderPara.BillAddress = billingAddress.Address1 + " " + billingAddress.Address2;
                        screenOrderPara.BillCity    = billingAddress.City ?? string.Empty;
                        screenOrderPara.BillState   = _stateProvinceService.GetStateProvinceByAddress(billingAddress)?.Name ?? string.Empty;
                        screenOrderPara.BillCountry = _countryService.GetCountryByAddress(billingAddress)?.TwoLetterIsoCode ?? string.Empty;
                        screenOrderPara.BillZIPCode = billingAddress.ZipPostalCode ?? string.Empty;
                    }

                    // Shipping Information
                    if (shippingAddress != null)
                    {
                        screenOrderPara.ShippingAddress = shippingAddress.Address1 + " " + shippingAddress.Address2;
                        screenOrderPara.ShippingCity    = shippingAddress.City ?? string.Empty;
                        screenOrderPara.ShippingState   = _stateProvinceService.GetStateProvinceByAddress(shippingAddress)?.Name ?? string.Empty;
                        screenOrderPara.ShippingCountry = _countryService.GetCountryByAddress(shippingAddress)?.TwoLetterIsoCode ?? string.Empty;
                        screenOrderPara.ShippingZIPCode = shippingAddress.ZipPostalCode ?? string.Empty;
                    }

                    //Payment information
                    var cardNumber = _encryptionService.DecryptText(order.CardNumber);

                    if (!string.IsNullOrEmpty(cardNumber))
                    {
                        screenOrderPara.BinNo       = cardNumber.Substring(0, 6);
                        screenOrderPara.CardNumber  = cardNumber;
                        screenOrderPara.PaymentMode = Order.PaymentMethods.CREDIT_CARD;
                    }

                    // Order Information
                    screenOrderPara.Department    = _storeContext.CurrentStore.Name ?? string.Empty;
                    screenOrderPara.UserOrderID   = order.Id.ToString();
                    screenOrderPara.UserOrderMemo = order.OrderGuid.ToString();
                    screenOrderPara.Amount        = order.OrderTotal;
                    screenOrderPara.Quantity      = _orderService.GetOrderItems(order.Id).Sum(x => x.Quantity);
                    screenOrderPara.Currency      = order.CustomerCurrencyCode ?? string.Empty;

                    // ScreenOrder API
                    var screenOrder = new Order();
                    // Send order to FraudLabs Pro
                    var result = screenOrder.ScreenOrder(screenOrderPara);
                    _genericAttributeService.SaveAttribute(order, FraudLabsProDefaults.OrderResultAttribute, JsonConvert.SerializeObject(result));
                    _fraudLabsProSettings.Balance = result.FraudLabsProCredit;
                    _settingService.SaveSetting(_fraudLabsProSettings);

                    //save order status
                    _genericAttributeService.SaveAttribute(order, FraudLabsProDefaults.OrderStatusAttribute, result.FraudLabsProStatus);

                    UpdateOrerStatus(order, result.FraudLabsProStatus);

                    return(result);
                }
            }
            catch (Exception exception)
            {
                //log full error
                _logger.Error($"FraundLabs Pro ScreenOrder error: {exception.Message}.", exception, _workContext.CurrentCustomer);
            }
            return(null);
        }
Esempio n. 19
0
        /// <summary>
        /// Invoke the widget view component
        /// </summary>
        /// <param name="widgetZone">Widget zone</param>
        /// <param name="additionalData">Additional parameters</param>
        /// <returns>View component result</returns>
        public IViewComponentResult Invoke(string widgetZone, object additionalData)
        {
            //ensure that Avalara tax provider is active
            if (!_taxPluginManager.IsPluginActive(AvalaraTaxDefaults.SystemName, _workContext.CurrentCustomer, _storeContext.CurrentStore.Id))
            {
                return(Content(string.Empty));
            }

            //ensure that it's a proper widget zone
            if (!widgetZone.Equals(PublicWidgetZones.CheckoutConfirmTop) && !widgetZone.Equals(PublicWidgetZones.OpCheckoutConfirmTop))
            {
                return(Content(string.Empty));
            }

            //ensure thet address validation is enabled
            if (!_avalaraTaxSettings.ValidateAddress)
            {
                return(Content(string.Empty));
            }

            //validate entered by customer addresses only
            var addressId = _taxSettings.TaxBasedOn == TaxBasedOn.BillingAddress
                ? _workContext.CurrentCustomer.BillingAddressId
                : _taxSettings.TaxBasedOn == TaxBasedOn.ShippingAddress
                ? _workContext.CurrentCustomer.ShippingAddressId
                : null;

            var address = _addressService.GetAddressById(addressId ?? 0);

            if (address == null)
            {
                return(Content(string.Empty));
            }

            //validate address
            var validationResult = _avalaraTaxManager.ValidateAddress(address);

            //whether there are errors in validation result
            var errorDetails = validationResult?.messages?
                               .Where(message => message.severity.Equals("Error", StringComparison.InvariantCultureIgnoreCase))
                               .Select(message => message.details)
                               ?? new List <string>();

            if (errorDetails.Any())
            {
                //display error message to customer
                return(View("~/Plugins/Tax.Avalara/Views/Checkout/AddressValidation.cshtml", new AddressValidationModel
                {
                    Message = string.Format(_localizationService.GetResource("Plugins.Tax.Avalara.AddressValidation.Error"),
                                            WebUtility.HtmlEncode(string.Join("; ", errorDetails))),
                    IsError = true
                }));
            }

            //if there are no errors and no validated addresses, nothing to display
            if (!validationResult?.validatedAddresses?.Any() ?? true)
            {
                return(Content(string.Empty));
            }

            //get validated address info
            var validatedAddressInfo = validationResult.validatedAddresses.FirstOrDefault();

            //create new address as a copy of address to validate and with details of the validated one
            var validatedAddress = _addressService.CloneAddress(address);

            validatedAddress.City            = validatedAddressInfo.city;
            validatedAddress.CountryId       = _countryService.GetCountryByTwoLetterIsoCode(validatedAddressInfo.country)?.Id;
            validatedAddress.Address1        = validatedAddressInfo.line1;
            validatedAddress.Address2        = validatedAddressInfo.line2;
            validatedAddress.ZipPostalCode   = validatedAddressInfo.postalCode;
            validatedAddress.StateProvinceId = _stateProvinceService.GetStateProvinceByAbbreviation(validatedAddressInfo.region)?.Id;

            //try to find an existing address with the same values
            var existingAddress = _addressService.FindAddress(_customerService.GetAddressesByCustomerId(_workContext.CurrentCustomer.Id).ToList(),
                                                              validatedAddress.FirstName, validatedAddress.LastName, validatedAddress.PhoneNumber,
                                                              validatedAddress.Email, validatedAddress.FaxNumber, validatedAddress.Company,
                                                              validatedAddress.Address1, validatedAddress.Address2, validatedAddress.City,
                                                              validatedAddress.County, validatedAddress.StateProvinceId, validatedAddress.ZipPostalCode,
                                                              validatedAddress.CountryId, validatedAddress.CustomAttributes);

            //if the found address is the same as address to validate, nothing to display
            if (address.Id == existingAddress?.Id)
            {
                return(Content(string.Empty));
            }

            //otherwise display to customer a confirmation dialog about address updating
            var model = new AddressValidationModel();

            if (existingAddress == null)
            {
                _addressService.InsertAddress(validatedAddress);
                model.AddressId    = validatedAddress.Id;
                model.IsNewAddress = true;
            }
            else
            {
                model.AddressId = existingAddress.Id;
            }

            string getAddressLine(Address address) =>
            WebUtility.HtmlEncode($"{(!string.IsNullOrEmpty(address.Address1) ? $"{address.Address1}, " : string.Empty)}" +
                                  $"{(!string.IsNullOrEmpty(address.Address2) ? $"{address.Address2}, " : string.Empty)}" +
                                  $"{(!string.IsNullOrEmpty(address.City) ? $"{address.City}, " : string.Empty)}" +
                                  $"{(_stateProvinceService.GetStateProvinceByAddress(address) is StateProvince stateProvince ? $"{stateProvince.Name}, " : string.Empty)}" +
                                  $"{(_countryService.GetCountryByAddress(address) is Country country ? $"{country.Name}, " : string.Empty)}" +
                                  $"{(!string.IsNullOrEmpty(address.ZipPostalCode) ? $"{address.ZipPostalCode}, " : string.Empty)}"
                                  .TrimEnd(' ').TrimEnd(','));

            model.Message = string.Format(_localizationService.GetResource("Plugins.Tax.Avalara.AddressValidation.Confirm"),
                                          getAddressLine(address), getAddressLine(existingAddress ?? validatedAddress));

            return(View("~/Plugins/Tax.Avalara/Views/Checkout/AddressValidation.cshtml", model));
        }