/// <summary> /// 添加日志 /// </summary> /// <param name="action">动作</param> /// <param name="data">数据</param> /// <param name="userId">用户编号</param> /// <param name="userName">用户名称</param> /// <param name="ip">IP</param> public async Task <bool> AddLogAsync(string action, string data, int userId, string userName) { var model = new LogEntity(action, webHelper.GetRawUrl(httpContextAccessor.HttpContext.Request), httpContextAccessor.HttpContext.Request.Method, data, userId, userName, webHelper.GetCurrentIpAddress()); return(await this.AddAsync(model)); }
/// <summary> /// Process a payment /// </summary> /// <param name="processPaymentRequest">Payment info required for an order processing</param> /// <returns>Process payment result</returns> public ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest) { var result = new ProcessPaymentResult(); var customer = _customerService.GetCustomerById(processPaymentRequest.CustomerId); var webClient = new WebClient(); var form = new NameValueCollection(); form.Add("x_login", _authorizeNetPaymentSettings.LoginId); form.Add("x_tran_key", _authorizeNetPaymentSettings.TransactionKey); //we should not send "x_test_request" parameter. otherwise, the transaction won't be logged in the sandbox //if (_authorizeNetPaymentSettings.UseSandbox) // form.Add("x_test_request", "TRUE"); //else // form.Add("x_test_request", "FALSE"); form.Add("x_delim_data", "TRUE"); form.Add("x_delim_char", "|"); form.Add("x_encap_char", ""); form.Add("x_version", GetApiVersion()); form.Add("x_relay_response", "FALSE"); form.Add("x_method", "CC"); form.Add("x_currency_code", _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId).CurrencyCode); if (_authorizeNetPaymentSettings.TransactMode == TransactMode.Authorize) { form.Add("x_type", "AUTH_ONLY"); } else if (_authorizeNetPaymentSettings.TransactMode == TransactMode.AuthorizeAndCapture) { form.Add("x_type", "AUTH_CAPTURE"); } else { throw new NopException("Not supported transaction mode"); } var orderTotal = Math.Round(processPaymentRequest.OrderTotal, 2); form.Add("x_amount", orderTotal.ToString("0.00", CultureInfo.InvariantCulture)); form.Add("x_card_num", processPaymentRequest.CreditCardNumber); form.Add("x_exp_date", processPaymentRequest.CreditCardExpireMonth.ToString("D2") + processPaymentRequest.CreditCardExpireYear.ToString()); form.Add("x_card_code", processPaymentRequest.CreditCardCvv2); form.Add("x_first_name", customer.BillingAddress.FirstName); form.Add("x_last_name", customer.BillingAddress.LastName); form.Add("x_email", customer.BillingAddress.Email); if (!string.IsNullOrEmpty(customer.BillingAddress.Company)) { form.Add("x_company", customer.BillingAddress.Company); } form.Add("x_address", customer.BillingAddress.Address1); form.Add("x_city", customer.BillingAddress.City); if (customer.BillingAddress.StateProvince != null) { form.Add("x_state", customer.BillingAddress.StateProvince.Abbreviation); } form.Add("x_zip", customer.BillingAddress.ZipPostalCode); if (customer.BillingAddress.Country != null) { form.Add("x_country", customer.BillingAddress.Country.TwoLetterIsoCode); } //x_invoice_num is 20 chars maximum. hece we also pass x_description form.Add("x_invoice_num", processPaymentRequest.OrderGuid.ToString().Substring(0, 20)); form.Add("x_description", string.Format("Full order #{0}", processPaymentRequest.OrderGuid)); form.Add("x_customer_ip", _webHelper.GetCurrentIpAddress()); var responseData = webClient.UploadValues(GetAuthorizeNetUrl(), form); var reply = Encoding.ASCII.GetString(responseData); if (!String.IsNullOrEmpty(reply)) { string[] responseFields = reply.Split('|'); switch (responseFields[0]) { case "1": result.AuthorizationTransactionCode = string.Format("{0},{1}", responseFields[6], responseFields[4]); result.AuthorizationTransactionResult = string.Format("Approved ({0}: {1})", responseFields[2], responseFields[3]); result.AvsResult = responseFields[5]; //responseFields[38]; if (_authorizeNetPaymentSettings.TransactMode == TransactMode.Authorize) { result.NewPaymentStatus = PaymentStatus.Authorized; } else { result.NewPaymentStatus = PaymentStatus.Paid; } break; case "2": result.AddError(string.Format("Declined ({0}: {1})", responseFields[2], responseFields[3])); break; case "3": result.AddError(string.Format("Error: {0}", reply)); break; } } else { result.AddError("Authorize.NET unknown error"); } return(result); }
public ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest) { var result = new ProcessPaymentResult(); var customer = _customerService.GetCustomerById(processPaymentRequest.CustomerId); var cardknoxFacade = PrepareCardknoxFacade(); CardknoxSDK.Actions.Common.PaymentRequest cardknoxPaymentRequest = null; if (_cardknoxPaymentSettings.TransactMode == TransactMode.Authorize) { cardknoxPaymentRequest = new CardknoxSDK.Actions.AuthOnly.Request(); } else { cardknoxPaymentRequest = new CardknoxSDK.Actions.Sale.Request(); } //Fill info if (processPaymentRequest.CreditCardExpireYear > 99) { //Take only 2 digits var date2digits = new DateTime(processPaymentRequest.CreditCardExpireYear, 1, 1).ToString("yy"); cardknoxPaymentRequest.ExpirationYear = Convert.ToInt32(date2digits); } else { cardknoxPaymentRequest.ExpirationYear = processPaymentRequest.CreditCardExpireYear; } cardknoxPaymentRequest.Name = processPaymentRequest.CreditCardName; cardknoxPaymentRequest.CardNumber = processPaymentRequest.CreditCardNumber; cardknoxPaymentRequest.ExpirationMonth = processPaymentRequest.CreditCardExpireMonth; cardknoxPaymentRequest.CVV = processPaymentRequest.CreditCardCvv2; cardknoxPaymentRequest.Amount = Math.Round(processPaymentRequest.OrderTotal, 2); cardknoxPaymentRequest.Email = customer.BillingAddress.Email; cardknoxPaymentRequest.CustomerIpAddress = _webHelper.GetCurrentIpAddress(); cardknoxPaymentRequest.Street = customer.BillingAddress.Address1; cardknoxPaymentRequest.Zip = customer.BillingAddress.ZipPostalCode; cardknoxPaymentRequest.SendReceiptToCustomerEmail = _cardknoxPaymentSettings.SendReceiptToCustomerEmail; cardknoxPaymentRequest.Invoice = processPaymentRequest.OrderGuid.ToString(); if (!_cardknoxPaymentSettings.HideAddressDetails) { cardknoxPaymentRequest.BillingAddress = new CardknoxSDK.Actions.Common.PaymentRequest.Address(); cardknoxPaymentRequest.ShippingAddress = new CardknoxSDK.Actions.Common.PaymentRequest.Address(); if (_cardknoxPaymentSettings.UseShippingAddressAsBilling) { MapAddressToCardknox(customer.ShippingAddress, cardknoxPaymentRequest.BillingAddress); } else { MapAddressToCardknox(customer.BillingAddress, cardknoxPaymentRequest.BillingAddress); } MapAddressToCardknox(customer.ShippingAddress, cardknoxPaymentRequest.ShippingAddress); } CardknoxSDK.Infra.IResponse response = null; if (_cardknoxPaymentSettings.TransactMode == TransactMode.Authorize) { response = cardknoxFacade.AuthOnly((CardknoxSDK.Actions.AuthOnly.Request)cardknoxPaymentRequest) .GetAwaiter().GetResult(); } else { response = cardknoxFacade.Sale((CardknoxSDK.Actions.Sale.Request)cardknoxPaymentRequest) .GetAwaiter().GetResult(); } if (response == null) { return(result); } switch (response.ResponseType) { case CardknoxSDK.Infra.ResponseTypes.Accepted: if (_cardknoxPaymentSettings.TransactMode == TransactMode.Authorize) { result.AuthorizationTransactionId = response.RefNum; result.AuthorizationTransactionCode = response.RefNum; result.NewPaymentStatus = PaymentStatus.Authorized; } else { result.CaptureTransactionId = response.RefNum; result.NewPaymentStatus = PaymentStatus.Paid; } result.AuthorizationTransactionResult = $"Payment request approved"; break; case CardknoxSDK.Infra.ResponseTypes.Declined: result.AddError($"Payment declined. Error code: {response.ErrorCode} - Error Message: {response.ErrorMessage}"); break; case CardknoxSDK.Infra.ResponseTypes.Error: result.AddError($"Payment error. Error code: {response.ErrorCode} - Error Message: {response.ErrorMessage}"); break; case CardknoxSDK.Infra.ResponseTypes.Timeout: result.AddError($"Payment timeout. Please try again. Error code: {response.ErrorCode} - Error Message: {response.ErrorMessage}"); break; case CardknoxSDK.Infra.ResponseTypes.HttpException: result.AddError($"Communication error. Please try again. Error code: {response.ErrorCode} - Error Message: {response.ErrorMessage}"); break; } return(result); }
public ActionResult BlogCommentAdd(int blogPostId, BlogPostModel model, bool captchaValid) { if (!_blogSettings.Enabled) { return(HttpNotFound()); } var blogPost = _blogService.GetBlogPostById(blogPostId); if (blogPost == null || !blogPost.AllowComments) { return(HttpNotFound()); } if (_workContext.CurrentCustomer.IsGuest() && !_blogSettings.AllowNotRegisteredUsersToLeaveComments) { ModelState.AddModelError("", _localizationService.GetResource("Blog.Comments.OnlyRegisteredUsersLeaveComments")); } //validate CAPTCHA if (_captchaSettings.Enabled && _captchaSettings.ShowOnBlogCommentPage && !captchaValid) { ModelState.AddModelError("", _localizationService.GetResource("Common.WrongCaptcha")); } if (ModelState.IsValid) { var comment = new BlogComment { BlogPostId = blogPost.Id, CustomerId = _workContext.CurrentCustomer.Id, IpAddress = _webHelper.GetCurrentIpAddress(), CommentText = model.AddNewComment.CommentText, IsApproved = true }; _customerContentService.InsertCustomerContent(comment); //update totals _blogService.UpdateCommentTotals(blogPost); //notify a store owner if (_blogSettings.NotifyAboutNewBlogComments) { Services.MessageFactory.SendBlogCommentNotificationMessage(comment, _localizationSettings.DefaultAdminLanguageId); } //activity log _customerActivityService.InsertActivity("PublicStore.AddBlogComment", _localizationService.GetResource("ActivityLog.PublicStore.AddBlogComment")); NotifySuccess(T("Blog.Comments.SuccessfullyAdded")); var url = UrlHelper.GenerateUrl( routeName: "BlogPost", actionName: null, controllerName: null, protocol: null, hostName: null, fragment: "new-comment", routeValues: new RouteValueDictionary(new { blogPostId = blogPost.Id, SeName = blogPost.GetSeName(blogPost.LanguageId, ensureTwoPublishedLanguages: false) }), routeCollection: System.Web.Routing.RouteTable.Routes, requestContext: this.ControllerContext.RequestContext, includeImplicitMvcValues: true /*helps fill in the nulls above*/ ); return(Redirect(url)); } //If we got this far, something failed, redisplay form PrepareBlogPostModel(model, blogPost, true); return(View(model)); }
protected ProcessPaymentResult AuthorizeOrSale(ProcessPaymentRequest processPaymentRequest, bool authorizeOnly) { var result = new ProcessPaymentResult(); var customer = _customerService.GetCustomerById(processPaymentRequest.CustomerId); var req = new DoDirectPaymentReq(); req.DoDirectPaymentRequest = new DoDirectPaymentRequestType(); req.DoDirectPaymentRequest.Version = GetApiVersion(); var details = new DoDirectPaymentRequestDetailsType(); req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails = details; details.IPAddress = _webHelper.GetCurrentIpAddress(); if (authorizeOnly) { details.PaymentAction = PaymentActionCodeType.Authorization; } else { details.PaymentAction = PaymentActionCodeType.Sale; } //credit card details.CreditCard = new CreditCardDetailsType(); details.CreditCard.CreditCardNumber = processPaymentRequest.CreditCardNumber; details.CreditCard.CreditCardType = GetPaypalCreditCardType(processPaymentRequest.CreditCardType); details.CreditCard.ExpMonthSpecified = true; details.CreditCard.ExpMonth = processPaymentRequest.CreditCardExpireMonth; details.CreditCard.ExpYearSpecified = true; details.CreditCard.ExpYear = processPaymentRequest.CreditCardExpireYear; details.CreditCard.CVV2 = processPaymentRequest.CreditCardCvv2; details.CreditCard.CardOwner = new PayerInfoType(); details.CreditCard.CardOwner.PayerCountry = GetPaypalCountryCodeType(customer.BillingAddress.Country); details.CreditCard.CreditCardTypeSpecified = true; //billing address details.CreditCard.CardOwner.Address = new AddressType(); details.CreditCard.CardOwner.Address.CountrySpecified = true; details.CreditCard.CardOwner.Address.Street1 = customer.BillingAddress.Address1; details.CreditCard.CardOwner.Address.Street2 = customer.BillingAddress.Address2; details.CreditCard.CardOwner.Address.CityName = customer.BillingAddress.City; if (customer.BillingAddress.StateProvince != null) { details.CreditCard.CardOwner.Address.StateOrProvince = customer.BillingAddress.StateProvince.Abbreviation; } else { details.CreditCard.CardOwner.Address.StateOrProvince = "CA"; } details.CreditCard.CardOwner.Address.Country = GetPaypalCountryCodeType(customer.BillingAddress.Country); details.CreditCard.CardOwner.Address.PostalCode = customer.BillingAddress.ZipPostalCode; details.CreditCard.CardOwner.Payer = customer.BillingAddress.Email; details.CreditCard.CardOwner.PayerName = new PersonNameType(); details.CreditCard.CardOwner.PayerName.FirstName = customer.BillingAddress.FirstName; details.CreditCard.CardOwner.PayerName.LastName = customer.BillingAddress.LastName; //order totals var payPalCurrency = PaypalHelper.GetPaypalCurrency(_currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId)); details.PaymentDetails = new PaymentDetailsType(); details.PaymentDetails.OrderTotal = new BasicAmountType(); details.PaymentDetails.OrderTotal.Value = Math.Round(processPaymentRequest.OrderTotal, 2).ToString("N", new CultureInfo("en-us")); details.PaymentDetails.OrderTotal.currencyID = payPalCurrency; details.PaymentDetails.Custom = processPaymentRequest.OrderGuid.ToString(); details.PaymentDetails.ButtonSource = "nopCommerceCart"; //pass product names and totals to PayPal //if (_paypalDirectPaymentSettings.PassProductNamesAndTotals) //{ // //individual items // var cart = processPaymentRequest.Customer.ShoppingCartItems // .Where(x=>x.ShoppingCartType == ShoppingCartType.ShoppingCart) // .ToList(); // var cartItems = new PaymentDetailsItemType[cart.Count]; // for (int i = 0; i < cart.Count; i++) // { // var sc = cart[i]; // decimal taxRate = decimal.Zero; // var customer = processPaymentRequest.Customer; // decimal scUnitPrice = _priceCalculationService.GetUnitPrice(sc, true); // decimal scSubTotal = _priceCalculationService.GetSubTotal(sc, true); // decimal scUnitPriceInclTax = _taxService.GetProductPrice(sc.ProductVariant, scUnitPrice, true, customer, out taxRate); // decimal scUnitPriceExclTax = _taxService.GetProductPrice(sc.ProductVariant, scUnitPrice, false, customer, out taxRate); // //decimal scSubTotalInclTax = _taxService.GetProductPrice(sc.ProductVariant, scSubTotal, true, customer, out taxRate); // //decimal scSubTotalExclTax = _taxService.GetProductPrice(sc.ProductVariant, scSubTotal, false, customer, out taxRate); // cartItems[i] = new PaymentDetailsItemType() // { // Name = sc.ProductVariant.FullProductName, // Number = sc.ProductVariant.Id.ToString(), // Quantity = sc.Quantity.ToString(), // Amount = new BasicAmountType() // { // currencyID = payPalCurrency, // Value = scUnitPriceExclTax.ToString("N", new CultureInfo("en-us")), // }, // Tax = new BasicAmountType() // { // currencyID = payPalCurrency, // Value = (scUnitPriceInclTax - scUnitPriceExclTax).ToString("N", new CultureInfo("en-us")), // }, // }; // }; // details.PaymentDetails.PaymentDetailsItem = cartItems; // //other totals (undone) // details.PaymentDetails.ItemTotal = null; // details.PaymentDetails.ShippingTotal = null; // details.PaymentDetails.TaxTotal = null; // details.PaymentDetails.HandlingTotal = null; //} //shipping if (customer.ShippingAddress != null) { if (customer.ShippingAddress.StateProvince != null && customer.ShippingAddress.Country != null) { var shippingAddress = new AddressType(); shippingAddress.Name = customer.ShippingAddress.FirstName + " " + customer.ShippingAddress.LastName; shippingAddress.Street1 = customer.ShippingAddress.Address1; shippingAddress.CityName = customer.ShippingAddress.City; shippingAddress.StateOrProvince = customer.ShippingAddress.StateProvince.Abbreviation; shippingAddress.PostalCode = customer.ShippingAddress.ZipPostalCode; shippingAddress.Country = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), customer.ShippingAddress.Country.TwoLetterIsoCode, true); shippingAddress.CountrySpecified = true; details.PaymentDetails.ShipToAddress = shippingAddress; } } //send request using (var service2 = new PayPalAPIAASoapBinding()) { if (!_paypalDirectPaymentSettings.UseSandbox) { service2.Url = "https://api-3t.paypal.com/2.0/"; } else { service2.Url = "https://api-3t.sandbox.paypal.com/2.0/"; } service2.RequesterCredentials = new CustomSecurityHeaderType(); service2.RequesterCredentials.Credentials = new UserIdPasswordType(); service2.RequesterCredentials.Credentials.Username = _paypalDirectPaymentSettings.ApiAccountName; service2.RequesterCredentials.Credentials.Password = _paypalDirectPaymentSettings.ApiAccountPassword; service2.RequesterCredentials.Credentials.Signature = _paypalDirectPaymentSettings.Signature; service2.RequesterCredentials.Credentials.Subject = ""; DoDirectPaymentResponseType response = service2.DoDirectPayment(req); string error = ""; bool success = PaypalHelper.CheckSuccess(response, out error); if (success) { result.AvsResult = response.AVSCode; result.AuthorizationTransactionCode = response.CVV2Code; if (authorizeOnly) { result.AuthorizationTransactionId = response.TransactionID; result.AuthorizationTransactionResult = response.Ack.ToString(); result.NewPaymentStatus = PaymentStatus.Authorized; } else { result.CaptureTransactionId = response.TransactionID; result.CaptureTransactionResult = response.Ack.ToString(); result.NewPaymentStatus = PaymentStatus.Paid; } } else { result.AddError(error); } } return(result); }
public void Flush() { if (_entries.Count == 0) { return; } string ipAddress = ""; string pageUrl = ""; string referrerUrl = ""; try { ipAddress = _webHelper.GetCurrentIpAddress(); pageUrl = _webHelper.GetThisPageUrl(true); referrerUrl = _webHelper.GetUrlReferrer(); } catch { } _logRepository.AutoCommitEnabled = false; using (var scope = new DbContextScope(autoDetectChanges: false, proxyCreation: false, validateOnSave: false)) { foreach (var context in _entries) { if (context.ShortMessage.IsEmpty() && context.FullMessage.IsEmpty()) { continue; } Log log = null; try { string shortMessage = context.ShortMessage.NaIfEmpty(); string fullMessage = context.FullMessage.EmptyNull(); string contentHash = null; if (context.HashNotFullMessage || context.HashIpAddress) { contentHash = (shortMessage + (context.HashNotFullMessage ? "" : fullMessage) + (context.HashIpAddress ? ipAddress.EmptyNull() : "") ).Hash(Encoding.Unicode, true); } else { contentHash = (shortMessage + fullMessage).Hash(Encoding.Unicode, true); } log = _logRepository.Table.OrderByDescending(x => x.CreatedOnUtc).FirstOrDefault(x => x.ContentHash == contentHash); if (log == null) { log = new Log { Frequency = 1, LogLevel = context.LogLevel, ShortMessage = shortMessage, FullMessage = fullMessage, IpAddress = ipAddress, Customer = context.Customer, PageUrl = pageUrl, ReferrerUrl = referrerUrl, CreatedOnUtc = DateTime.UtcNow, ContentHash = contentHash }; _logRepository.Insert(log); } else { if (log.Frequency < 2147483647) { log.Frequency = log.Frequency + 1; } log.LogLevel = context.LogLevel; log.IpAddress = ipAddress; log.Customer = context.Customer; log.PageUrl = pageUrl; log.ReferrerUrl = referrerUrl; log.UpdatedOnUtc = DateTime.UtcNow; _logRepository.Update(log); } } catch (Exception ex) { ex.Dump(); } } try { // FIRE! _logRepository.Context.SaveChanges(); } catch { } } _logRepository.AutoCommitEnabled = true; _entries.Clear(); }
public virtual IActionResult TopicCreate(EditForumTopicModel model) { if (!_forumSettings.ForumsEnabled) { return(RedirectToRoute("HomePage")); } var forum = _forumService.GetForumById(model.ForumId); if (forum == null) { return(RedirectToRoute("Boards")); } if (ModelState.IsValid) { try { if (!_forumService.IsCustomerAllowedToCreateTopic(_workContext.CurrentCustomer, forum)) { return(Challenge()); } var subject = model.Subject; var maxSubjectLength = _forumSettings.TopicSubjectMaxLength; if (maxSubjectLength > 0 && subject.Length > maxSubjectLength) { subject = subject.Substring(0, maxSubjectLength); } var text = model.Text; var maxPostLength = _forumSettings.PostMaxLength; if (maxPostLength > 0 && text.Length > maxPostLength) { text = text.Substring(0, maxPostLength); } var topicType = ForumTopicType.Normal; var ipAddress = _webHelper.GetCurrentIpAddress(); var nowUtc = DateTime.UtcNow; if (_forumService.IsCustomerAllowedToSetTopicPriority(_workContext.CurrentCustomer)) { topicType = (ForumTopicType)Enum.ToObject(typeof(ForumTopicType), model.TopicTypeId); } //forum topic var forumTopic = new ForumTopic { ForumId = forum.Id, CustomerId = _workContext.CurrentCustomer.Id, TopicTypeId = (int)topicType, Subject = subject, CreatedOnUtc = nowUtc, UpdatedOnUtc = nowUtc }; _forumService.InsertTopic(forumTopic, true); //forum post var forumPost = new ForumPost { TopicId = forumTopic.Id, CustomerId = _workContext.CurrentCustomer.Id, Text = text, IPAddress = ipAddress, CreatedOnUtc = nowUtc, UpdatedOnUtc = nowUtc }; _forumService.InsertPost(forumPost, false); //update forum topic forumTopic.NumPosts = 1; forumTopic.LastPostId = forumPost.Id; forumTopic.LastPostCustomerId = forumPost.CustomerId; forumTopic.LastPostTime = forumPost.CreatedOnUtc; forumTopic.UpdatedOnUtc = nowUtc; _forumService.UpdateTopic(forumTopic); //subscription if (_forumService.IsCustomerAllowedToSubscribe(_workContext.CurrentCustomer)) { if (model.Subscribed) { var forumSubscription = new ForumSubscription { SubscriptionGuid = Guid.NewGuid(), CustomerId = _workContext.CurrentCustomer.Id, TopicId = forumTopic.Id, CreatedOnUtc = nowUtc }; _forumService.InsertSubscription(forumSubscription); } } return(RedirectToRoute("TopicSlug", new { id = forumTopic.Id, slug = _forumService.GetTopicSeName(forumTopic) })); } catch (Exception ex) { ModelState.AddModelError("", ex.Message); } } //redisplay form _forumModelFactory.PrepareTopicCreateModel(forum, model); return(View(model)); }
protected Customer GetCurrentCustomer() { if (_cachedCustomer != null) { return(_cachedCustomer); } Customer customer = null; if (_httpContext != null) { //check whether request is made by a search engine //in this case return built-in customer record for search engines //or comment the following two lines of code in order to disable this functionality if (_webHelper.IsSearchEngine(_httpContext.Request)) { customer = _customerService.GetCustomerBySystemName(SystemCustomerNames.SearchEngine); } //registered user if (customer == null || customer.Deleted || !customer.Active) { customer = _authenticationService.GetAuthenticatedCustomer(); } //impersonate user if required (currently used for 'phone order' support) //and validate that the current user is admin if (customer != null && !customer.Deleted && customer.Active) { if (customer.IsAdmin()) { int?impersonatedCustomerId = customer.GetAttribute <int?>(SystemCustomerAttributeNames.ImpersonatedCustomerId); if (impersonatedCustomerId.HasValue && impersonatedCustomerId.Value > 0) { var impersonatedCustomer = _customerService.GetCustomerById(impersonatedCustomerId.Value); if (impersonatedCustomer != null && !impersonatedCustomer.Deleted && impersonatedCustomer.Active) { //set impersonated customer _originalCustomerIfImpersonated = customer; customer = impersonatedCustomer; } } } } //load guest customer if (customer == null || customer.Deleted || !customer.Active) { var customerCookie = GetCustomerCookie(); if (customerCookie != null && !String.IsNullOrEmpty(customerCookie.Value)) { Guid customerGuid; if (Guid.TryParse(customerCookie.Value, out customerGuid)) { var customerByCookie = _customerService.GetCustomerByGuid(customerGuid); if (customerByCookie != null && //this customer (from cookie) should not be registered !customerByCookie.IsRegistered() && //it should not be a built-in 'search engine' customer account !customerByCookie.IsSearchEngineAccount()) { customer = customerByCookie; } } } } //create guest if not exists if (customer == null || customer.Deleted || !customer.Active) { customer = _customerService.InsertGuestCustomer(); } SetCustomerCookie(customer.CustomerGuid); } //validation if (customer != null && !customer.Deleted && customer.Active) { //update last activity date if (customer.LastActivityDateUtc.AddMinutes(1.0) < DateTime.UtcNow) { customer.LastActivityDateUtc = DateTime.UtcNow; _customerService.UpdateCustomer(customer); } //update IP address string currentIpAddress = _webHelper.GetCurrentIpAddress(); if (!String.IsNullOrEmpty(currentIpAddress)) { if (!currentIpAddress.Equals(customer.LastIpAddress)) { customer.LastIpAddress = currentIpAddress; _customerService.UpdateCustomer(customer); } } _cachedCustomer = customer; } return(_cachedCustomer); }
protected ProcessPaymentResult AuthorizeOrSale(ProcessPaymentRequest processPaymentRequest, bool authorizeOnly) { var result = new ProcessPaymentResult(); var customer = _customerService.GetCustomerById(processPaymentRequest.CustomerId); if (customer == null) { throw new Exception("Customer cannot be loaded"); } var req = new DoDirectPaymentReq(); req.DoDirectPaymentRequest = new DoDirectPaymentRequestType(); req.DoDirectPaymentRequest.Version = GetApiVersion(); var details = new DoDirectPaymentRequestDetailsType(); req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails = details; details.IPAddress = _webHelper.GetCurrentIpAddress() ?? ""; if (authorizeOnly) { details.PaymentAction = PaymentActionCodeType.AUTHORIZATION; } else { details.PaymentAction = PaymentActionCodeType.SALE; } //credit card details.CreditCard = new CreditCardDetailsType(); details.CreditCard.CreditCardNumber = processPaymentRequest.CreditCardNumber; details.CreditCard.CreditCardType = GetPaypalCreditCardType(processPaymentRequest.CreditCardType); details.CreditCard.ExpMonth = processPaymentRequest.CreditCardExpireMonth; details.CreditCard.ExpYear = processPaymentRequest.CreditCardExpireYear; details.CreditCard.CVV2 = processPaymentRequest.CreditCardCvv2; details.CreditCard.CardOwner = new PayerInfoType(); var country = EngineContext.Current.Resolve <ICountryService>().GetCountryById(customer.BillingAddress.CountryId); details.CreditCard.CardOwner.PayerCountry = GetPaypalCountryCodeType(country); //billing address details.CreditCard.CardOwner.Address = new AddressType(); details.CreditCard.CardOwner.Address.Street1 = customer.BillingAddress.Address1; details.CreditCard.CardOwner.Address.Street2 = customer.BillingAddress.Address2; details.CreditCard.CardOwner.Address.CityName = customer.BillingAddress.City; if (customer.BillingAddress.StateProvinceId != 0) { var state = EngineContext.Current.Resolve <IStateProvinceService>().GetStateProvinceById(customer.BillingAddress.StateProvinceId); details.CreditCard.CardOwner.Address.StateOrProvince = state.Abbreviation; } else { details.CreditCard.CardOwner.Address.StateOrProvince = "CA"; } details.CreditCard.CardOwner.Address.Country = GetPaypalCountryCodeType(country); details.CreditCard.CardOwner.Address.PostalCode = customer.BillingAddress.ZipPostalCode; details.CreditCard.CardOwner.Payer = customer.BillingAddress.Email; details.CreditCard.CardOwner.PayerName = new PersonNameType(); details.CreditCard.CardOwner.PayerName.FirstName = customer.BillingAddress.FirstName; details.CreditCard.CardOwner.PayerName.LastName = customer.BillingAddress.LastName; //order totals var payPalCurrency = PaypalHelper.GetPaypalCurrency(_currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId)); details.PaymentDetails = new PaymentDetailsType(); details.PaymentDetails.OrderTotal = new BasicAmountType(); details.PaymentDetails.OrderTotal.value = Math.Round(processPaymentRequest.OrderTotal, 2).ToString("N", new CultureInfo("en-us")); details.PaymentDetails.OrderTotal.currencyID = payPalCurrency; details.PaymentDetails.Custom = processPaymentRequest.OrderGuid.ToString(); details.PaymentDetails.ButtonSource = "nopCommerceCart"; //shipping if (customer.ShippingAddress != null) { if (customer.ShippingAddress.StateProvinceId != 0 && customer.ShippingAddress.CountryId != 0) { var state = EngineContext.Current.Resolve <IStateProvinceService>().GetStateProvinceById(customer.ShippingAddress.StateProvinceId); var countryshipping = EngineContext.Current.Resolve <ICountryService>().GetCountryById(customer.ShippingAddress.CountryId); var shippingAddress = new AddressType(); shippingAddress.Name = customer.ShippingAddress.FirstName + " " + customer.ShippingAddress.LastName; shippingAddress.Street1 = customer.ShippingAddress.Address1; shippingAddress.Street2 = customer.ShippingAddress.Address2; shippingAddress.CityName = customer.ShippingAddress.City; shippingAddress.StateOrProvince = state.Abbreviation; shippingAddress.PostalCode = customer.ShippingAddress.ZipPostalCode; shippingAddress.Country = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), countryshipping.TwoLetterIsoCode, true); details.PaymentDetails.ShipToAddress = shippingAddress; } } //send request var service = GetService(); DoDirectPaymentResponseType response = service.DoDirectPayment(req); string error; bool success = PaypalHelper.CheckSuccess(response, out error); if (success) { result.AvsResult = response.AVSCode; result.AuthorizationTransactionCode = response.CVV2Code; if (authorizeOnly) { result.AuthorizationTransactionId = response.TransactionID; result.AuthorizationTransactionResult = response.Ack.ToString(); result.NewPaymentStatus = PaymentStatus.Authorized; } else { result.CaptureTransactionId = response.TransactionID; result.CaptureTransactionResult = response.Ack.ToString(); result.NewPaymentStatus = PaymentStatus.Paid; } } else { result.AddError(error); } return(result); }
public JsonResult CityJson() { var location = _locationService.GetLocation(_webHelper.GetCurrentIpAddress()); return(Json(_localizationService.GetResource(string.Format("cities.{0}", location?.city)))); }
public virtual JsonResult GetCityJson(IWebHelper webHelper, ILocationService locationService) { var location = locationService.GetLocation(webHelper.GetCurrentIpAddress()); return(Json(location?.city)); }