using MAX.Core.Autofac; using MAX.Core.DependencyInjection; using MAX.Core.Helpers; using MAX.Core.Logger; using Store.Client.Extensions; using System; using System.Net; using System.Text; namespace Store.Client.HttpExtension { /// /// Store 基础 API 请求基类。 /// 项目 API 可以继承该基类并重写 ServiceConfigKey,使用项目自己的服务配置。 /// public class AppApiRequestBase { /// /// 日志。 /// [Autowired] protected ILoggerFacade _logger => LazyServiceProvider.Instance.LazyGetService(); protected IApiServerConfig _config => LazyServiceProvider.Instance.LazyGetService(); /// /// 默认服务请求。 /// protected HttpResult Post(string urlpath, string postdata = "") { return Request(BuildServiceUrl(urlpath), postdata); } /// /// 公共签名服务请求。 /// protected HttpResult PostPublic(string urlpath, string postdata = "") { return Request(BuildServiceUrl(urlpath), postdata, isUserSign: false); } /// /// 拼多多服务请求。 /// protected HttpResult PostPdd(string urlpath, string postdata = "") { return Request(BuildServiceUrl("bxx_" + urlpath), postdata); } /// /// 微信服务请求。 /// protected HttpResult PostWx(string urlpath, string postdata = "") { return Request(BuildServiceUrl("wxxd_" + urlpath), postdata); } /// /// 微信图片服务请求。 /// protected HttpResult PostWxImg(string urlpath, string postdata = "") { return Request(BuildServiceUrl("wxxd_" + urlpath), postdata); } /// /// 默认兼容服务请求。 /// protected HttpResult PostDefault(string urlpath, string postdata = "") { return Request(BuildServiceUrl(urlpath), postdata); } /// /// 使用当前 Key 构建服务请求地址。 /// protected string BuildServiceUrl(string urlPath) { return $"{_config.Host}/wxxd_{urlPath}?obj=29wx/wxxd_{urlPath}"; } /// /// 创建并执行服务端请求,默认使用当前用户签名。 /// protected HttpResult Request(string url, string postdata = "", MethodType method = MethodType.Post, bool isUserSign = true) { ServerHttpItem item = new ServerHttpItem { URL = url, Method = method, Postdata = postdata ?? string.Empty }; if (isUserSign) { item.SignUser(); } return ServerRequest(item); } /// /// 服务器请求。 /// public HttpResult ServerRequest(ServerHttpItem item) { if (item == null) { throw new ArgumentNullException(nameof(item)); } #if RELEASE item.WebProxy = null; #endif if (!item.IsSign) { if (item.Shop != null) { item.SignUser(item.Shop.Id, item.Shop.Name); } else { item.Sign(); } } return Send(item); } /// /// 执行底层 HTTP 请求。 /// protected HttpResult Send(ServerHttpItem item) { if (item == null) { throw new ArgumentNullException(nameof(item)); } if (string.IsNullOrWhiteSpace(item.URL)) { throw new ArgumentException("请求地址不能为空。", nameof(item)); } if (!item.URL.StartsWith("http", StringComparison.OrdinalIgnoreCase)) { item.URL = _config.Host + "/" + item.URL.TrimStart('/'); } item.Encoding = Encoding.UTF8; HttpResult result = HttpHelper.Request(item); if (result.StatusCode == HttpStatusCode.OK && !string.IsNullOrEmpty(result.Html) && result.Html[0] == 65279) { result.Html = result.Html.Remove(0, 1); } return result; } } }