示例#1
0
        public HttpResponseMessage UploadPhoto()
        {
            var currentHosting = _webHelper.GetStoreHost(_webHelper.IsCurrentConnectionSecured()).TrimEnd('/');

            List <UploadPhotoModelView> images = new List <UploadPhotoModelView>();
            int fileCount = HttpContext.Current.Request.Files.Count;

            for (int i = 0; i < fileCount; i++)
            {
                HttpPostedFile file     = HttpContext.Current.Request.Files[i];
                var            fileName = Path.GetFileName(file.FileName);

                var data      = StreamHelper.ReadToEnd(file.InputStream);
                var pictureId = _mediaService.InsertPicture(new UploadFileRequest
                {
                    SourceTarget = EMediaFileSourceTarget.ImageDisk,
                    Binary       = data,
                    MimeType     = file.ContentType,
                    StoragePath  = ApplicationSettings.ImageStoragePath,
                    Path         = $"{Guid.NewGuid()}{Path.GetExtension(fileName)}"
                });
                var imageUrl = _mediaService.GetPictureUrl(pictureId);
                images.Add(new UploadPhotoModelView
                {
                    Id       = pictureId,
                    FilePath = imageUrl,
                    FileUrl  = $"{currentHosting}{imageUrl}",
                });
            }
            JsonDataResult.Data = new { images = images };
            return(this.CreateResponseMessage());
        }
示例#2
0
        public async Task <IHttpActionResult> GetArtists()
        {
            var currentHosting = _webHelper.GetStoreHost(_webHelper.IsCurrentConnectionSecured()).TrimEnd('/');
            var artists        = await _artistRepository.Table.OrderBy(p => p.Seq).ToListAsync();

            var imageUrls = artists.Where(p => p.ImageId > 0).Select(p => p.ImageId)
                            .Select(p => new { ImageId = p, ImageUrl = $"{currentHosting}{_mediaService.GetPictureUrl(p)}" });

            return(Ok(artists.Select(p =>
            {
                var imageUrl = imageUrls.Where(i => i.ImageId == p.ImageId).Select(i => i.ImageUrl).FirstOrDefault();
                return new
                {
                    p.Id,
                    p.ImageId,
                    p.Name,
                    p.Seq,
                    p.ShowOnHompage,
                    ImageUrl = imageUrl,
                    Image = new
                    {
                        imageId = p.ImageId,
                        imageUrl = imageUrl
                    }
                };
            })));
        }
示例#3
0
 public void Can_get_storeHost_with_ssl()
 {
     var serverVariables = new NameValueCollection();
     serverVariables.Add("HTTP_HOST", "www.example.com");
     _httpContext = new FakeHttpContext("~/", "GET", null, null, null, null, null, serverVariables);
     _webHelper = new WebHelper(_httpContext);
     _webHelper.GetStoreHost(true).ShouldEqual("https://www.example.com/");
 }
示例#4
0
        public void Can_get_storeHost_with_ssl()
        {
            var serverVariables = new NameValueCollection();

            serverVariables.Add("HTTP_HOST", "www.example.com");
            _httpContext = new FakeHttpContext("~/", "GET", null, null, null, null, null, serverVariables);
            _webHelper   = new WebHelper(_httpContext);
            _webHelper.GetStoreHost(true).ShouldEqual("https://www.example.com/");
        }
        /// <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)
        {
            ClientSelfPostForm GTpaySubmitForm = new ClientSelfPostForm();

            GTpaySubmitForm.ActionURL   = _GTpayPaymentSettings.PostUrl;
            GTpaySubmitForm.Method      = "POST";
            GTpaySubmitForm.RedirectMsg = "Redirecting you to the payment Gateway (this will take a few seconds)";

            GTpaySubmitForm["gtpay_mert_id"] = _GTpayPaymentSettings.MerchantID;
            //sendToSecure.Add("gtpay_return_url", SiteConfiguration.gtpay_return_url);
            GTpaySubmitForm["gtpay_tranx_curr"] = _GTpayPaymentSettings.CurrencyCode;
            GTpaySubmitForm["gtpay_gway_first"] = _GTpayPaymentSettings.ShowGateWayFirst;

            if (_GTpayPaymentSettings.ShowGateWayFirst == "yes")
            {
                GTpaySubmitForm["gtpay_gway_name"] = _GTpayPaymentSettings.GateWayName;
            }
            GTpaySubmitForm["gtpay_cust_id"]   = postProcessPaymentRequest.Order.CustomerId.ToString();
            GTpaySubmitForm["gtpay_cust_name"] = postProcessPaymentRequest.Order.BillingAddress.FirstName + " " + postProcessPaymentRequest.Order.BillingAddress.LastName;

            int i           = 1;
            var actualTotal = Math.Round(postProcessPaymentRequest.Order.OrderTotal, 2);



            var amt          = actualTotal.ToString("0.00");
            var final        = amt.Split('.');
            var postedAmount = final[0] + final[1];

            GTpaySubmitForm["gtpay_tranx_amt"]  = postedAmount;
            GTpaySubmitForm["gtpay_tranx_memo"] = "Online Shopping @ " + _webHelper.GetStoreHost(false);//pass store name here


            var orderid = postProcessPaymentRequest.Order.Id;

            var hash = string.Empty;
            // [gtpay_tranx_id + gtpay_tranx_amt + gtpay_tranx_noti_url + hashkey]
            string returnUrl = _webHelper.GetStoreLocation(false) + "Plugins/PaymentGTpay/PDTHandler";
            var    hashdata  = postProcessPaymentRequest.Order.OrderGuid + "|" + orderid + postedAmount + returnUrl + "?txid=" + postProcessPaymentRequest.Order.OrderGuid + "|" + orderid + _GTpayPaymentSettings.HashCode;

            hash = Hash.GetHashMini(hashdata, Hash.HashType.SHA512); //GetSHA512(hashdata);

            GTpaySubmitForm["gtpay_tranx_hash"] = hash;

            GTpaySubmitForm["gtpay_tranx_id"]       = postProcessPaymentRequest.Order.OrderGuid + "|" + orderid;
            GTpaySubmitForm["gtpay_tranx_noti_url"] = returnUrl + "?txid=" + postProcessPaymentRequest.Order.OrderGuid + "|" + orderid;
            GTpaySubmitForm["gtpay_echo_data"]      = postProcessPaymentRequest.Order.OrderGuid + "|" + orderid;

            _httpContext.Response.Clear();
            _httpContext.Response.Write(GTpaySubmitForm.Build());
            _httpContext.Response.Flush();
            _httpContext.Response.End();
        }
示例#6
0
        public void Can_get_storeHost_with_ssl()
        {
            NameValueCollection serverVariablesCollection = new NameValueCollection();

            string link = "www.xaaxaxxaxa.com";

            serverVariablesCollection.Add("HTTP_HOST", link);
            _fakeHttpContext = new FakeHttpContext("~/", "GET", null, null, null, null, null, serverVariablesCollection);
            _webHelper       = new WebHelper(_fakeHttpContext);

            link = "https://" + link + "/"; //adding "https://" (not http !)
            Assert.AreEqual(link, _webHelper.GetStoreHost(true));
            //GetStoreHost(true) returns https://www.xaaxaxxaxa.com/
        }
示例#7
0
        public static string GetBaseUrl(this IWebHelper helper)
        {
            var result = "http";

            if (helper.IsCurrentConnectionSecured())
            {
                result += "s";
            }

            result += "://";

            result += helper.GetStoreHost(false).Replace("http://", "");

            return(result);
        }
        public IActionResult Get()
        {
            var cnfg  = _BotConfigService.Get();
            var url   = _webHelper.GetStoreHost(true);
            var Token = "";

            if (cnfg == null /*|| cnfg.IsActive == false*/)
            {
                return(Redirect("/Admin/Farabot/Config"));
            }

            Token = cnfg.TokenApi;
            Models.Bot.GetBotClientAsync(Token, url).Wait();

            return(Redirect("/Admin/Farabot/Config"));
        }
示例#9
0
        public async Task <HttpResponseMessage> GetArticle(int id)
        {
            var currentHosting = _webHelper.GetStoreHost(_webHelper.IsCurrentConnectionSecured()).TrimEnd('/');
            var article        = await _articleRepository.Table.AsNoTracking().Where(p => p.Id == id)
                                 .Include(p => p.ArticleLanguages)
                                 .Include("ArticleLanguages.MetaTag").Select(p => new ArticleModelView
            {
                Id               = p.Id,
                CreatedDate      = p.CreatedDate,
                HeadLine         = p.HeadLine,
                ModifiedDate     = p.ModifiedDate,
                PublishDate      = p.PublishDate,
                FeatureImageId   = p.FeatureImageId,
                IsActive         = p.IsActive,
                IsShowHomepage   = p.IsShowHomepage,
                Section1         = p.Section1,
                Section2         = p.Section2,
                ArticleLanguages = p.ArticleLanguages.Select(al => new ArticleLanguageModelView
                {
                    Id         = al.Id,
                    Content    = al.Content,
                    Extract    = al.Extract,
                    HeadLine   = al.HeadLine,
                    LanguageId = al.LanguageId,
                    MetaTag    = al.MetaTag,
                    MetaTagId  = al.MetaTagId
                })
            }).FirstOrDefaultAsync();

            if (article != null && article.FeatureImageId.HasValue)
            {
                article.FeatureImage = new ImageModelView {
                    ImageUrl = $"{currentHosting}{ _mediaService.GetPictureUrl(article.FeatureImageId.Value)}", ImageId = article.FeatureImageId.Value
                };
            }
            return(Request.CreateResponse(HttpStatusCode.OK, article));
        }
        public ActionResult <JObject> CompanyToken([FromBody] CompanyTokenRequest tokenRequest)
        {
            // discover endpoints from metadata
            var client = new HttpClient();
            var disco  = client.GetDiscoveryDocumentAsync(new DiscoveryDocumentRequest
            {
                Address = _webHelper.GetStoreHost(false),
                Policy  = { RequireHttps = false }
            }).Result;

            if (disco.IsError)
            {
                throw new NGPException(disco.Error);
            }

            //获取人员Id
            var workContext = EngineContext.Current.Resolve <IWorkContext>();
            var employee    = _repository.FindById <SysOrg_Employee>(workContext.Current.EmplId);

            // request token
            var request = new PasswordTokenRequest
            {
                Address      = disco.TokenEndpoint,
                ClientId     = "debt_api_client",
                ClientSecret = "debt_secret",
                UserName     = employee.LoginName,
                Password     = CommonHelper.Decrypt(employee.Password),
                GrantType    = GrantType.ResourceOwnerPassword
            };

            request.Parameters["company_id"] = tokenRequest.CompanyId;

            var tokenResponse = client.RequestPasswordTokenAsync(request).Result;

            return(Ok(tokenResponse.Json));
        }
示例#11
0
 public void Can_get_storeHost_without_ssl()
 {
     _webHelper.GetStoreHost(false).ShouldEqual("http://www.Example.com/");
 }
示例#12
0
        public ActionResult ProcessPayment(FormCollection form)
        {
            var model     = new WeiXinPaymentModel(Path.Combine(_webHelper.GetStoreHost(_webHelper.IsCurrentConnectionSecured()), "Plugins/PaymentWeiXin/QueryOrder"));
            var error     = new WeiXinPaymentErrorModel();
            var processor = _paymentService.LoadPaymentMethodBySystemName("Payments.WeiXin") as WeiXinPaymentProcessor;

            if (processor == null ||
                !processor.IsPaymentMethodActive(_paymentSettings) || !processor.PluginDescriptor.Installed)
            {
                error.Message = "微信支付服务终止";
            }
            else
            {
                try
                {
                    if (form.HasKeys())
                    {
                        if (!string.IsNullOrWhiteSpace(form["result"]))
                        {
                            var wxModel = new WxPayData();
                            wxModel.FromXml(HttpUtility.HtmlDecode(form["result"]), _weiXinPaymentSettings.AppSecret);


                            if (wxModel.IsSet("code_url"))
                            {
                                model.QRCode = processor.GetQrCode(wxModel.GetValue("code_url").ToString());


                                if (!string.IsNullOrWhiteSpace(form["orderid"]))
                                {
                                    int orderId;
                                    if (int.TryParse(form["orderid"], out orderId))
                                    {
                                        var order = _orderService.GetOrderById(orderId);
                                        if (order != null)
                                        {
                                            if (order.Customer.Id == _workContext.CurrentCustomer.Id)
                                            {
                                                if (_orderProcessingService.CanMarkOrderAsPaid(order))
                                                {
                                                    if (!string.IsNullOrWhiteSpace(form["total"]) &&
                                                        form["total"] == order.OrderTotal.ToString("0.00"))
                                                    {
                                                        model.OrderId = order.Id.ToString(CultureInfo.InvariantCulture);
                                                        model.Total   = order.OrderTotal.ToString("¥0.00");
                                                    }
                                                    else
                                                    {
                                                        error.Message = "价格不匹配";
                                                    }
                                                }
                                                else
                                                {
                                                    if (order.PaymentStatus == PaymentStatus.Paid)
                                                    {
                                                        error.Message = "您已付款,请勿重复提交";
                                                    }
                                                    else
                                                    {
                                                        error.Message = "订单状态错误";
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                error.Message = "用户不匹配";
                                            }
                                        }
                                        else
                                        {
                                            error.Message = "订单号不存在";
                                        }
                                    }
                                    else
                                    {
                                        error.Message = "无法读取订单号";
                                    }
                                }
                                else
                                {
                                    error.Message = "订单号丢失";
                                }
                            }
                            else
                            {
                                error.Message = "无法读取二维码";
                            }
                        }
                        else if (!string.IsNullOrWhiteSpace(form["nativeUrl"]))
                        {
                            model.QRCode = processor.GetQrCode(form["nativeUrl"]);

                            if (!string.IsNullOrWhiteSpace(form["orderid"]))
                            {
                                int orderId;
                                if (int.TryParse(form["orderid"], out orderId))
                                {
                                    var order = _orderService.GetOrderById(orderId);
                                    if (order != null)
                                    {
                                        if (order.Customer.Id == _workContext.CurrentCustomer.Id)
                                        {
                                            if (_orderProcessingService.CanMarkOrderAsPaid(order))
                                            {
                                                if (!string.IsNullOrWhiteSpace(form["total"]) &&
                                                    form["total"] == order.OrderTotal.ToString("0.00"))
                                                {
                                                    model.OrderId = order.Id.ToString(CultureInfo.InvariantCulture);
                                                    model.Total   = order.OrderTotal.ToString("¥0.00");
                                                }
                                                else
                                                {
                                                    error.Message = "价格不匹配";
                                                }
                                            }
                                            else
                                            {
                                                if (order.PaymentStatus == PaymentStatus.Paid)
                                                {
                                                    error.Message = "您已付款,请勿重复提交";
                                                }
                                                else
                                                {
                                                    error.Message = "订单状态错误";
                                                }
                                            }
                                        }
                                        else
                                        {
                                            error.Message = "用户不匹配";
                                        }
                                    }
                                    else
                                    {
                                        error.Message = "订单号不存在";
                                    }
                                }
                                else
                                {
                                    error.Message = "无法读取订单号";
                                }
                            }
                            else
                            {
                                error.Message = "订单号丢失";
                            }
                        }
                        else
                        {
                            error.Message = "参数错误";
                        }
                    }
                    else
                    {
                        error.Message = "没有参数";
                    }
                }
                catch (NopException ex)
                {
                    error.Message = ex.Message;
                }
            }



            if (error.HasError)
            {
                return(View("~/Plugins/Payments.WeiXin/Views/PaymentWeiXin/Error.cshtml", error));
            }
            return(View("~/Plugins/Payments.WeiXin/Views/PaymentWeiXin/ProcessPayment.cshtml", model));
        }
        public void AddUserTokens(IList <Token> tokens, User user)
        {
            tokens.Add(new Token("User.Email", user.EmailAddress));
            tokens.Add(new Token("User.Username", user.UserName));
            tokens.Add(new Token("User.Surname", user.Surname));
            tokens.Add(new Token("User.Name", user.Name));

            //note: we do not use SEO friendly URLS because we can get errors caused by having .(dot) in the URL (from the email address)
            //TODO add a method for getting URL (use routing because it handles all SEO friendly URLs)
            string passwordRecoveryUrl  = string.Format("{0}passwordrecovery/confirm?token={1}&email={2}", _webHelper.GetStoreHost(false), user.PasswordResetCode, HttpUtility.UrlEncode(user.EmailAddress));
            string accountActivationUrl = string.Format("{0}customer/activation?token={1}&email={2}", _webHelper.GetStoreHost(false), user.EmailConfirmationCode, HttpUtility.UrlEncode(user.EmailAddress));

            tokens.Add(new Token("Customer.PasswordRecoveryURL", passwordRecoveryUrl, true));
            tokens.Add(new Token("Customer.AccountActivationURL", accountActivationUrl, true));
        }
示例#14
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)
        {
            var customerValues = postProcessPaymentRequest.Order.DeserializeCustomValues();
            var isJsPay        = false;

            if (_httpContext.Session["isJsPay"] != null)
            {
                isJsPay = _httpContext.Session["isJsPay"].ToString().ToLower() == "true";
            }

            string openId = null;

            if (isJsPay)
            {
                var weiXinAuthentication =
                    _workContext.CurrentCustomer.ExternalAuthenticationRecords.FirstOrDefault(
                        q => q.ProviderSystemName == "ExternalAuth.WeiXin");
                if (weiXinAuthentication != null)
                {
                    openId = weiXinAuthentication.ExternalIdentifier;
                }
                else
                {
                    isJsPay = false;
                }
            }


            string productId, body;
            var    firstProduct = postProcessPaymentRequest.Order.OrderItems.FirstOrDefault();

            if (firstProduct != null)
            {
                productId = firstProduct.Product.Id.ToString(CultureInfo.InvariantCulture);
                body      = firstProduct.Product.GetLocalized(q => q.Name);
            }
            else
            {
                productId = postProcessPaymentRequest.Order.Id.ToString(CultureInfo.InvariantCulture);
                body      = postProcessPaymentRequest.Order.Id.ToString(CultureInfo.InvariantCulture);
            }

            string detail = string.Join(", ",
                                        postProcessPaymentRequest.Order.OrderItems.Select(q => q.Product.GetLocalized(p => p.Name)));
            string orderId = postProcessPaymentRequest.Order.Id.ToString(CultureInfo.InvariantCulture);
            string total   = ((int)(postProcessPaymentRequest.Order.OrderTotal * 100)).ToString(CultureInfo.InvariantCulture);

            var post = new RemotePost();

            post.FormName = "weixinpayment";
            post.Method   = "POST";
            post.Add("orderid", postProcessPaymentRequest.Order.Id.ToString(CultureInfo.InvariantCulture));
            post.Add("total", postProcessPaymentRequest.Order.OrderTotal.ToString("0.00"));
            if (isJsPay && !string.IsNullOrWhiteSpace(openId))
            {
                var jsApiPay = new JsApiPay(_weiXinPaymentSettings, Path.Combine(_webHelper.GetStoreHost(_webHelper.IsCurrentConnectionSecured()), "onepagecheckout"));
                jsApiPay.Openid   = openId;
                jsApiPay.TotalFee = total;

                var unifiedOrderResult = jsApiPay.GetUnifiedOrderResult(postProcessPaymentRequest.Order.Id, _webHelper.GetCurrentIpAddress(), _notifyUrl);

                var data = new WxPayData();


                var timestamp = CommonExtension.GetCurrentTimeStamp().ToString();
                var nonceStr  = Guid.NewGuid().ToString("N");



                data.SetValue("appId", _weiXinPaymentSettings.AppId);
                data.SetValue("timeStamp", timestamp);
                data.SetValue("nonceStr", nonceStr);
                data.SetValue("package", "prepay_id=" + unifiedOrderResult.GetValue("prepay_id"));
                data.SetValue("signType", "MD5");
                var sign = data.MakeSign(_weiXinPaymentSettings.AppSecret);


                post.Add("appId", _weiXinPaymentSettings.AppId);
                post.Add("timeStamp", timestamp);
                post.Add("nonceStr", nonceStr);
                post.Add("package", "prepay_id=" + unifiedOrderResult.GetValue("prepay_id"));
                post.Add("signType", "MD5");
                post.Add("paySign", sign);

                post.Url = Path.Combine(_webHelper.GetStoreHost(_webHelper.IsCurrentConnectionSecured()), "Plugins/PaymentWeiXin/JsApiPayment/");
                post.Post();
            }
            else
            {
                post.Url = Path.Combine(_webHelper.GetStoreHost(_webHelper.IsCurrentConnectionSecured()), "Plugins/PaymentWeiXin/ProcessPayment");
                post.Add("nativeUrl", GetUrlForMethodOne(postProcessPaymentRequest.Order.Id));
                //var result = Unifiedorder(productId, body, detail, orderId, total);
                //post.Add("result", HttpUtility.HtmlEncode(result));
                post.Post();
            }
        }
 public void CanGetStoreHostWithoutSsl()
 {
     _webHelper.GetStoreHost(false).Should().Be($"http://{NopTestsDefaults.HostIpAddress}/");
 }
        public ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var    result = new ProcessPaymentResult();
            string Authority;

            System.Net.ServicePointManager.Expect100Continue = false;
            var zp = new ZarinPalWebService.PaymentGatewayImplementationService();

            var storeScope = this.GetActiveStoreScopeConfiguration(_storeService, _workContext);
            var payPalStandardPaymentSettings = _settingService.LoadSetting <ZarinPalPaymentSettings>(storeScope);

            var email        = processPaymentRequest.CustomValues["EMail"];
            var merchantCode = payPalStandardPaymentSettings.MerchantCode;
            var description  = payPalStandardPaymentSettings.Description;
            var phonenumber  = processPaymentRequest.CustomValues["Phonenumber"];
            var userSsl      = payPalStandardPaymentSettings.UseSsl;
            var currencyId   = payPalStandardPaymentSettings.CurrencyId;

            //processPaymentRequest.CustomValues.Clear();

            //check configurations fileds
            if (string.IsNullOrWhiteSpace(merchantCode) || string.IsNullOrWhiteSpace(description) || currencyId == 0)
            {
                result.AddError(
                    _localizationService.GetResource("Plugins.Payments.ZarinPal.ErrorOccurred"));

                result.NewPaymentStatus = PaymentStatus.Voided;
                return(result);
            }

            //get base url
            var baseUrl = _webHelper.GetStoreHost(userSsl);

            //get currency for convert to target currency
            var sourceCurrency = _currencyService.GetCurrencyById(_workContext.WorkingCurrency.Id);
            var targetCurrency = _currencyService.GetCurrencyById(currencyId);

            //get converted price
            var finalPrice = _currencyService.ConvertCurrency(processPaymentRequest.OrderTotal, sourceCurrency, targetCurrency);

            if (email == null)
            {
                email = "";
            }
            if (phonenumber == null)
            {
                phonenumber = "";
            }

            //send information to bank and get status
            var status = zp.PaymentRequest(merchantCode, (int)finalPrice,
                                           description, email.ToString(), phonenumber.ToString(),
                                           baseUrl + "Plugins/PaymentZarinPal/Result", out Authority);

            //retuened status from bank
            if (status == 100)
            {
                result.NewPaymentStatus = PaymentStatus.Pending;
            }
            else
            {
                result.NewPaymentStatus = PaymentStatus.Voided;
                result.AddError(_localizationService.GetResource("Plugins.Payments.ZarinPal.ErrorOccurred"));
            }

            result.AuthorizationTransactionCode = Authority;

            return(result);
        }