删除了CoceSDk,Simapihttpclient 添加到配置中,标准调用

This commit is contained in:
2026-05-10 20:24:08 +08:00
parent 140e039d27
commit ec3004518f
9 changed files with 39 additions and 419 deletions
-234
View File
@@ -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<CoceApp> logger, IDistributedCache cache)
{
/// <summary>
/// 获取Level Token
/// </summary>
/// <param name="lv1Token"></param>
/// <param name="level"></param>
/// <returns></returns>
public LevelTokenResponse? GetLevelToken(string lv1Token, int level = 5)
{
var dict = new Dictionary<string, object>
{
{ "lv1Token", lv1Token },
{ "time", (int)SimApiUtil.TimestampNow },
{ "appId", simApiOptions.CoceSdkOptions.AppId! },
{ "level", level }
};
return QueryAppApi<LevelTokenResponse>("/api/app/token", dict);
}
/// <summary>
/// 通过用户手机号搜索用户
/// </summary>
/// <param name="phone"></param>
/// <returns></returns>
public UserInfo? SearchUserByPhone(string phone)
{
var dict = new Dictionary<string, object>
{
{ "cell", phone },
{ "time", (int)SimApiUtil.TimestampNow },
{ "appId", simApiOptions.CoceSdkOptions.AppId! },
};
return QueryAppApi<UserInfo>("/api/app/user/search-by-phone", dict);
}
/// <summary>
/// 通过给出的UserId列表获取用户信息
/// </summary>
/// <param name="userIds"></param>
/// <returns></returns>
public UserInfo[]? SearchUserByIds(IEnumerable<string> userIds)
{
var dict = new Dictionary<string, object>
{
{ "ids", string.Join(",", userIds) },
{ "time", (int)SimApiUtil.TimestampNow },
{ "appId", simApiOptions.CoceSdkOptions.AppId! },
};
return QueryAppApi<UserInfo[]>("/api/app/user/search-by-ids", dict);
}
/// <summary>
/// 向用户发送消息
/// </summary>
/// <param name="userId"></param>
/// <param name="title"></param>
/// <param name="content"></param>
/// <returns></returns>
public bool SendUserMessage(string userId, string title, string content)
{
var dict = new Dictionary<string, object>
{
{ "time", (int)SimApiUtil.TimestampNow },
{ "appId", simApiOptions.CoceSdkOptions.AppId! },
{ "userId", userId },
{ "type", "text" },
{ "title", title },
{ "text", content }
};
return QueryAppApiNoResp("/api/app/message", dict);
}
/// <summary>
/// 创建交易订单号
/// </summary>
/// <param name="name"></param>
/// <param name="amount"></param>
/// <param name="ext"></param>
/// <returns></returns>
public string? TradeCreate(string name, int amount, string ext)
{
var dict = new Dictionary<string, object>
{
{ "time", (int)SimApiUtil.TimestampNow },
{ "appId", simApiOptions.CoceSdkOptions.AppId! },
{ "amount", amount },
{ "ext", ext },
{ "name", name }
};
return QueryAppApi<string>("/api/app/trade/create", dict);
}
/// <summary>
/// 查询订单状态
/// </summary>
/// <param name="tradeNo"></param>
/// <returns></returns>
public CheckTradeResponse? TradeCheck(string tradeNo)
{
var dict = new Dictionary<string, object>
{
{ "time", (int)SimApiUtil.TimestampNow },
{ "appId", simApiOptions.CoceSdkOptions.AppId! },
{ "tradeNo", tradeNo }
};
return QueryAppApi<CheckTradeResponse>("/api/app/trade/result", dict);
}
/// <summary>
/// 对订单进行退款
/// </summary>
/// <param name="tradeNo"></param>
/// <returns></returns>
public bool TradeRefund(string tradeNo)
{
var dict = new Dictionary<string, object>
{
{ "time", (int)SimApiUtil.TimestampNow },
{ "appId", simApiOptions.CoceSdkOptions.AppId! },
{ "tradeNo", tradeNo }
};
return QueryAppApiNoResp("/api/app/trade/refund", dict);
}
private T? QueryAppApi<T>(string endpoint, Dictionary<string, object> request)
{
var response = QueryAppApi(endpoint, request);
var result = response.Content.ReadFromJsonAsync<SimApiBaseResponse<T>>().Result!;
if (result.Code == 200) return result.Data;
logger.LogDebug("发生错误: {Code} => {Message}", result.Code, result.Message);
return default;
}
private bool QueryAppApiNoResp(string endpoint, Dictionary<string, object> request)
{
var response = QueryAppApi(endpoint, request);
var result = response.Content.ReadFromJsonAsync<SimApiBaseResponse>().Result!;
return result.Code == 200;
}
private HttpResponseMessage QueryAppApi(string endpoint, Dictionary<string, object> 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;
}
/// <summary>
/// 获取用户的群组信息
/// </summary>
/// <param name="token">Level >=2 的Token</param>
/// <returns></returns>
public IEnumerable<GroupInfo>? GetUserGroups(string token)
{
const string uri = "/api/lv2/user/groups";
var resp = ProxyQuery<GroupInfo[]>(uri, token, "{}");
return resp;
}
/// <summary>
/// 获取用户信息
/// </summary>
/// <param name="token"></param>
/// <returns></returns>
public UserInfo? GetUserInfo(string token)
{
const string uri = "/api/lv1/user/info";
return ProxyQuery<UserInfo>(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<dynamic>(uri, token, json);
public dynamic? ProxyQueue(string uri, string token, object data) =>
ProxyQuery<dynamic>(uri, token, SimApiUtil.Json(data));
public T? ProxyQueue<T>(string uri, string token, object data) =>
ProxyQuery<T>(uri, token, SimApiUtil.Json(data));
public T? ProxyQuery<T>(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<SimApiBaseResponse<T>>().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);
}
}
-15
View File
@@ -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; }
}
-52
View File
@@ -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<ConfigResponse> GetConfig()
{
return new SimApiBaseResponse<ConfigResponse>(coce.GetConfig());
}
[HttpPost]
public string Login([FromBody] SimApiOneFieldRequest<string> 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<string, string>
{
{ "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<ICoceLoginProcessor>();
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();
}
}
-43
View File
@@ -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; }
}
-9
View File
@@ -1,9 +0,0 @@
using System.Collections.Generic;
using SimApi.Communications;
namespace SimApi.CoceSdk;
public interface ICoceLoginProcessor
{
SimApiLoginItem Process(SimApiLoginItem loginItem, GroupInfo[] groups);
}
@@ -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;
}
+10 -9
View File
@@ -1,5 +1,4 @@
using System; using System;
using SimApi.CoceSdk;
namespace SimApi.Configurations; namespace SimApi.Configurations;
@@ -51,9 +50,6 @@ public class SimApiOptions
/// </summary> /// </summary>
public bool EnableCors { get; set; } = true; public bool EnableCors { get; set; } = true;
public CoceAppSdkOption CoceSdkOptions { get; set; } = new();
/// <summary> /// <summary>
/// 启用异常拦截,启用后,所有的异常将被通过json反馈。 /// 启用异常拦截,启用后,所有的异常将被通过json反馈。
/// default: true /// default: true
@@ -93,6 +89,9 @@ public class SimApiOptions
public bool EnableLogger { get; set; } = true; public bool EnableLogger { get; set; } = true;
public bool EnableSimApiHttpClient { get; set; } = false;
/// <summary> /// <summary>
/// 配置Job /// 配置Job
/// </summary> /// </summary>
@@ -112,16 +111,18 @@ public class SimApiOptions
public SimApiGateAuthOptions SimApiGateAuthOptions { get; set; } = new(); public SimApiGateAuthOptions SimApiGateAuthOptions { get; set; } = new();
public SimApiHttpClientOptions SimApiHttpClientOptions { get; set; } = new();
public void ConfigureSimApiHttpClient(Action<SimApiHttpClientOptions>? options = null)
{
options?.Invoke(SimApiHttpClientOptions);
}
public void ConfigureSimApiSynapse(Action<SimApiSynapseOptions>? options = null) public void ConfigureSimApiSynapse(Action<SimApiSynapseOptions>? options = null)
{ {
options?.Invoke(SimApiSynapseOptions); options?.Invoke(SimApiSynapseOptions);
} }
public void ConfigureCoceSdk(Action<CoceAppSdkOption>? options = null)
{
options?.Invoke(CoceSdkOptions);
}
public void ConfigureSimApiDoc(Action<SimApiDocOptions>? options = null) public void ConfigureSimApiDoc(Action<SimApiDocOptions>? options = null)
{ {
options?.Invoke(SimApiDocOptions); options?.Invoke(SimApiDocOptions);
+11 -22
View File
@@ -3,19 +3,19 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Net.Http; using System.Net.Http;
using System.Net.Http.Json; using System.Net.Http.Json;
using Microsoft.Extensions.Logging;
using SimApi.Communications; using SimApi.Communications;
using SimApi.Configurations;
using SimApi.Exceptions; using SimApi.Exceptions;
namespace SimApi.Helpers; namespace SimApi.Helpers;
public class SimApiHttpClient public class SimApiHttpClient(SimApiOptions? apiOptions = null, ILogger<SimApiHttpClient>? logger = null)
{ {
public required string Server { get; init; } public string Server { get; init; } = apiOptions?.SimApiHttpClientOptions.Server ?? string.Empty;
public required string AppId { get; init; } 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 SignName { get; init; } = "sign";
public string TimestampName { get; init; } = "timestamp"; public string TimestampName { get; init; } = "timestamp";
public string NonceName { get; init; } = "nonce"; public string NonceName { get; init; } = "nonce";
@@ -103,23 +103,12 @@ public class SimApiHttpClient
private T? Query<T>(string url, object? req) private T? Query<T>(string url, object? req)
{ {
var http = new HttpClient(); var http = new HttpClient();
if (Debug) logger?.LogDebug($"[HTTPCLIENT请求] {url}\n{SimApiUtil.Json(req)}\n");
{
Console.WriteLine($"[HTTPCLIENT请求] {url}\n{SimApiUtil.Json(req)}\n");
}
var resp = http.PostAsJsonAsync(url, req).Result; var resp = http.PostAsJsonAsync(url, req).Result;
if (Debug) logger?.LogDebug($"[HTTPCLIENT响应] {resp.Content.ReadAsStringAsync().Result}\n");
{
Console.WriteLine($"[HTTPCLIENT响应] {resp.Content.ReadAsStringAsync().Result}\n");
}
var res = resp.Content.ReadFromJsonAsync<SimApiBaseResponse<T>>().Result; var res = resp.Content.ReadFromJsonAsync<SimApiBaseResponse<T>>().Result;
if (res == null) SimApiError.ErrorWhenNull(res, 500, "请求发生错误");
{ SimApiError.ErrorWhen(res.Code != 200, res.Code, res.Message);
throw new SimApiException(500, "请求发生错误"); return res.Data;
}
return res.Code != 200 ? throw new SimApiException(res.Code, res.Message) : res.Data;
} }
} }
+10 -35
View File
@@ -16,7 +16,6 @@ using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using SimApi.Attributes; using SimApi.Attributes;
using SimApi.CoceSdk;
using SimApi.Configurations; using SimApi.Configurations;
using SimApi.Interfaces; using SimApi.Interfaces;
using SimApi.Logger; using SimApi.Logger;
@@ -59,11 +58,6 @@ public static class SimApiExtensions
builder.AddSingleton<SimApiAuth>(); builder.AddSingleton<SimApiAuth>();
} }
if (simApiOptions.EnableCoceSdk)
{
builder.AddSingleton<CoceApp>();
}
var simApiAuthChecker = typeof(ISimApiAuthChecker); var simApiAuthChecker = typeof(ISimApiAuthChecker);
var stackTrace = new StackTrace(); var stackTrace = new StackTrace();
var callingMethod = stackTrace.GetFrame(stackTrace.FrameCount - 1)?.GetMethod(); var callingMethod = stackTrace.GetFrame(stackTrace.FrameCount - 1)?.GetMethod();
@@ -108,6 +102,11 @@ public static class SimApiExtensions
policy => { policy.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin(); })); policy => { policy.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin(); }));
} }
if (simApiOptions.EnableSimApiHttpClient)
{
builder.AddSingleton<SimApiHttpClient>();
}
if (simApiOptions.EnableSynapse) if (simApiOptions.EnableSynapse)
{ {
builder.AddSingleton<Synapse>(); builder.AddSingleton<Synapse>();
@@ -355,11 +354,11 @@ public static class SimApiExtensions
builder.Services.GetService<SimApiStorage>(); builder.Services.GetService<SimApiStorage>();
} }
if (options.EnableCoceSdk) if (options.EnableSimApiHttpClient)
{ {
logger.LogInformation("开始配置CoceAppSdk...\nApi入口: {ApiUrl}\nAuth入口:{AuthUrl}n\nAppId: {AppId}", logger.LogInformation("开始配置SimApiHttpClient...\n服务器地址: {ApiUrl}\nAppId:{AuthUrl}n\nAppkey: {AppId}",
options.CoceSdkOptions.ApiEndpoint, options.CoceSdkOptions.AuthEndpoint, options.SimApiHttpClientOptions.Server, options.SimApiHttpClientOptions.AppId,
options.CoceSdkOptions.AppId); !string.IsNullOrEmpty(options.SimApiHttpClientOptions.AppKey));
} }
if (options.EnableSynapse) if (options.EnableSynapse)
@@ -436,30 +435,6 @@ public static class SimApiExtensions
controller = "SimApiAuth", controller = "SimApiAuth",
action = "Logout" 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) if (options.EnableVersionUrl)
@@ -482,7 +457,7 @@ public static class SimApiExtensions
x.DocumentTitle = docOptions.DocumentTitle; x.DocumentTitle = docOptions.DocumentTitle;
foreach (var group in docOptions.ApiGroups) 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); x.SupportedSubmitMethods(docOptions.SupportedMethod);