diff --git a/BBWY.Server.API/Controllers/YunDingController.cs b/BBWY.Server.API/Controllers/YunDingController.cs new file mode 100644 index 00000000..4154de19 --- /dev/null +++ b/BBWY.Server.API/Controllers/YunDingController.cs @@ -0,0 +1,26 @@ +using BBWY.Server.Business; +using BBWY.Server.Model.Db; +using Microsoft.AspNetCore.Mvc; + +// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 + +namespace BBWY.Server.API.Controllers +{ + [Produces("application/json")] + [Route("Api/[Controller]/[Action]")] + [ApiController] + public class YunDingController : ControllerBase + { + private YunDingBusiness yunDingBusiness; + public YunDingController(YunDingBusiness yunDingBusiness) + { + this.yunDingBusiness = yunDingBusiness; + } + + [HttpGet] + public void CreateKey() + { + yunDingBusiness.CreateKey(); + } + } +} diff --git a/BBWY.Server.API/Startup.cs b/BBWY.Server.API/Startup.cs index 3dd4b4ff..819743d3 100644 --- a/BBWY.Server.API/Startup.cs +++ b/BBWY.Server.API/Startup.cs @@ -134,8 +134,9 @@ namespace BBWY.Server.API } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. - public void Configure(IApplicationBuilder app, IWebHostEnvironment env) + public void Configure(IApplicationBuilder app, IWebHostEnvironment env,YunDingBusiness yunDingBusiness) { + yunDingBusiness.RefreshKey(); //app.UseSwagger(c => c.SerializeAsV2 = true) // .UseSwaggerUI(c => // { diff --git a/BBWY.Server.Business/BasePlatformRelayBusiness.cs b/BBWY.Server.Business/BasePlatformRelayBusiness.cs index 36c21437..14a99739 100644 --- a/BBWY.Server.Business/BasePlatformRelayBusiness.cs +++ b/BBWY.Server.Business/BasePlatformRelayBusiness.cs @@ -1,6 +1,7 @@ using BBWY.Common.Http; using BBWY.Server.Model; using Microsoft.Extensions.Options; +using System.Collections.Generic; using System.Linq; namespace BBWY.Server.Business @@ -9,10 +10,12 @@ namespace BBWY.Server.Business { protected RestApiService restApiService; protected GlobalConfig globalConfig; - public BasePlatformRelayBusiness(RestApiService restApiService, IOptions options) + private YunDingBusiness yunDingBusiness; + public BasePlatformRelayBusiness(RestApiService restApiService, IOptions options, YunDingBusiness yunDingBusiness) { this.restApiService = restApiService; this.globalConfig = options.Value; + this.yunDingBusiness = yunDingBusiness; } /// @@ -24,5 +27,18 @@ namespace BBWY.Server.Business { return globalConfig.PlatformAPIs.FirstOrDefault(p => p.Platform == platform).APIHost; } + + protected string GetYunDingKey() + { + return yunDingBusiness.GetKey(); + } + + protected IDictionary GetYunDingRequestHeader() + { + return new Dictionary() + { + { "YunDingKey", GetYunDingKey()} + }; + } } } diff --git a/BBWY.Server.Business/Order/OrderBusiness.cs b/BBWY.Server.Business/Order/OrderBusiness.cs index 8897270e..1e906e9e 100644 --- a/BBWY.Server.Business/Order/OrderBusiness.cs +++ b/BBWY.Server.Business/Order/OrderBusiness.cs @@ -41,7 +41,7 @@ namespace BBWY.Server.Business IIdGenerator idGenerator, IOptions options, IServiceProvider serviceProvider, - IMemoryCache memoryCache) : base(restApiService, options) + IMemoryCache memoryCache, YunDingBusiness yunDingBusiness) : base(restApiService, options, yunDingBusiness) { this.fsql = fsql; this.idGenerator = idGenerator; @@ -396,7 +396,7 @@ namespace BBWY.Server.Business public ConsigneeSimpleResponse DecryptConsignee(DecryptConsigneeRequest decryptConsigneeRequest) { var relayAPIHost = GetPlatformRelayAPIHost(decryptConsigneeRequest.Platform); - var sendResult = restApiService.SendRequest(relayAPIHost, "api/PlatformSDK/DecryptConsignee", decryptConsigneeRequest, null, HttpMethod.Post); + var sendResult = restApiService.SendRequest(relayAPIHost, "api/PlatformSDK/DecryptConsignee", decryptConsigneeRequest, GetYunDingRequestHeader(), HttpMethod.Post); if (sendResult.StatusCode != System.Net.HttpStatusCode.OK) throw new BusinessException(sendResult.Content) { Code = (int)sendResult.StatusCode }; var response = JsonConvert.DeserializeObject>(sendResult.Content); @@ -700,7 +700,7 @@ namespace BBWY.Server.Business OrderId = sdCalculationCostRequest.OrderId, Platform = sdCalculationCostRequest.Platform, VenderRemark = sdCalculationCostRequest.VenderRemark - }, null, HttpMethod.Post); + }, GetYunDingRequestHeader(), HttpMethod.Post); if (editApiResult.StatusCode != System.Net.HttpStatusCode.OK) throw new BusinessException($"修改商家备注失败 {editApiResult.Content}") { Code = (int)editApiResult.StatusCode }; var editResponse = JsonConvert.DeserializeObject(editApiResult.Content); @@ -963,7 +963,7 @@ namespace BBWY.Server.Business throw new BusinessException($"订单{outStockRequest.OrderId} 只有在待出库时才允许出库"); var relayAPIHost = GetPlatformRelayAPIHost(outStockRequest.Platform); - var sendResult = restApiService.SendRequest(relayAPIHost, "api/PlatformSDK/OutStock", outStockRequest, null, HttpMethod.Post); + var sendResult = restApiService.SendRequest(relayAPIHost, "api/PlatformSDK/OutStock", outStockRequest, GetYunDingRequestHeader(), HttpMethod.Post); if (sendResult.StatusCode != System.Net.HttpStatusCode.OK) throw new BusinessException(sendResult.Content) { Code = (int)sendResult.StatusCode }; var response = JsonConvert.DeserializeObject>(sendResult.Content); @@ -986,7 +986,7 @@ namespace BBWY.Server.Business if (editVenderRemarkRequest.Platform == Enums.Platform.京东) { - var editApiResult = restApiService.SendRequest(relayAPIHost, "/Api/PlatformSDK/EditVenderRemark", editVenderRemarkRequest, null, HttpMethod.Post); + var editApiResult = restApiService.SendRequest(relayAPIHost, "/Api/PlatformSDK/EditVenderRemark", editVenderRemarkRequest, GetYunDingRequestHeader(), HttpMethod.Post); if (editApiResult.StatusCode != System.Net.HttpStatusCode.OK) throw new BusinessException($"修改商家备注失败 {editApiResult.Content}") { Code = (int)editApiResult.StatusCode }; var editResponse = JsonConvert.DeserializeObject(editApiResult.Content); @@ -1024,8 +1024,8 @@ namespace BBWY.Server.Business AppKey = request.AppKey, AppSecret = request.AppSecret, AppToken = request.AppToken, - Platform = request.Platform - }, null, HttpMethod.Post); + Platform = request.Platform, + }, GetYunDingRequestHeader(), HttpMethod.Post); if (orderApiResult.StatusCode != System.Net.HttpStatusCode.OK) throw new BusinessException($"获取未付款订单失败 {orderApiResult.Content}"); diff --git a/BBWY.Server.Business/Product/ProductBusiness.cs b/BBWY.Server.Business/Product/ProductBusiness.cs index 647b2a10..eab8beba 100644 --- a/BBWY.Server.Business/Product/ProductBusiness.cs +++ b/BBWY.Server.Business/Product/ProductBusiness.cs @@ -12,7 +12,7 @@ namespace BBWY.Server.Business { public class ProductBusiness : BasePlatformRelayBusiness, IDenpendency { - public ProductBusiness(RestApiService restApiService, IConfiguration configuration,IOptions options) : base(restApiService, options) + public ProductBusiness(RestApiService restApiService, IConfiguration configuration, IOptions options, YunDingBusiness yunDingBusiness) : base(restApiService, options, yunDingBusiness) { } @@ -20,7 +20,7 @@ namespace BBWY.Server.Business public ProductListResponse GetProductList(SearchProductRequest searchProductRequest) { var relayAPIHost = GetPlatformRelayAPIHost(searchProductRequest.Platform); - var sendResult = restApiService.SendRequest(relayAPIHost, "api/PlatformSDK/GetProductList", searchProductRequest, null, HttpMethod.Post); + var sendResult = restApiService.SendRequest(relayAPIHost, "api/PlatformSDK/GetProductList", searchProductRequest, GetYunDingRequestHeader(), HttpMethod.Post); if (sendResult.StatusCode != System.Net.HttpStatusCode.OK) throw new BusinessException(sendResult.Content) { Code = (int)sendResult.StatusCode }; var response = JsonConvert.DeserializeObject>(sendResult.Content); @@ -32,7 +32,7 @@ namespace BBWY.Server.Business public IList GetProductSkuList(SearchProductSkuRequest searchProductSkuRequest) { var relayAPIHost = GetPlatformRelayAPIHost(searchProductSkuRequest.Platform); - var sendResult = restApiService.SendRequest(relayAPIHost, "api/PlatformSDK/GetProductSkuList", searchProductSkuRequest, null, HttpMethod.Post); + var sendResult = restApiService.SendRequest(relayAPIHost, "api/PlatformSDK/GetProductSkuList", searchProductSkuRequest, GetYunDingRequestHeader(), HttpMethod.Post); if (sendResult.StatusCode != System.Net.HttpStatusCode.OK) throw new BusinessException(sendResult.Content) { Code = (int)sendResult.StatusCode }; var response = JsonConvert.DeserializeObject>>(sendResult.Content); diff --git a/BBWY.Server.Business/Sync/AfterSaleOrderSyncBusiness.cs b/BBWY.Server.Business/Sync/AfterSaleOrderSyncBusiness.cs index 6718f7fb..569e6396 100644 --- a/BBWY.Server.Business/Sync/AfterSaleOrderSyncBusiness.cs +++ b/BBWY.Server.Business/Sync/AfterSaleOrderSyncBusiness.cs @@ -167,7 +167,7 @@ namespace BBWY.Server.Business SaveResponseLog = true, OrderId = orderId, VenderId = shop.VenderId - }, null, HttpMethod.Post); + }, GetYunDingRequestHeader(), HttpMethod.Post); if (afterOrderListApiResult.StatusCode != System.Net.HttpStatusCode.OK) throw new Exception($"获取退款订单失败 {afterOrderListApiResult.Content}"); @@ -221,7 +221,7 @@ namespace BBWY.Server.Business Platform = shop.PlatformId, SaveResponseLog = false, OrderId = orderId - }, null, HttpMethod.Post); + }, GetYunDingRequestHeader(), HttpMethod.Post); if (refundOrderListApiResult.StatusCode != System.Net.HttpStatusCode.OK) throw new Exception($"获取退款订单失败 {refundOrderListApiResult.Content}"); diff --git a/BBWY.Server.Business/Sync/JD/JDPopularizeReportFormAdGroupLevelSyncBusiness.cs b/BBWY.Server.Business/Sync/JD/JDPopularizeReportFormAdGroupLevelSyncBusiness.cs index 7e4b8fb4..aee98e02 100644 --- a/BBWY.Server.Business/Sync/JD/JDPopularizeReportFormAdGroupLevelSyncBusiness.cs +++ b/BBWY.Server.Business/Sync/JD/JDPopularizeReportFormAdGroupLevelSyncBusiness.cs @@ -103,7 +103,7 @@ namespace BBWY.Server.Business.Sync Platform = shop.PlatformId, PageIndex = pageIndex, Business = 2 - }, null, HttpMethod.Post); + }, GetYunDingRequestHeader(), HttpMethod.Post); if (httpResult.StatusCode != System.Net.HttpStatusCode.OK) throw new Exception($"获取JD推广报表-单元维度失败 {httpResult.Content}"); diff --git a/BBWY.Server.Business/Sync/JD/JDPopularizeReportFormAdLevelSyncBusiness.cs b/BBWY.Server.Business/Sync/JD/JDPopularizeReportFormAdLevelSyncBusiness.cs index 5a888698..4935428d 100644 --- a/BBWY.Server.Business/Sync/JD/JDPopularizeReportFormAdLevelSyncBusiness.cs +++ b/BBWY.Server.Business/Sync/JD/JDPopularizeReportFormAdLevelSyncBusiness.cs @@ -103,7 +103,7 @@ namespace BBWY.Server.Business.Sync Platform = shop.PlatformId, PageIndex = pageIndex, Business = 2 - }, null, HttpMethod.Post); + }, GetYunDingRequestHeader(), HttpMethod.Post); if (httpResult.StatusCode != System.Net.HttpStatusCode.OK) throw new Exception($"获取JD推广报表-创意维度失败 {httpResult.Content}"); diff --git a/BBWY.Server.Business/Sync/JD/JDPopularizeReportFormCampaignLevelSyncBusiness.cs b/BBWY.Server.Business/Sync/JD/JDPopularizeReportFormCampaignLevelSyncBusiness.cs index ecff53d6..28a8f5c5 100644 --- a/BBWY.Server.Business/Sync/JD/JDPopularizeReportFormCampaignLevelSyncBusiness.cs +++ b/BBWY.Server.Business/Sync/JD/JDPopularizeReportFormCampaignLevelSyncBusiness.cs @@ -111,7 +111,7 @@ namespace BBWY.Server.Business.Sync Platform = shop.PlatformId, PageIndex = pageIndex, Business = businessType - }, null, HttpMethod.Post); + }, GetYunDingRequestHeader(), HttpMethod.Post); if (httpResult.StatusCode != System.Net.HttpStatusCode.OK) throw new Exception($"获取JD推广报表-计划维度失败 {httpResult.Content}"); diff --git a/BBWY.Server.Business/Sync/JD/JDPopularizeReportFormOrderLevelSyncBusiness.cs b/BBWY.Server.Business/Sync/JD/JDPopularizeReportFormOrderLevelSyncBusiness.cs index 04d4041e..deccadfb 100644 --- a/BBWY.Server.Business/Sync/JD/JDPopularizeReportFormOrderLevelSyncBusiness.cs +++ b/BBWY.Server.Business/Sync/JD/JDPopularizeReportFormOrderLevelSyncBusiness.cs @@ -112,7 +112,7 @@ namespace BBWY.Server.Business.Sync Platform = shop.PlatformId, PageIndex = pageIndex, Business = businessType - }, null, HttpMethod.Post); + }, GetYunDingRequestHeader(), HttpMethod.Post); if (httpResult.StatusCode != System.Net.HttpStatusCode.OK) throw new Exception($"获取JD推广报表-订单维度失败 {httpResult.Content}"); diff --git a/BBWY.Server.Business/Sync/JD/JDPopularizeReportFormSkuLevelSyncBusiness.cs b/BBWY.Server.Business/Sync/JD/JDPopularizeReportFormSkuLevelSyncBusiness.cs index b6e5c40c..072d352c 100644 --- a/BBWY.Server.Business/Sync/JD/JDPopularizeReportFormSkuLevelSyncBusiness.cs +++ b/BBWY.Server.Business/Sync/JD/JDPopularizeReportFormSkuLevelSyncBusiness.cs @@ -108,7 +108,7 @@ namespace BBWY.Server.Business.Sync Platform = shop.PlatformId, PageIndex = pageIndex, Business = 134217728 - }, null, HttpMethod.Post); + }, GetYunDingRequestHeader(), HttpMethod.Post); if (httpResult.StatusCode != System.Net.HttpStatusCode.OK) throw new Exception($"获取JD推广报表-sku维度失败 {httpResult.Content}"); diff --git a/BBWY.Server.Business/Sync/JD/JDPopularizeSyncBusiness.cs b/BBWY.Server.Business/Sync/JD/JDPopularizeSyncBusiness.cs index ae0fea7f..72c25ac6 100644 --- a/BBWY.Server.Business/Sync/JD/JDPopularizeSyncBusiness.cs +++ b/BBWY.Server.Business/Sync/JD/JDPopularizeSyncBusiness.cs @@ -83,7 +83,7 @@ namespace BBWY.Server.Business.Sync StartDate = startDate, Platform = shop.PlatformId, PageIndex = pageIndex - }, null, HttpMethod.Post); + }, GetYunDingRequestHeader(), HttpMethod.Post); if (httpResult.StatusCode != System.Net.HttpStatusCode.OK) throw new Exception($"获取JD推广费用失败 {httpResult.Content}"); diff --git a/BBWY.Server.Business/Sync/OrderSyncBusiness.cs b/BBWY.Server.Business/Sync/OrderSyncBusiness.cs index 00c637ba..63a53ea8 100644 --- a/BBWY.Server.Business/Sync/OrderSyncBusiness.cs +++ b/BBWY.Server.Business/Sync/OrderSyncBusiness.cs @@ -83,7 +83,7 @@ namespace BBWY.Server.Business //SaveResponseLog = true, OrderId = orderId, SortTimeType = sortTimeType - }, null, HttpMethod.Post); + }, GetYunDingRequestHeader(), HttpMethod.Post); if (orderListApiResult.StatusCode != System.Net.HttpStatusCode.OK) throw new Exception($"获取订单失败 {orderListApiResult.Content}"); @@ -600,7 +600,7 @@ namespace BBWY.Server.Business AppToken = appToken, Platform = Enums.Platform.京东, Sku = orderSkuIdString - }, null, HttpMethod.Post); + }, GetYunDingRequestHeader(), HttpMethod.Post); if (skuHttpResult.StatusCode != System.Net.HttpStatusCode.OK) continue; var skuResponse = JsonConvert.DeserializeObject>>(skuHttpResult.Content); diff --git a/BBWY.Server.Business/Vender/VenderBusiness.cs b/BBWY.Server.Business/Vender/VenderBusiness.cs index 332f0948..063ec5b6 100644 --- a/BBWY.Server.Business/Vender/VenderBusiness.cs +++ b/BBWY.Server.Business/Vender/VenderBusiness.cs @@ -31,7 +31,7 @@ namespace BBWY.Server.Business public VenderResponse GetVenderInfo(PlatformRequest platformRequest) { var relayAPIHost = GetPlatformRelayAPIHost(platformRequest.Platform); - var sendResult = restApiService.SendRequest(relayAPIHost, "api/PlatformSDK/GetVenderInfo", platformRequest, null, HttpMethod.Post); + var sendResult = restApiService.SendRequest(relayAPIHost, "api/PlatformSDK/GetVenderInfo", platformRequest, GetYunDingRequestHeader(), HttpMethod.Post); if (sendResult.StatusCode != System.Net.HttpStatusCode.OK) throw new BusinessException(sendResult.Content) { Code = (int)sendResult.StatusCode }; var response = JsonConvert.DeserializeObject>(sendResult.Content); @@ -43,7 +43,7 @@ namespace BBWY.Server.Business public IList GetLogisticsList(PlatformRequest platformRequest) { var relayAPIHost = GetPlatformRelayAPIHost(platformRequest.Platform); - var sendResult = restApiService.SendRequest(relayAPIHost, "api/PlatformSDK/GetLogisticsList", platformRequest, null, System.Net.Http.HttpMethod.Post); + var sendResult = restApiService.SendRequest(relayAPIHost, "api/PlatformSDK/GetLogisticsList", platformRequest, GetYunDingRequestHeader(), System.Net.Http.HttpMethod.Post); if (sendResult.StatusCode != System.Net.HttpStatusCode.OK) throw new BusinessException(sendResult.Content) { Code = (int)sendResult.StatusCode }; var response = JsonConvert.DeserializeObject>>(sendResult.Content); @@ -57,7 +57,7 @@ namespace BBWY.Server.Business var venderResponse = GetVenderInfo(new PlatformRequest() { AppKey = "120EA9EC65AB017567D78CC1139EEEA5", - AppSecret = "866a9877f5f24b03b537483b4defe75d", + AppSecret = "8a42bc2301e8439b896e99f5475e0a9b", AppToken = jDShopToken.Access_Token, Platform = Enums.Platform.京东 }); @@ -186,7 +186,7 @@ namespace BBWY.Server.Business { Id = x.ShopPKId, AppKey = string.IsNullOrEmpty(x.AppKey) ? "120EA9EC65AB017567D78CC1139EEEA5" : x.AppKey, - AppSecret = string.IsNullOrEmpty(x.AppSecret) ? "866a9877f5f24b03b537483b4defe75d" : x.AppSecret, + AppSecret = string.IsNullOrEmpty(x.AppSecret) ? "8a42bc2301e8439b896e99f5475e0a9b" : x.AppSecret, AppToken = x.AppToken, ManagePwd = x.ManagePwd, PlatformId = (Enums.Platform)x.PlatformId, diff --git a/BBWY.Server.Business/YunDingBusiness.cs b/BBWY.Server.Business/YunDingBusiness.cs new file mode 100644 index 00000000..02ad221a --- /dev/null +++ b/BBWY.Server.Business/YunDingBusiness.cs @@ -0,0 +1,47 @@ +using BBWY.Common.Models; +using BBWY.Server.Model.Db; +using Microsoft.Extensions.Caching.Memory; +using System; + +namespace BBWY.Server.Business +{ + public class YunDingBusiness : IDenpendency + { + private IMemoryCache memoryCache; + private IFreeSql fsql; + private TimeSpan expirationTimeSpan = TimeSpan.FromDays(2); + public YunDingBusiness(IMemoryCache memoryCache, IFreeSql fsql) + { + this.memoryCache = memoryCache; + this.fsql = fsql; + } + + /// + /// 创建云鼎Key + /// + public void CreateKey() + { + var key = Guid.NewGuid().ToString(); + memoryCache.Set("YunDingKey", key, expirationTimeSpan); + fsql.Update(1).Set(k => k.YunDingKey, key).ExecuteAffrows(); + } + + /// + /// 刷新云鼎Key + /// + public void RefreshKey() + { + var yundingKey = fsql.Select(1).ToOne(); + memoryCache.Set("YunDingKey", yundingKey.YunDingKey, expirationTimeSpan); + } + + /// + /// 读取云鼎Key + /// + /// + public string GetKey() + { + return memoryCache.Get("YunDingKey"); + } + } +} diff --git a/BBWY.Server.Model/Db/JD/JDYunDingAPIKey.cs b/BBWY.Server.Model/Db/JD/JDYunDingAPIKey.cs new file mode 100644 index 00000000..a4cde223 --- /dev/null +++ b/BBWY.Server.Model/Db/JD/JDYunDingAPIKey.cs @@ -0,0 +1,18 @@ +using FreeSql.DataAnnotations; + +namespace BBWY.Server.Model.Db +{ + + [Table(Name = "jdyundingapikey", DisableSyncStructure = true)] + public partial class JDYunDingAPIKey + { + + [Column(IsPrimary = true)] + public long Id { get; set; } + + [Column(StringLength = 50)] + public string YunDingKey { get; set; } + + } + +} diff --git a/BBWY.Test/Program.cs b/BBWY.Test/Program.cs index 072c5204..62851d2e 100644 --- a/BBWY.Test/Program.cs +++ b/BBWY.Test/Program.cs @@ -25,7 +25,7 @@ namespace BBWY.Test static void Main(string[] args) { var appkey = "120EA9EC65AB017567D78CC1139EEEA5"; - var appSecret = "866a9877f5f24b03b537483b4defe75d"; + var appSecret = "8a42bc2301e8439b896e99f5475e0a9b"; var token = "2ace3023200c4ea9aa682bbf8bffee18jztm"; //"b46065ef5b894f2297686e28d39cb37a2mdy";//"2ace3023200c4ea9aa682bbf8bffee18jztm"; IJdClient client = GetJdClient(appkey, appSecret); diff --git a/BBWY.sln b/BBWY.sln index efd5d059..04d4230b 100644 --- a/BBWY.sln +++ b/BBWY.sln @@ -32,7 +32,9 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BBWY.1688SDK", "BBWY.1688SDK\BBWY.1688SDK.csproj", "{1A7EB438-5DEF-4940-8CB2-C58141C75524}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BBWY.Test", "BBWY.Test\BBWY.Test.csproj", "{FCD5E03E-DA48-406B-9AA8-F72F21F62BDB}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BBWY.Test", "BBWY.Test\BBWY.Test.csproj", "{FCD5E03E-DA48-406B-9AA8-F72F21F62BDB}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "JD.API", "JD.API\JD.API.csproj", "{3D37A8D3-0364-4539-B3E9-A6610F4659A8}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -80,6 +82,10 @@ Global {FCD5E03E-DA48-406B-9AA8-F72F21F62BDB}.Debug|Any CPU.Build.0 = Debug|Any CPU {FCD5E03E-DA48-406B-9AA8-F72F21F62BDB}.Release|Any CPU.ActiveCfg = Release|Any CPU {FCD5E03E-DA48-406B-9AA8-F72F21F62BDB}.Release|Any CPU.Build.0 = Release|Any CPU + {3D37A8D3-0364-4539-B3E9-A6610F4659A8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {3D37A8D3-0364-4539-B3E9-A6610F4659A8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {3D37A8D3-0364-4539-B3E9-A6610F4659A8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {3D37A8D3-0364-4539-B3E9-A6610F4659A8}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -94,6 +100,7 @@ Global {2DC24A1B-EFE0-4F9D-8A9A-A6B530696E17} = {B131026A-2025-4A74-ABF1-644059FADF78} {1A7EB438-5DEF-4940-8CB2-C58141C75524} = {B131026A-2025-4A74-ABF1-644059FADF78} {FCD5E03E-DA48-406B-9AA8-F72F21F62BDB} = {B545F3FA-E6A7-4CB1-B92D-801C66357CF5} + {3D37A8D3-0364-4539-B3E9-A6610F4659A8} = {B545F3FA-E6A7-4CB1-B92D-801C66357CF5} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {CC045257-4D86-45FD-A1F0-2715C024F1B5} diff --git a/JD.API/.config/dotnet-tools.json b/JD.API/.config/dotnet-tools.json new file mode 100644 index 00000000..53c82263 --- /dev/null +++ b/JD.API/.config/dotnet-tools.json @@ -0,0 +1,12 @@ +{ + "version": 1, + "isRoot": true, + "tools": { + "dotnet-ef": { + "version": "6.0.10", + "commands": [ + "dotnet-ef" + ] + } + } +} \ No newline at end of file diff --git a/BBWY.Server.API/Controllers/PlatformSDKController.cs b/JD.API/Controllers/PlatformSDKController.cs similarity index 99% rename from BBWY.Server.API/Controllers/PlatformSDKController.cs rename to JD.API/Controllers/PlatformSDKController.cs index 0bb451a0..c12c66a5 100644 --- a/BBWY.Server.API/Controllers/PlatformSDKController.cs +++ b/JD.API/Controllers/PlatformSDKController.cs @@ -7,7 +7,7 @@ using Newtonsoft.Json.Linq; using System.Collections.Generic; using System.Linq; -namespace BBWY.Server.API.Controllers +namespace JD.API.API.Controllers { /// /// 平台SDK控制器,只能在对应的(云鼎/聚石塔等)服务器调用 diff --git a/JD.API/Controllers/YunDingController.cs b/JD.API/Controllers/YunDingController.cs new file mode 100644 index 00000000..2bb6f32c --- /dev/null +++ b/JD.API/Controllers/YunDingController.cs @@ -0,0 +1,26 @@ +using BBWY.Server.Business; +using BBWY.Server.Model.Db; +using Microsoft.AspNetCore.Mvc; + +// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 + +namespace JD.API.Controllers +{ + [Produces("application/json")] + [Route("Api/[Controller]/[Action]")] + [ApiController] + public class YunDingController : ControllerBase + { + private YunDingBusiness yunDingBusiness; + public YunDingController(YunDingBusiness yunDingBusiness) + { + this.yunDingBusiness = yunDingBusiness; + } + + [HttpGet] + public void RefreshKey() + { + yunDingBusiness.RefreshKey(); + } + } +} diff --git a/JD.API/Filters/ResultFilter.cs b/JD.API/Filters/ResultFilter.cs new file mode 100644 index 00000000..a2d8ecb7 --- /dev/null +++ b/JD.API/Filters/ResultFilter.cs @@ -0,0 +1,30 @@ +using BBWY.Common.Models; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Filters; + +namespace JD.API.Filters +{ + public class ResultFilter : IResultFilter + { + public void OnResultExecuted(ResultExecutedContext context) + { + + } + + public void OnResultExecuting(ResultExecutingContext context) + { + if (context.Result is ObjectResult) + { + var objectResult = context.Result as ObjectResult; + if (!(objectResult.Value is ApiResponse)) + { + objectResult.Value = new ApiResponse() { Data = objectResult.Value }; + } + } + else if (context.Result is EmptyResult) + { + context.Result = new ObjectResult(new ApiResponse()); + } + } + } +} diff --git a/JD.API/JD.API.csproj b/JD.API/JD.API.csproj new file mode 100644 index 00000000..a8271105 --- /dev/null +++ b/JD.API/JD.API.csproj @@ -0,0 +1,24 @@ + + + + netcoreapp3.1 + True + + + + + + + + + + + + + + + + + + + diff --git a/JD.API/Middlewares/CustomExceptionMiddleWare.cs b/JD.API/Middlewares/CustomExceptionMiddleWare.cs new file mode 100644 index 00000000..8e31e91c --- /dev/null +++ b/JD.API/Middlewares/CustomExceptionMiddleWare.cs @@ -0,0 +1,86 @@ +using BBWY.Common.Models; +using Microsoft.AspNetCore.Http; +using Newtonsoft.Json; +using NLog; +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading.Tasks; + +namespace JD.API.Middlewares +{ + public class CustomExceptionMiddleWare + { + /// + /// 管道请求委托 + /// + private RequestDelegate _next; + + /// + /// 需要处理的状态码字典 + /// + private IDictionary _exceptionStatusCodeDic; + + private ILogger logger; + + public CustomExceptionMiddleWare(RequestDelegate next, ILogger logger) + { + _next = next; + this.logger = logger; + _exceptionStatusCodeDic = new Dictionary + { + { 401, "未授权的请求" }, + { 404, "找不到该资源" }, + { 403, "访问被拒绝" }, + { 500, "服务器发生意外的错误" }, + { 503, "服务不可用" } + //其余状态自行扩展 + }; + } + + public async Task Invoke(HttpContext context) + { + try + { + await _next(context); //调用管道执行下一个中间件 + } + catch (Exception ex) + { + if (ex is BusinessException) + { + var busEx = ex as BusinessException; + context.Response.StatusCode = 200; //业务异常时将Http状态码改为200 + await ErrorHandle(context, busEx.Code, busEx.Message); + } + else + { + context.Response.Clear(); + context.Response.StatusCode = 500; //发生未捕获的异常,手动设置状态码 + logger.Error(ex); //记录错误 + } + } + finally + { + if (_exceptionStatusCodeDic.TryGetValue(context.Response.StatusCode, out string exMsg)) + { + await ErrorHandle(context, context.Response.StatusCode, exMsg); + } + } + } + + /// + /// 处理方式:返回Json格式 + /// + /// + /// + /// + /// + private async Task ErrorHandle(HttpContext context, int code, string exMsg) + { + var apiResponse = ApiResponse.Error(code, exMsg); + var serialzeStr = JsonConvert.SerializeObject(apiResponse); + context.Response.ContentType = "application/json"; + await context.Response.WriteAsync(serialzeStr, Encoding.UTF8); + } + } +} diff --git a/JD.API/Program.cs b/JD.API/Program.cs new file mode 100644 index 00000000..6a19dd04 --- /dev/null +++ b/JD.API/Program.cs @@ -0,0 +1,26 @@ +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace JD.API +{ + public class Program + { + public static void Main(string[] args) + { + CreateHostBuilder(args).Build().Run(); + } + + public static IHostBuilder CreateHostBuilder(string[] args) => + Host.CreateDefaultBuilder(args) + .ConfigureWebHostDefaults(webBuilder => + { + webBuilder.UseStartup(); + }); + } +} diff --git a/JD.API/Properties/launchSettings.json b/JD.API/Properties/launchSettings.json new file mode 100644 index 00000000..1ce1711b --- /dev/null +++ b/JD.API/Properties/launchSettings.json @@ -0,0 +1,30 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:46194", + "sslPort": 0 + } + }, + "profiles": { + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "weatherforecast", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "JD.API": { + "commandName": "Project", + "launchBrowser": true, + "launchUrl": "weatherforecast", + "applicationUrl": "http://localhost:5000", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/JD.API/Startup.cs b/JD.API/Startup.cs new file mode 100644 index 00000000..5b68a0ec --- /dev/null +++ b/JD.API/Startup.cs @@ -0,0 +1,149 @@ +using BBWY.Common.Http; +using BBWY.Server.Business; +using JD.API.Filters; +using JD.API.Middlewares; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using Microsoft.OpenApi.Models; +using Newtonsoft.Json.Serialization; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Threading.Tasks; + +namespace JD.API +{ + public class Startup + { + public Startup(IConfiguration configuration) + { + Configuration = configuration; + } + + public IConfiguration Configuration { get; } + + private bool isEnableSwagger; + + // This method gets called by the runtime. Use this method to add services to the container. + public void ConfigureServices(IServiceCollection services) + { + isEnableSwagger = Convert.ToBoolean(Configuration.GetSection("IsEnableSwagger").Value); + + services.AddHttpContextAccessor(); + services.AddHttpClient(); + services.AddMemoryCache(); + services.AddSingleton(typeof(NLog.ILogger), NLog.LogManager.GetCurrentClassLogger()); + + var fsql = new FreeSql.FreeSqlBuilder().UseConnectionString(FreeSql.DataType.MySql, Configuration.GetConnectionString("DB")).Build(); + services.AddSingleton(typeof(IFreeSql), fsql); + + services.AddCors(options => + { + options.AddDefaultPolicy(p => + { + p.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader(); + }); + }); + + services.AddControllers(configure => + { + configure.Filters.Add(); + }).AddNewtonsoftJson(setupAction => + { + setupAction.SerializerSettings.ContractResolver = new DefaultContractResolver(); + setupAction.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; + //setupAction.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Include; + //setupAction.SerializerSettings.DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Include; + }); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + + if (isEnableSwagger) + { + services.AddSwaggerGen(c => + { + c.SwaggerDoc("v1", new OpenApiInfo + { + Version = "v1.0.0", + Title = "JDƶAPI", + Description = "ע\r\n1.زƲôշ\r\n2.ApiResponseΪض(Code,Data,Message),ӿеķֵData\r\n3.Code=200" + }); + // JWT֤ + //c.AddSecurityDefinition(JwtBearerDefaults.AuthenticationScheme, new OpenApiSecurityScheme + //{ + // Scheme = JwtBearerDefaults.AuthenticationScheme, + // BearerFormat = "JWT", + // Type = SecuritySchemeType.ApiKey, + // Name = "Authorization", + // In = ParameterLocation.Header, + // Description = "Authorization:Bearer {your JWT token}
", + //}); + //c.AddSecurityRequirement(new OpenApiSecurityRequirement + // { + // { + // new OpenApiSecurityScheme{Reference = new OpenApiReference + // { + // Type = ReferenceType.SecurityScheme, + // Id = JwtBearerDefaults.AuthenticationScheme + // } + // }, + // new string[] { } + // } + // }); + + var executingAssembly = Assembly.GetExecutingAssembly(); + var assemblyNames = executingAssembly.GetReferencedAssemblies().Union(new AssemblyName[] { executingAssembly.GetName() }).ToArray(); + Array.ForEach(assemblyNames, (assemblyName) => + { + //var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; + var xmlFile = $"{assemblyName.Name}.xml"; + var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); + if (!File.Exists(xmlPath)) + return; + c.IncludeXmlComments(xmlPath, true); + }); + }); + } + } + + // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. + public void Configure(IApplicationBuilder app, IWebHostEnvironment env, YunDingBusiness yunDingBusiness) + { + yunDingBusiness.RefreshKey(); + if (isEnableSwagger) + { + app.UseSwagger(c => c.SerializeAsV2 = true) + .UseSwaggerUI(c => + { + c.SwaggerEndpoint("/swagger/v1/swagger.json", "BBWY API"); + c.RoutePrefix = string.Empty; + }); + } + + //if (env.IsDevelopment()) + //{ + // app.UseDeveloperExceptionPage(); + //} + + app.UseMiddleware(); + + app.UseRouting(); + + app.UseAuthorization(); + + app.UseEndpoints(endpoints => + { + endpoints.MapControllers(); + }); + } + } +} diff --git a/JD.API/WeatherForecast.cs b/JD.API/WeatherForecast.cs new file mode 100644 index 00000000..de88e8d3 --- /dev/null +++ b/JD.API/WeatherForecast.cs @@ -0,0 +1,15 @@ +using System; + +namespace JD.API +{ + public class WeatherForecast + { + public DateTime Date { get; set; } + + public int TemperatureC { get; set; } + + public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); + + public string Summary { get; set; } + } +} diff --git a/JD.API/appsettings.Development.json b/JD.API/appsettings.Development.json new file mode 100644 index 00000000..8983e0fc --- /dev/null +++ b/JD.API/appsettings.Development.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft": "Warning", + "Microsoft.Hosting.Lifetime": "Information" + } + } +} diff --git a/JD.API/appsettings.json b/JD.API/appsettings.json new file mode 100644 index 00000000..5518a7eb --- /dev/null +++ b/JD.API/appsettings.json @@ -0,0 +1,14 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft": "Warning", + "Microsoft.Hosting.Lifetime": "Information" + } + }, + "ConnectionStrings": { + "DB": "data source=rm-bp1508okrh23710yfao.mysql.rds.aliyuncs.com;port=3306;user id=qyroot;password=kaicn1132+-;initial catalog=bbwy_test;charset=utf8;sslmode=none;", + }, + "IsEnableSwagger": false, + "AllowedHosts": "*" +}