sunpengfei
2025-11-28 312ebed2d86858e4fb57ec09679244e9b806b57f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
using Aliyun.OSS;
using Aop.Api.Domain;
using ApiTools.Core.Utils.WxmpUtils;
using Azure.Core;
using Furion.FriendlyException;
using Furion.HttpRemote;
using Furion.JsonSerialization;
using Mapster;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json.Nodes;
using System.Text.Unicode;
using System.Threading;
using System.Threading.Tasks;
using static System.Net.Mime.MediaTypeNames;
 
namespace ApiTools.Core
{
    /// <summary>
    /// 微信小程序工具
    /// </summary>
    public class WxmpUtils
    {
        private readonly IOptions<WxmpOptions> options;
        private readonly IHttpRemoteService httpRemoteService;
        private readonly IDistributedCache distributedCache;
 
        public WxmpUtils(
            IOptions<WxmpOptions> options,
            IHttpRemoteService httpRemoteService,
            IDistributedCache distributedCache)
        {
            this.options = options;
            this.httpRemoteService = httpRemoteService;
            this.distributedCache = distributedCache;
        }
 
        public async Task<WxmpSnsJscode2sessionResponse> SnsJscode2sessionAsync(string wxmpCode, string code, CancellationToken cancellationToken = default)
        {
            var option = options.Value.Items.FirstOrDefault(it => it.Code == wxmpCode);
            if (option == null || option.AppId.IsNull() || option.AppSecret.IsNull())
                throw Oops.Oh(EnumErrorCodeType.s400, "登录失败,缺失配置:WxmpOptions");
            if (code.IsNull())
                throw Oops.Oh(EnumErrorCodeType.s400, "请填写WxmpCode");
            var callback = await httpRemoteService.GetAsAsync<WxmpSnsJscode2sessionResponse>("https://api.weixin.qq.com/sns/jscode2session",
                builder => builder.WithQueryParameters(new Dictionary<string, string>
                {
                    { "appid", option.AppId },
                    { "secret", option.AppSecret },
                    { "js_code", code },
                    { "grant_type", "authorization_code" }
                }));
            if (callback == null || callback.errcode != 0)
                throw Oops.Oh(EnumErrorCodeType.s510, $"登录失败:{callback.errmsg},请联系管理员");
            return callback;
        }
 
        /// <summary>
        /// 获取小程序接口调用凭据
        /// </summary>
        /// <param name="wxmpCode"></param>
        /// <returns></returns>
        public async Task<string> GetAccessToken(string wxmpCode)
        {
            var cacheKey = $"Wxmp|{wxmpCode}|AccessToken";
            var accessToken = await distributedCache.GetStringAsync(cacheKey);
            if (accessToken.IsNull())
            {
                var option = options.Value.Items.FirstOrDefault(it => it.Code == wxmpCode);
                if (option == null || option.AppId.IsNull() || option.AppSecret.IsNull())
                    throw Oops.Oh(EnumErrorCodeType.s400, "获取小程序接口调用凭据失败,缺失配置:WxmpOptions");
                var request = new WxmpGetAccessTokenRequest
                {
                    Appid = option.AppId,
                    Secret = option.AppSecret,
                };
                var response = await httpRemoteService.GetAsStringAsync("https://api.weixin.qq.com/cgi-bin/token",
                    builder => builder.WithQueryParameters(JsonObject.Parse(request.ToJson())));
                var callback = response.JsonTo<WxmpGetAccessTokenResponse>();
                if (callback == null && callback.AccessToken.IsNull())
                    throw Oops.Oh(EnumErrorCodeType.s510, "获取小程序接口调用凭据失败");
                accessToken = callback.AccessToken;
                await distributedCache.SetStringAsync(cacheKey, accessToken, new DistributedCacheEntryOptions
                {
                    AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(callback.ExpiresIn - 300)
                });
            }
            return accessToken;
        }
 
        /// <summary>
        /// 获取小程序码
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        public async Task<string> GetQrCodeOssUrl(WxmpGetQrCodeCommand command)
        {
            var option = options.Value.Items.FirstOrDefault(it => it.Code == command.WxmpCode);
            if (option == null || option.AppId.IsNull() || option.AppSecret.IsNull())
                throw Oops.Oh(EnumErrorCodeType.s400, "获取小程序码失败,缺失配置:WxmpOptions");
            command.EnvVersion = option.EnvVersion;
            var accessToken = await GetAccessToken(command.WxmpCode);
            var request = command.Adapt<WxmpGetQrCodeRequest>();
            var jsonContent = JsonConvert.SerializeObject(request, new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore
            });
            var response = await httpRemoteService.PostAsync("https://api.weixin.qq.com/wxa/getwxacodeunlimit",
                builder => builder
                .WithQueryParameter("access_token", accessToken)
                .SetJsonContent(jsonContent));
            response.EnsureSuccessStatusCode();
            if (response.Content.Headers.ContentType.ToString() == "application/json; charset=UTF-8")
            {
                var jsonResult = await response.Content.ReadAsStringAsync();
                var callback = jsonResult.JsonTo<WxmpGetQrCodeResponse>();
                if (callback == null || callback.ErrorCode != 0)
                    throw Oops.Oh(EnumErrorCodeType.s510, $"获取小程序码失败:{callback.ErrorMessage},请联系管理员");
            }
            var stream = await response.Content.ReadAsStreamAsync();
            var result = AliyunOSSUtils.Upload(command.OssScene, stream, command.OssFileName);
            return result.Url;
        }
 
        /// <summary>
        /// 查询订阅消息模板
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        public async Task<GetWxmpSubscribMessageTemplatesResponse> GetWxmpSubscribMessageTemplate(GetWxmpSubscribMessageTemplatesRequest command)
        {
            var option = options.Value.Items.FirstOrDefault(it => it.Code == command.WxmpCode);
            if (option == null || option.AppId.IsNull() || option.AppSecret.IsNull())
                throw Oops.Oh(EnumErrorCodeType.s400, "发送订阅消息失败,缺失配置:WxmpOptions");
            var accessToken = await GetAccessToken(command.WxmpCode);
            var jsonContent = JsonConvert.SerializeObject(command, new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore
            });
            var response = await httpRemoteService.GetAsAsync<GetWxmpSubscribMessageTemplatesResponse>(
                "https://api.weixin.qq.com/wxaapi/newtmpl/gettemplate",
                builder => builder.WithQueryParameter("access_token", accessToken));
            return response;
        }
 
        /// <summary>
        /// 发送订阅消息
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        public async Task WxmpSendSubscribMessage(WxmpSendSubscribMessageRequest command)
        {
            var option = options.Value.Items.FirstOrDefault(it => it.Code == command.WxmpCode);
            if (option == null || option.AppId.IsNull() || option.AppSecret.IsNull())
                throw Oops.Oh(EnumErrorCodeType.s400, "发送订阅消息失败,缺失配置:WxmpOptions");
            command.EnvVersion = option.EnvVersion;
            var accessToken = await GetAccessToken(command.WxmpCode);
            var jsonContent = JsonConvert.SerializeObject(command, new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore
            });
            var response = await httpRemoteService.PostAsync("https://api.weixin.qq.com/cgi-bin/message/subscribe/send",
                builder => builder
                .WithQueryParameter("access_token", accessToken)
                .SetJsonContent(jsonContent));
            response.EnsureSuccessStatusCode();
            var jsonResult = await response.Content.ReadAsStringAsync();
            var callback = jsonResult.JsonTo<WxmpSendSubscribMessageResponse>();
            if (callback == null || callback.ErrorCode != 0)
                throw Oops.Oh(EnumErrorCodeType.s510, $"发送订阅消息失败:{callback.ErrorMessage},请联系管理员");
        }
    }
}