Files
Web_BAI_Manage_ApiServer/docs/example.md
XuJiacheng 72e974672e feat: 实现微信小程序后端接口与用户认证系统
新增微信登录/注册合一接口、资料完善接口和token刷新接口
重构用户服务层,支持自动维护用户类型和资料完整度
引入JWT认证中间件和请求验证中间件
更新文档与测试用例,支持dist构建部署
2026-03-20 18:32:58 +08:00

42 lines
1.6 KiB
Markdown

// 获取微信小程序OpenID
private async Task<string> GetWxOpenIdAsync(string code)
{
try
{
var appId = configuration["WeChat:AppId"];
var appSecret = configuration["WeChat:AppSecret"];
if (string.IsNullOrEmpty(appId) || string.IsNullOrEmpty(appSecret))
{
throw new Exception("微信小程序配置缺失");
}
var httpClient = _httpClientFactory.CreateClient();
var url = $"https://api.weixin.qq.com/sns/jscode2session?appid={appId}&secret={appSecret}&js_code={code}&grant_type=authorization_code";
var response = await httpClient.GetAsync(url);
response.EnsureSuccessStatusCode();
var responseContent = await response.Content.ReadAsStringAsync();
var jsonDocument = JsonDocument.Parse(responseContent);
if (jsonDocument.RootElement.TryGetProperty("openid", out var openidElement))
{
return openidElement.GetString();
}
else
{
// 如果有错误信息,抛出异常
if (jsonDocument.RootElement.TryGetProperty("errcode", out var errcodeElement) &&
jsonDocument.RootElement.TryGetProperty("errmsg", out var errmsgElement))
{
throw new Exception($"获取OpenID失败: {errcodeElement.GetInt32()} - {errmsgElement.GetString()}");
}
throw new Exception("获取OpenID失败: 响应中未包含openid");
}
}
catch (Exception ex)
{
throw new Exception($"获取微信OpenID时发生错误: {ex.Message}");
}
}