Browse Source

步步为盈服务端请求JDAPI增加云鼎Key

qianyi
shanji 3 years ago
parent
commit
894f45ec95
  1. 26
      BBWY.Server.API/Controllers/YunDingController.cs
  2. 3
      BBWY.Server.API/Startup.cs
  3. 18
      BBWY.Server.Business/BasePlatformRelayBusiness.cs
  4. 14
      BBWY.Server.Business/Order/OrderBusiness.cs
  5. 6
      BBWY.Server.Business/Product/ProductBusiness.cs
  6. 4
      BBWY.Server.Business/Sync/AfterSaleOrderSyncBusiness.cs
  7. 2
      BBWY.Server.Business/Sync/JD/JDPopularizeReportFormAdGroupLevelSyncBusiness.cs
  8. 2
      BBWY.Server.Business/Sync/JD/JDPopularizeReportFormAdLevelSyncBusiness.cs
  9. 2
      BBWY.Server.Business/Sync/JD/JDPopularizeReportFormCampaignLevelSyncBusiness.cs
  10. 2
      BBWY.Server.Business/Sync/JD/JDPopularizeReportFormOrderLevelSyncBusiness.cs
  11. 2
      BBWY.Server.Business/Sync/JD/JDPopularizeReportFormSkuLevelSyncBusiness.cs
  12. 2
      BBWY.Server.Business/Sync/JD/JDPopularizeSyncBusiness.cs
  13. 4
      BBWY.Server.Business/Sync/OrderSyncBusiness.cs
  14. 8
      BBWY.Server.Business/Vender/VenderBusiness.cs
  15. 47
      BBWY.Server.Business/YunDingBusiness.cs
  16. 18
      BBWY.Server.Model/Db/JD/JDYunDingAPIKey.cs
  17. 2
      BBWY.Test/Program.cs
  18. 9
      BBWY.sln
  19. 12
      JD.API/.config/dotnet-tools.json
  20. 2
      JD.API/Controllers/PlatformSDKController.cs
  21. 26
      JD.API/Controllers/YunDingController.cs
  22. 30
      JD.API/Filters/ResultFilter.cs
  23. 24
      JD.API/JD.API.csproj
  24. 86
      JD.API/Middlewares/CustomExceptionMiddleWare.cs
  25. 26
      JD.API/Program.cs
  26. 30
      JD.API/Properties/launchSettings.json
  27. 149
      JD.API/Startup.cs
  28. 15
      JD.API/WeatherForecast.cs
  29. 9
      JD.API/appsettings.Development.json
  30. 14
      JD.API/appsettings.json

26
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();
}
}
}

3
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 =>
// {

18
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<GlobalConfig> options)
private YunDingBusiness yunDingBusiness;
public BasePlatformRelayBusiness(RestApiService restApiService, IOptions<GlobalConfig> options, YunDingBusiness yunDingBusiness)
{
this.restApiService = restApiService;
this.globalConfig = options.Value;
this.yunDingBusiness = yunDingBusiness;
}
/// <summary>
@ -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<string, string> GetYunDingRequestHeader()
{
return new Dictionary<string, string>()
{
{ "YunDingKey", GetYunDingKey()}
};
}
}
}

14
BBWY.Server.Business/Order/OrderBusiness.cs

@ -41,7 +41,7 @@ namespace BBWY.Server.Business
IIdGenerator idGenerator,
IOptions<GlobalConfig> 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<ApiResponse<ConsigneeSimpleResponse>>(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<ApiResponse>(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<ApiResponse<ConsigneeSimpleResponse>>(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<ApiResponse>(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}");

6
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<GlobalConfig> options) : base(restApiService, options)
public ProductBusiness(RestApiService restApiService, IConfiguration configuration, IOptions<GlobalConfig> 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<ApiResponse<ProductListResponse>>(sendResult.Content);
@ -32,7 +32,7 @@ namespace BBWY.Server.Business
public IList<ProductSkuResponse> 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<ApiResponse<IList<ProductSkuResponse>>>(sendResult.Content);

4
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}");

2
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}");

2
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}");

2
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}");

2
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}");

2
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}");

2
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}");

4
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<ApiResponse<IList<SimpleProductSkuResponse>>>(skuHttpResult.Content);

8
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<ApiResponse<VenderResponse>>(sendResult.Content);
@ -43,7 +43,7 @@ namespace BBWY.Server.Business
public IList<LogisticsResponse> 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<ApiResponse<IList<LogisticsResponse>>>(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,

47
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;
}
/// <summary>
/// 创建云鼎Key
/// </summary>
public void CreateKey()
{
var key = Guid.NewGuid().ToString();
memoryCache.Set("YunDingKey", key, expirationTimeSpan);
fsql.Update<JDYunDingAPIKey>(1).Set(k => k.YunDingKey, key).ExecuteAffrows();
}
/// <summary>
/// 刷新云鼎Key
/// </summary>
public void RefreshKey()
{
var yundingKey = fsql.Select<JDYunDingAPIKey>(1).ToOne();
memoryCache.Set("YunDingKey", yundingKey.YunDingKey, expirationTimeSpan);
}
/// <summary>
/// 读取云鼎Key
/// </summary>
/// <returns></returns>
public string GetKey()
{
return memoryCache.Get<string>("YunDingKey");
}
}
}

18
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; }
}
}

2
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);

9
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}

12
JD.API/.config/dotnet-tools.json

@ -0,0 +1,12 @@
{
"version": 1,
"isRoot": true,
"tools": {
"dotnet-ef": {
"version": "6.0.10",
"commands": [
"dotnet-ef"
]
}
}
}

2
BBWY.Server.API/Controllers/PlatformSDKController.cs → 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
{
/// <summary>
/// 平台SDK控制器,只能在对应的(云鼎/聚石塔等)服务器调用

26
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();
}
}
}

30
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());
}
}
}
}

24
JD.API/JD.API.csproj

@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<GenerateDocumentationFile>True</GenerateDocumentationFile>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="FreeSql" Version="2.6.100" />
<PackageReference Include="FreeSql.Provider.MySql" Version="2.6.100" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.1.21" />
<PackageReference Include="NLog" Version="4.7.12" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\BBWY.Common\BBWY.Common.csproj" />
<ProjectReference Include="..\BBWY.JDSDK\BBWY.JDSDK.csproj" />
<ProjectReference Include="..\BBWY.Server.Business\BBWY.Server.Business.csproj" />
<ProjectReference Include="..\BBWY.Server.Model\BBWY.Server.Model.csproj" />
</ItemGroup>
</Project>

86
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
{
/// <summary>
/// 管道请求委托
/// </summary>
private RequestDelegate _next;
/// <summary>
/// 需要处理的状态码字典
/// </summary>
private IDictionary<int, string> _exceptionStatusCodeDic;
private ILogger logger;
public CustomExceptionMiddleWare(RequestDelegate next, ILogger logger)
{
_next = next;
this.logger = logger;
_exceptionStatusCodeDic = new Dictionary<int, string>
{
{ 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);
}
}
}
/// <summary>
/// 处理方式:返回Json格式
/// </summary>
/// <param name="context"></param>
/// <param name="code"></param>
/// <param name="exMsg"></param>
/// <returns></returns>
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);
}
}
}

26
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<Startup>();
});
}
}

30
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"
}
}
}
}

149
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<ResultFilter>();
}).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<RestApiService>();
services.AddSingleton<PlatformSDKBusiness, JDBusiness>();
services.AddSingleton<PlatformSDKBusiness, _1688Business>();
services.AddSingleton<YunDingBusiness>();
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}<br/>",
//});
//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<CustomExceptionMiddleWare>();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}

15
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; }
}
}

9
JD.API/appsettings.Development.json

@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
}
}

14
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": "*"
}
Loading…
Cancel
Save