From ec3004518f426e2c803e8fe896f7d98a14fd9627 Mon Sep 17 00:00:00 2001 From: xRain Date: Sun, 10 May 2026 20:24:08 +0800 Subject: [PATCH] =?UTF-8?q?=E5=88=A0=E9=99=A4=E4=BA=86CoceSDk,Simapihttpcl?= =?UTF-8?q?ient=20=E6=B7=BB=E5=8A=A0=E5=88=B0=E9=85=8D=E7=BD=AE=E4=B8=AD,?= =?UTF-8?q?=E6=A0=87=E5=87=86=E8=B0=83=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CoceSdk/CoceApp.cs | 234 ---------------------- CoceSdk/CoceAppSdkOption.cs | 15 -- CoceSdk/CoceController.cs | 52 ----- CoceSdk/CoceModels.cs | 43 ---- CoceSdk/ICoceLoginProcessor.cs | 9 - Configurations/SimApiHttpClientOptions.cs | 8 + Configurations/SimApiOptions.cs | 19 +- Helpers/SimApiHttpClient.cs | 33 +-- SimApiExtensions.cs | 45 +---- 9 files changed, 39 insertions(+), 419 deletions(-) delete mode 100644 CoceSdk/CoceApp.cs delete mode 100644 CoceSdk/CoceAppSdkOption.cs delete mode 100644 CoceSdk/CoceController.cs delete mode 100644 CoceSdk/CoceModels.cs delete mode 100644 CoceSdk/ICoceLoginProcessor.cs create mode 100644 Configurations/SimApiHttpClientOptions.cs diff --git a/CoceSdk/CoceApp.cs b/CoceSdk/CoceApp.cs deleted file mode 100644 index 0af8155..0000000 --- a/CoceSdk/CoceApp.cs +++ /dev/null @@ -1,234 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using System.Net.Http; -using System.Net.Http.Json; -using System.Text; -using System.Text.Json; -using Microsoft.Extensions.Caching.Distributed; -using Microsoft.Extensions.Logging; -using SimApi.Communications; -using SimApi.Configurations; -using SimApi.Helpers; - -namespace SimApi.CoceSdk; - -public class CoceApp(SimApiOptions simApiOptions, ILogger logger, IDistributedCache cache) -{ - /// - /// 获取Level Token - /// - /// - /// - /// - public LevelTokenResponse? GetLevelToken(string lv1Token, int level = 5) - { - var dict = new Dictionary - { - { "lv1Token", lv1Token }, - { "time", (int)SimApiUtil.TimestampNow }, - { "appId", simApiOptions.CoceSdkOptions.AppId! }, - { "level", level } - }; - return QueryAppApi("/api/app/token", dict); - } - - /// - /// 通过用户手机号搜索用户 - /// - /// - /// - public UserInfo? SearchUserByPhone(string phone) - { - var dict = new Dictionary - { - { "cell", phone }, - { "time", (int)SimApiUtil.TimestampNow }, - { "appId", simApiOptions.CoceSdkOptions.AppId! }, - }; - return QueryAppApi("/api/app/user/search-by-phone", dict); - } - - /// - /// 通过给出的UserId列表获取用户信息 - /// - /// - /// - public UserInfo[]? SearchUserByIds(IEnumerable userIds) - { - var dict = new Dictionary - { - { "ids", string.Join(",", userIds) }, - { "time", (int)SimApiUtil.TimestampNow }, - { "appId", simApiOptions.CoceSdkOptions.AppId! }, - }; - return QueryAppApi("/api/app/user/search-by-ids", dict); - } - - /// - /// 向用户发送消息 - /// - /// - /// - /// - /// - public bool SendUserMessage(string userId, string title, string content) - { - var dict = new Dictionary - { - { "time", (int)SimApiUtil.TimestampNow }, - { "appId", simApiOptions.CoceSdkOptions.AppId! }, - { "userId", userId }, - { "type", "text" }, - { "title", title }, - { "text", content } - }; - return QueryAppApiNoResp("/api/app/message", dict); - } - - /// - /// 创建交易订单号 - /// - /// - /// - /// - /// - public string? TradeCreate(string name, int amount, string ext) - { - var dict = new Dictionary - { - { "time", (int)SimApiUtil.TimestampNow }, - { "appId", simApiOptions.CoceSdkOptions.AppId! }, - { "amount", amount }, - { "ext", ext }, - { "name", name } - }; - return QueryAppApi("/api/app/trade/create", dict); - } - - /// - /// 查询订单状态 - /// - /// - /// - public CheckTradeResponse? TradeCheck(string tradeNo) - { - var dict = new Dictionary - { - { "time", (int)SimApiUtil.TimestampNow }, - { "appId", simApiOptions.CoceSdkOptions.AppId! }, - { "tradeNo", tradeNo } - }; - return QueryAppApi("/api/app/trade/result", dict); - } - - /// - /// 对订单进行退款 - /// - /// - /// - public bool TradeRefund(string tradeNo) - { - var dict = new Dictionary - { - { "time", (int)SimApiUtil.TimestampNow }, - { "appId", simApiOptions.CoceSdkOptions.AppId! }, - { "tradeNo", tradeNo } - }; - return QueryAppApiNoResp("/api/app/trade/refund", dict); - } - - - private T? QueryAppApi(string endpoint, Dictionary request) - { - var response = QueryAppApi(endpoint, request); - var result = response.Content.ReadFromJsonAsync>().Result!; - if (result.Code == 200) return result.Data; - logger.LogDebug("发生错误: {Code} => {Message}", result.Code, result.Message); - return default; - } - - private bool QueryAppApiNoResp(string endpoint, Dictionary request) - { - var response = QueryAppApi(endpoint, request); - var result = response.Content.ReadFromJsonAsync().Result!; - return result.Code == 200; - } - - private HttpResponseMessage QueryAppApi(string endpoint, Dictionary request) - { - var platUrl = simApiOptions.CoceSdkOptions.ApiEndpoint + endpoint; - var sorted = request.OrderBy(x => x.Key); - var signStr = sorted.Aggregate("", (current, item) => current + $"{item.Key}={item.Value}&").TrimEnd('&'); - logger.LogDebug("签名的字符串: {SignStr}", signStr); - var sign = SimApiUtil.Md5(signStr + simApiOptions.CoceSdkOptions.AppKey); - logger.LogDebug("签名: {Sign}", sign); - request.Add("sign", sign); - logger.LogDebug("请求地址: {PlatUrl} => {Data}", platUrl, SimApiUtil.Json(request)); - var http = new HttpClient(); - return http.PostAsJsonAsync(platUrl, request).Result; - } - - - /// - /// 获取用户的群组信息 - /// - /// Level >=2 的Token - /// - public IEnumerable? GetUserGroups(string token) - { - const string uri = "/api/lv2/user/groups"; - var resp = ProxyQuery(uri, token, "{}"); - return resp; - } - - /// - /// 获取用户信息 - /// - /// - /// - public UserInfo? GetUserInfo(string token) - { - const string uri = "/api/lv1/user/info"; - return ProxyQuery(uri, token); - } - - public void SaveToken(string userId, string levelToken) - { - cache.SetString($"LEVEL:TOKEN:{userId}", levelToken); - } - - public string? GetToken(string userId) - { - return cache.GetString($"LEVEL:TOKEN:{userId}"); - } - - - public dynamic? ProxyQuery(string uri, string token, string json) => ProxyQuery(uri, token, json); - - public dynamic? ProxyQueue(string uri, string token, object data) => - ProxyQuery(uri, token, SimApiUtil.Json(data)); - - public T? ProxyQueue(string uri, string token, object data) => - ProxyQuery(uri, token, SimApiUtil.Json(data)); - - public T? ProxyQuery(string uri, string token, string json = "{}") - { - var http = new HttpClient(); - http.DefaultRequestHeaders.Add("Token", token); - var realUrl = simApiOptions.CoceSdkOptions.ApiEndpoint + uri; - var response = http.PostAsync(realUrl, new StringContent(json, Encoding.UTF8, "application/json")) - .Result; - var resp = response.Content.ReadFromJsonAsync>().Result!; - if (resp.Code != 200) - { - logger.LogDebug("请求发生错误: {RespCode} => {RespMessage}", resp.Code, resp.Message); - } - - return resp.Code == 200 ? resp.Data : default; - } - - public ConfigResponse GetConfig() - { - return new ConfigResponse(simApiOptions.CoceSdkOptions.AppId!, simApiOptions.CoceSdkOptions.AuthEndpoint); - } -} \ No newline at end of file diff --git a/CoceSdk/CoceAppSdkOption.cs b/CoceSdk/CoceAppSdkOption.cs deleted file mode 100644 index 910c99b..0000000 --- a/CoceSdk/CoceAppSdkOption.cs +++ /dev/null @@ -1,15 +0,0 @@ -namespace SimApi.CoceSdk; - -public class CoceAppSdkOption -{ - /** - * 中心API服务器地址 - */ - public string ApiEndpoint { get; set; } = "https://api.coce.cc"; - - public string AuthEndpoint { get; set; } = "https://home.coce.cc"; - - public string? AppId { get; set; } - - public string? AppKey { get; set; } -} \ No newline at end of file diff --git a/CoceSdk/CoceController.cs b/CoceSdk/CoceController.cs deleted file mode 100644 index 32cb63c..0000000 --- a/CoceSdk/CoceController.cs +++ /dev/null @@ -1,52 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using Microsoft.AspNetCore.Mvc; -using Microsoft.Extensions.DependencyInjection; -using SimApi.Attributes; -using SimApi.Communications; -using SimApi.Controllers; -using SimApi.Helpers; -using static SimApi.Helpers.SimApiError; - -namespace SimApi.CoceSdk; - -public class CoceController(CoceApp coce, SimApiAuth auth, IServiceProvider sp) : SimApiBaseController -{ - [HttpPost] - public SimApiBaseResponse GetConfig() - { - return new SimApiBaseResponse(coce.GetConfig()); - } - - [HttpPost] - public string Login([FromBody] SimApiOneFieldRequest request) - { - var data = coce.GetLevelToken(request.Data!); - ErrorWhenNull(data, 400); - coce.SaveToken(data!.UserId, data.Token); - var userinfo = coce.GetUserInfo(data!.Token); - var meta = new Dictionary - { - { "name", userinfo!.Name }, - { "image", userinfo.Image } - }; - var groups = coce.GetUserGroups(data.Token!)!; - var loginItem = new SimApiLoginItem - { - Id = data.UserId, - Meta = meta, - }; - var processor = sp.GetService(); - processor?.Process(loginItem, groups.ToArray()); - return auth.Login(loginItem); - } - - [HttpPost, SimApiAuth] - public GroupInfo[] ListGroups() - { - var levelToken = coce.GetToken(LoginInfo.Id!); - var groups = coce.GetUserGroups(levelToken!)!; - return groups.ToArray(); - } -} \ No newline at end of file diff --git a/CoceSdk/CoceModels.cs b/CoceSdk/CoceModels.cs deleted file mode 100644 index 545ca3a..0000000 --- a/CoceSdk/CoceModels.cs +++ /dev/null @@ -1,43 +0,0 @@ -using System; - -namespace SimApi.CoceSdk; - -public record ConfigResponse(string AppId, string AuthUrl); - -public record LevelTokenResponse(string Token, string UserId, int TokenLevel); - -public record GroupInfo(string Id, string Name, string Image, string Description, string Role); - -public record UserInfo(string UserId, string Name, string Image); - -public record CheckTradeResponse( - string TradeNo, - int Amount, - int Fee, - string Name, - string? Ext, - string Status, - DateTime CreatedAt, - DateTime? FinishedAt, - DateTime? RefundAt, - DateTime? CloseAt); - -public class UserInfoWithGroup -{ - public string? UserId { get; set; } - - public string? Name { get; set; } - - public string? LevelToken { get; set; } - - public UserGroupItem[]? UserGroupItems { get; set; } -} - -public class UserGroupItem -{ - public string? GroupId { get; set; } - - public string? GroupName { get; set; } - - public string? GroupRole { get; set; } -} \ No newline at end of file diff --git a/CoceSdk/ICoceLoginProcessor.cs b/CoceSdk/ICoceLoginProcessor.cs deleted file mode 100644 index 6f61930..0000000 --- a/CoceSdk/ICoceLoginProcessor.cs +++ /dev/null @@ -1,9 +0,0 @@ -using System.Collections.Generic; -using SimApi.Communications; - -namespace SimApi.CoceSdk; - -public interface ICoceLoginProcessor -{ - SimApiLoginItem Process(SimApiLoginItem loginItem, GroupInfo[] groups); -} \ No newline at end of file diff --git a/Configurations/SimApiHttpClientOptions.cs b/Configurations/SimApiHttpClientOptions.cs new file mode 100644 index 0000000..e977f54 --- /dev/null +++ b/Configurations/SimApiHttpClientOptions.cs @@ -0,0 +1,8 @@ +namespace SimApi.Configurations; + +public class SimApiHttpClientOptions +{ + public string Server { get; set; } = string.Empty; + public string AppId { get; set; } = string.Empty; + public string AppKey { get; set; } = string.Empty; +} \ No newline at end of file diff --git a/Configurations/SimApiOptions.cs b/Configurations/SimApiOptions.cs index 306a809..04b338c 100644 --- a/Configurations/SimApiOptions.cs +++ b/Configurations/SimApiOptions.cs @@ -1,5 +1,4 @@ using System; -using SimApi.CoceSdk; namespace SimApi.Configurations; @@ -51,9 +50,6 @@ public class SimApiOptions /// public bool EnableCors { get; set; } = true; - - public CoceAppSdkOption CoceSdkOptions { get; set; } = new(); - /// /// 启用异常拦截,启用后,所有的异常将被通过json反馈。 /// default: true @@ -93,6 +89,9 @@ public class SimApiOptions public bool EnableLogger { get; set; } = true; + public bool EnableSimApiHttpClient { get; set; } = false; + + /// /// 配置Job /// @@ -112,16 +111,18 @@ public class SimApiOptions public SimApiGateAuthOptions SimApiGateAuthOptions { get; set; } = new(); + public SimApiHttpClientOptions SimApiHttpClientOptions { get; set; } = new(); + + public void ConfigureSimApiHttpClient(Action? options = null) + { + options?.Invoke(SimApiHttpClientOptions); + } + public void ConfigureSimApiSynapse(Action? options = null) { options?.Invoke(SimApiSynapseOptions); } - public void ConfigureCoceSdk(Action? options = null) - { - options?.Invoke(CoceSdkOptions); - } - public void ConfigureSimApiDoc(Action? options = null) { options?.Invoke(SimApiDocOptions); diff --git a/Helpers/SimApiHttpClient.cs b/Helpers/SimApiHttpClient.cs index c494ee4..7e98061 100644 --- a/Helpers/SimApiHttpClient.cs +++ b/Helpers/SimApiHttpClient.cs @@ -3,19 +3,19 @@ using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Net.Http.Json; +using Microsoft.Extensions.Logging; using SimApi.Communications; +using SimApi.Configurations; using SimApi.Exceptions; namespace SimApi.Helpers; -public class SimApiHttpClient +public class SimApiHttpClient(SimApiOptions? apiOptions = null, ILogger? logger = null) { - public required string Server { get; init; } - public required string AppId { get; init; } + public string Server { get; init; } = apiOptions?.SimApiHttpClientOptions.Server ?? string.Empty; + public string AppId { get; init; } = apiOptions?.SimApiHttpClientOptions.AppId ?? string.Empty; + public string AppKey { get; init; } = apiOptions?.SimApiHttpClientOptions.AppKey ?? string.Empty; - public required string AppKey { get; init; } - - public bool Debug { get; init; } = false; public string SignName { get; init; } = "sign"; public string TimestampName { get; init; } = "timestamp"; public string NonceName { get; init; } = "nonce"; @@ -103,23 +103,12 @@ public class SimApiHttpClient private T? Query(string url, object? req) { var http = new HttpClient(); - if (Debug) - { - Console.WriteLine($"[HTTPCLIENT请求] {url}\n{SimApiUtil.Json(req)}\n"); - } - + logger?.LogDebug($"[HTTPCLIENT请求] {url}\n{SimApiUtil.Json(req)}\n"); var resp = http.PostAsJsonAsync(url, req).Result; - if (Debug) - { - Console.WriteLine($"[HTTPCLIENT响应] {resp.Content.ReadAsStringAsync().Result}\n"); - } - + logger?.LogDebug($"[HTTPCLIENT响应] {resp.Content.ReadAsStringAsync().Result}\n"); var res = resp.Content.ReadFromJsonAsync>().Result; - if (res == null) - { - throw new SimApiException(500, "请求发生错误"); - } - - return res.Code != 200 ? throw new SimApiException(res.Code, res.Message) : res.Data; + SimApiError.ErrorWhenNull(res, 500, "请求发生错误"); + SimApiError.ErrorWhen(res.Code != 200, res.Code, res.Message); + return res.Data; } } \ No newline at end of file diff --git a/SimApiExtensions.cs b/SimApiExtensions.cs index 3d485ed..9fe75d8 100644 --- a/SimApiExtensions.cs +++ b/SimApiExtensions.cs @@ -16,7 +16,6 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using SimApi.Attributes; -using SimApi.CoceSdk; using SimApi.Configurations; using SimApi.Interfaces; using SimApi.Logger; @@ -59,11 +58,6 @@ public static class SimApiExtensions builder.AddSingleton(); } - if (simApiOptions.EnableCoceSdk) - { - builder.AddSingleton(); - } - var simApiAuthChecker = typeof(ISimApiAuthChecker); var stackTrace = new StackTrace(); var callingMethod = stackTrace.GetFrame(stackTrace.FrameCount - 1)?.GetMethod(); @@ -108,6 +102,11 @@ public static class SimApiExtensions policy => { policy.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin(); })); } + if (simApiOptions.EnableSimApiHttpClient) + { + builder.AddSingleton(); + } + if (simApiOptions.EnableSynapse) { builder.AddSingleton(); @@ -355,11 +354,11 @@ public static class SimApiExtensions builder.Services.GetService(); } - if (options.EnableCoceSdk) + if (options.EnableSimApiHttpClient) { - logger.LogInformation("开始配置CoceAppSdk...\nApi入口: {ApiUrl}\nAuth入口:{AuthUrl}n\nAppId: {AppId}", - options.CoceSdkOptions.ApiEndpoint, options.CoceSdkOptions.AuthEndpoint, - options.CoceSdkOptions.AppId); + logger.LogInformation("开始配置SimApiHttpClient...\n服务器地址: {ApiUrl}\nAppId:{AuthUrl}n\nAppkey: {AppId}", + options.SimApiHttpClientOptions.Server, options.SimApiHttpClientOptions.AppId, + !string.IsNullOrEmpty(options.SimApiHttpClientOptions.AppKey)); } if (options.EnableSynapse) @@ -436,30 +435,6 @@ public static class SimApiExtensions controller = "SimApiAuth", action = "Logout" }); - if (options.EnableCoceSdk) - { - logger.LogInformation("开始配置CoceAppSdk...\nApi入口: {ApiUrl}\nAuth入口:{AuthUrl}n\nAppId: {AppId}", - options.CoceSdkOptions.ApiEndpoint, options.CoceSdkOptions.AuthEndpoint, - options.CoceSdkOptions.AppId); - builder.MapControllerRoute(name: "LoginUseCoce", pattern: "/auth/login", - defaults: new - { - controller = "Coce", - action = "Login" - }); - builder.MapControllerRoute(name: "LoginUseCoce", pattern: "/user/groups", - defaults: new - { - controller = "Coce", - action = "ListGroups" - }); - builder.MapControllerRoute(name: "LoginUseCoce", pattern: "/auth/config", - defaults: new - { - controller = "Coce", - action = "GetConfig" - }); - } } if (options.EnableVersionUrl) @@ -482,7 +457,7 @@ public static class SimApiExtensions x.DocumentTitle = docOptions.DocumentTitle; foreach (var group in docOptions.ApiGroups) { - x.SwaggerEndpoint($"/swagger/{group.Id}.json", name: group.Name); + x.SwaggerEndpoint($"{group.Id}.json", name: group.Name); } x.SupportedSubmitMethods(docOptions.SupportedMethod);