using System.Text; using System.Text.Json; using System.Text.Json.Serialization; using System.Xml.Linq; using SimpleAdmin.Api.WeChat.Options; namespace SimpleAdmin.Api.WeChat.Services; public interface IWeChatMpApiClient { Task CreateLoginQrCodeUrlAsync(string loginUuid, int expireSeconds, CancellationToken cancellationToken = default); /// /// 获取引导关注公众号的永久二维码(scene=oms_follow),结果进程内缓存。 /// Task CreateFollowQrCodeUrlAsync(CancellationToken cancellationToken = default); /// /// 代理下载公众号 showqrcode 图片,供 H5 同源展示以提升微信长按识别成功率。 /// Task<(byte[] Content, string ContentType)> DownloadShowQrCodeAsync( string ticket, CancellationToken cancellationToken = default); Task GetOAuthAccessTokenAsync(string code, CancellationToken cancellationToken = default); Task GetOAuthUserInfoAsync(string accessToken, string openId, CancellationToken cancellationToken = default); /// /// 清空数据库中缓存的公众号 access_token。 /// Task InvalidateAccessTokenCacheAsync(CancellationToken cancellationToken = default); } public sealed record WeChatOAuthTokenResult(string AccessToken, string OpenId, string? Unionid = null); public sealed record WeChatOAuthUserResult( string Openid, string? Nickname, int Sex, string? Province, string? City, string? Country, string? Headimgurl, string? Unionid); internal sealed class WeChatMpApiClient( IHttpClientFactory httpClientFactory, IWeChatMpConfigProvider configProvider, IWeChatMpAccessTokenStore accessTokenStore, ILogger logger) : IWeChatMpApiClient { private readonly object _followQrLock = new(); private string? _cachedFollowQrCodeUrl; public Task InvalidateAccessTokenCacheAsync(CancellationToken cancellationToken = default) => accessTokenStore.ClearAsync(cancellationToken); public async Task CreateLoginQrCodeUrlAsync( string loginUuid, int expireSeconds, CancellationToken cancellationToken = default) { return await CreateQrCodeUrlCoreAsync( actionName: "QR_STR_SCENE", sceneStr: loginUuid, expireSeconds: expireSeconds, retried: false, cancellationToken); } public async Task CreateFollowQrCodeUrlAsync(CancellationToken cancellationToken = default) { lock (_followQrLock) { if (!string.IsNullOrWhiteSpace(_cachedFollowQrCodeUrl)) { return _cachedFollowQrCodeUrl; } } var url = await CreateQrCodeUrlCoreAsync( actionName: "QR_LIMIT_STR_SCENE", sceneStr: WeChatQrSceneParser.FollowScene, expireSeconds: null, retried: false, cancellationToken); lock (_followQrLock) { _cachedFollowQrCodeUrl = url; } return url; } private async Task CreateQrCodeUrlCoreAsync( string actionName, string sceneStr, int? expireSeconds, bool retried, CancellationToken cancellationToken) { var mp = await configProvider.GetAsync(cancellationToken); var accessToken = await GetAccessTokenAsync(mp, cancellationToken); var client = httpClientFactory.CreateClient(nameof(WeChatMpApiClient)); object payload = expireSeconds is > 0 ? new { expire_seconds = expireSeconds.Value, action_name = actionName, action_info = new { scene = new { scene_str = sceneStr } } } : new { action_name = actionName, action_info = new { scene = new { scene_str = sceneStr } } }; // 微信服务端要求 POST 带 Content-Length;PostAsJsonAsync 可能走 chunked 导致 HTTP 412 var json = JsonSerializer.Serialize(payload); using var content = new StringContent(json, Encoding.UTF8, "application/json"); using var response = await client.PostAsync( $"https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token={Uri.EscapeDataString(accessToken)}", content, cancellationToken); var result = await ReadWeChatJsonAsync( response, "创建公众号二维码", cancellationToken); if (result == null || string.IsNullOrWhiteSpace(result.Ticket)) { throw new InvalidOperationException(result?.Errmsg ?? "创建微信二维码失败"); } if (result.Errcode is > 0) { if (!retried && IsAccessTokenInvalidError(result.Errcode)) { logger.LogWarning("微信 access_token 失效(errcode={Errcode}),清空库内 token 后重试创建二维码", result.Errcode); await accessTokenStore.ClearAsync(cancellationToken); return await CreateQrCodeUrlCoreAsync( actionName, sceneStr, expireSeconds, retried: true, cancellationToken); } throw new InvalidOperationException(FormatWeChatError("创建公众号二维码", result.Errcode, result.Errmsg)); } return $"https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket={Uri.EscapeDataString(result.Ticket)}"; } public async Task<(byte[] Content, string ContentType)> DownloadShowQrCodeAsync( string ticket, CancellationToken cancellationToken = default) { if (string.IsNullOrWhiteSpace(ticket)) { throw new ArgumentException("ticket 不能为空", nameof(ticket)); } var client = httpClientFactory.CreateClient(nameof(WeChatMpApiClient)); var url = $"https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket={Uri.EscapeDataString(ticket.Trim())}"; using var response = await client.GetAsync(url, cancellationToken); response.EnsureSuccessStatusCode(); var bytes = await response.Content.ReadAsByteArrayAsync(cancellationToken); if (bytes.Length == 0) { throw new InvalidOperationException("微信二维码图片为空"); } var contentType = response.Content.Headers.ContentType?.MediaType; if (string.IsNullOrWhiteSpace(contentType) || contentType.Contains("text", StringComparison.OrdinalIgnoreCase)) { contentType = "image/jpeg"; } return (bytes, contentType); } public async Task GetOAuthAccessTokenAsync(string code, CancellationToken cancellationToken = default) { var mp = await configProvider.GetAsync(cancellationToken); var client = httpClientFactory.CreateClient(nameof(WeChatMpApiClient)); var url = $"https://api.weixin.qq.com/sns/oauth2/access_token?appid={Uri.EscapeDataString(mp.AppId)}&secret={Uri.EscapeDataString(mp.Secret)}&code={Uri.EscapeDataString(code)}&grant_type=authorization_code"; using var response = await client.GetAsync(url, cancellationToken); response.EnsureSuccessStatusCode(); var body = await response.Content.ReadFromJsonAsync(cancellationToken: cancellationToken); if (body == null || string.IsNullOrWhiteSpace(body.AccessToken) || string.IsNullOrWhiteSpace(body.Openid)) { logger.LogWarning("微信 OAuth 换取 access_token 失败: {Message}", body?.Errmsg); return null; } return new WeChatOAuthTokenResult(body.AccessToken, body.Openid, body.Unionid); } public async Task GetOAuthUserInfoAsync( string accessToken, string openId, CancellationToken cancellationToken = default) { var client = httpClientFactory.CreateClient(nameof(WeChatMpApiClient)); var url = $"https://api.weixin.qq.com/sns/userinfo?access_token={Uri.EscapeDataString(accessToken)}&openid={Uri.EscapeDataString(openId)}&lang=zh_CN"; using var response = await client.GetAsync(url, cancellationToken); response.EnsureSuccessStatusCode(); var body = await response.Content.ReadFromJsonAsync(cancellationToken: cancellationToken); if (body == null || string.IsNullOrWhiteSpace(body.Openid)) { logger.LogWarning("微信 OAuth 获取用户信息失败: {Message}", body?.Errmsg); return null; } return new WeChatOAuthUserResult( body.Openid, body.Nickname, body.Sex, body.Province, body.City, body.Country, body.Headimgurl, body.Unionid); } private async Task GetAccessTokenAsync(WeChatMpOptions mp, CancellationToken cancellationToken) { EnsureConfigured(mp); var cached = await accessTokenStore.GetValidAsync(cancellationToken); if (!string.IsNullOrWhiteSpace(cached)) { return cached; } var client = httpClientFactory.CreateClient(nameof(WeChatMpApiClient)); var url = $"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={Uri.EscapeDataString(mp.AppId)}&secret={Uri.EscapeDataString(mp.Secret)}"; using var response = await client.GetAsync(url, cancellationToken); var body = await ReadWeChatJsonAsync( response, "获取 access_token", cancellationToken); if (body == null || string.IsNullOrWhiteSpace(body.AccessToken)) { throw new InvalidOperationException( FormatWeChatError("获取 access_token", body?.Errcode ?? 0, body?.Errmsg)); } await accessTokenStore.SaveAsync(body.AccessToken, body.ExpiresIn, cancellationToken); return body.AccessToken; } private static bool IsAccessTokenInvalidError(int errcode) => errcode is 40001 or 40014 or 42001; private static void EnsureConfigured(WeChatMpOptions mp) { if (string.IsNullOrWhiteSpace(mp.AppId)) { throw new InvalidOperationException("未配置微信公众号 AppId,请在系统其他配置(wechat_mp)或 Consul 中维护"); } if (string.IsNullOrWhiteSpace(mp.Secret)) { throw new InvalidOperationException("未配置微信公众号 AppSecret,请在系统其他配置(wechat_mp)或 Consul 中维护"); } } private async Task ReadWeChatJsonAsync( HttpResponseMessage response, string action, CancellationToken cancellationToken) where T : class { var raw = await response.Content.ReadAsStringAsync(cancellationToken); if (!response.IsSuccessStatusCode) { logger.LogWarning( "微信{Action} HTTP 失败: {StatusCode} {Body}", action, (int)response.StatusCode, raw); var hint = response.StatusCode == System.Net.HttpStatusCode.PreconditionFailed ? "(常见于 POST 未带 Content-Length 或出口 IP 未加白名单,请检查服务端 HttpClient 与公众号 IP 白名单)" : string.Empty; throw new InvalidOperationException( $"微信{action}失败 HTTP {(int)response.StatusCode} {response.ReasonPhrase}: {raw}{hint}"); } if (string.IsNullOrWhiteSpace(raw)) { return null; } try { return JsonSerializer.Deserialize(raw); } catch (JsonException ex) { logger.LogWarning(ex, "微信{Action}响应解析失败: {Body}", action, raw); throw new InvalidOperationException($"微信{action}响应解析失败: {raw}", ex); } } private static string FormatWeChatError(string action, int errcode, string? errmsg) { var message = string.IsNullOrWhiteSpace(errmsg) ? $"errcode={errcode}" : errmsg; if (errcode == 40164) { return $"微信{action}失败: {message}(请将 API 服务器出口 IP 加入公众号 IP 白名单)"; } if (errcode is 40001 or 40013 or 40125 or 40014 or 42001) { return $"微信{action}失败: {message}(请检查 AppId / AppSecret 是否正确,或 access_token 已失效需刷新)"; } return $"微信{action}失败: {message}"; } private sealed class WeChatAccessTokenResponse { [JsonPropertyName("access_token")] public string? AccessToken { get; set; } [JsonPropertyName("expires_in")] public int ExpiresIn { get; set; } [JsonPropertyName("errcode")] public int Errcode { get; set; } [JsonPropertyName("errmsg")] public string? Errmsg { get; set; } } private sealed class WeChatQrTicketResponse { [JsonPropertyName("ticket")] public string? Ticket { get; set; } [JsonPropertyName("expire_seconds")] public int ExpireSeconds { get; set; } [JsonPropertyName("errcode")] public int Errcode { get; set; } [JsonPropertyName("errmsg")] public string? Errmsg { get; set; } } private sealed class WeChatOAuthTokenResponse { [JsonPropertyName("access_token")] public string? AccessToken { get; set; } [JsonPropertyName("openid")] public string? Openid { get; set; } [JsonPropertyName("unionid")] public string? Unionid { get; set; } [JsonPropertyName("errcode")] public int Errcode { get; set; } [JsonPropertyName("errmsg")] public string? Errmsg { get; set; } } private sealed class WeChatOAuthUserResponse { [JsonPropertyName("openid")] public string? Openid { get; set; } [JsonPropertyName("nickname")] public string? Nickname { get; set; } [JsonPropertyName("sex")] public int Sex { get; set; } [JsonPropertyName("province")] public string? Province { get; set; } [JsonPropertyName("city")] public string? City { get; set; } [JsonPropertyName("country")] public string? Country { get; set; } [JsonPropertyName("headimgurl")] public string? Headimgurl { get; set; } [JsonPropertyName("unionid")] public string? Unionid { get; set; } [JsonPropertyName("errcode")] public int Errcode { get; set; } [JsonPropertyName("errmsg")] public string? Errmsg { get; set; } } } internal static class WeChatXmlMessageParser { public static WeChatIncomingMessage? Parse(string xml) { if (string.IsNullOrWhiteSpace(xml)) { return null; } var doc = XDocument.Parse(xml); var root = doc.Root; if (root == null) { return null; } string? Value(string name) => root.Element(name)?.Value; return new WeChatIncomingMessage { ToUserName = Value("ToUserName"), FromUserName = Value("FromUserName"), CreateTime = Value("CreateTime"), MsgType = Value("MsgType"), Event = Value("Event"), EventKey = Value("EventKey"), Content = Value("Content"), UnionId = Value("UnionId") }; } } internal static class WeChatJsonMessageParser { public static WeChatIncomingMessage? Parse(string json) { if (string.IsNullOrWhiteSpace(json)) { return null; } try { using var doc = JsonDocument.Parse(json); var root = doc.RootElement; string? GetString(string name) { if (!root.TryGetProperty(name, out var prop)) { return null; } return prop.ValueKind switch { JsonValueKind.String => prop.GetString(), JsonValueKind.Number => prop.GetRawText(), JsonValueKind.True => "true", JsonValueKind.False => "false", _ => prop.ToString() }; } return new WeChatIncomingMessage { ToUserName = GetString("ToUserName"), FromUserName = GetString("FromUserName"), CreateTime = GetString("CreateTime"), MsgType = GetString("MsgType"), Event = GetString("Event"), EventKey = GetString("EventKey"), Content = GetString("Content"), UnionId = GetString("UnionId") }; } catch (JsonException) { return null; } } } internal static class WeChatIncomingMessageParser { public static WeChatIncomingMessage? Parse(string body, string? contentType) { if (string.IsNullOrWhiteSpace(body)) { return null; } var trimmed = body.TrimStart(); if (IsJson(contentType, trimmed)) { return WeChatJsonMessageParser.Parse(body); } return WeChatXmlMessageParser.Parse(body); } private static bool IsJson(string? contentType, ReadOnlySpan body) => contentType?.Contains("json", StringComparison.OrdinalIgnoreCase) == true || body.StartsWith("{"); } public sealed class WeChatIncomingMessage { public string? ToUserName { get; init; } public string? FromUserName { get; init; } public string? CreateTime { get; init; } public string? MsgType { get; init; } public string? Event { get; init; } public string? EventKey { get; init; } public string? Content { get; init; } /// 开放平台绑定后事件推送可能带 UnionId。 public string? UnionId { get; init; } } internal static class WeChatXmlMessageBuilder { public static string BuildTextReply(string toUser, string fromUser, string content) { var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); return $""" {now} """; } }