username@email.com
2024-05-15 c2b4e7c86e790d3880a8da9adeffafb3e6c12145
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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
/***********************************************************************
 *            Project: baifenBinfa.Net                                     *
 *                Web: https://baifenBinfa.com                             *
 *        ProjectName: 百分兵法管理系统                               *
 *             Author:                                        *
 *              Email:                               *
 *         CreateTime: 2024-03-11 09:33:00
 *        Description: 暂无
 ***********************************************************************/
 
 
using System;
using CoreCms.Net.Caching.AutoMate.RedisCache;
using CoreCms.Net.Configuration;
using CoreCms.Net.IServices;
using CoreCms.Net.Model.Entities;
using CoreCms.Net.WeChat.Service.HttpClients;
using CoreCms.Net.WeChat.Service.Options;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using SKIT.FlurlHttpClient;
using SKIT.FlurlHttpClient.Wechat;
using SKIT.FlurlHttpClient.Wechat.Api;
using SKIT.FlurlHttpClient.Wechat.Api.Models;
 
 
namespace CoreCms.Net.Task
{
    /// <summary>
    /// 定时刷新获取微信AccessToken
    /// </summary>
    public class RefreshWeChatAccessTokenJob
    {
        private readonly ISysTaskLogServices _taskLogServices;
 
        private readonly IRedisOperationRepository _redisOperationRepository;
 
        private readonly WeChatOptions _weChatOptions;
        private readonly IWeChatApiHttpClientFactory _weChatApiHttpClientFactory;
        private readonly IWeChatAccessTokenServices _weChatAccessTokenServices;
 
 
        public RefreshWeChatAccessTokenJob(IRedisOperationRepository redisOperationRepository, ISysTaskLogServices taskLogServices, IOptions<WeChatOptions> weChatOptions, IWeChatApiHttpClientFactory weChatApiHttpClientFactory, IWeChatAccessTokenServices weChatAccessTokenServices)
        {
            _redisOperationRepository = redisOperationRepository;
            _taskLogServices = taskLogServices;
            _weChatApiHttpClientFactory = weChatApiHttpClientFactory;
            _weChatAccessTokenServices = weChatAccessTokenServices;
            _weChatOptions = weChatOptions.Value;
        }
 
        public async System.Threading.Tasks.Task Execute()
        {
            try
            {
                //微信公众号刷新
                if (!string.IsNullOrEmpty(_weChatOptions.WeiXinAppId) && !string.IsNullOrEmpty(_weChatOptions.WeiXinAppSecret))
                {
                    var entity = await _weChatAccessTokenServices.QueryByClauseAsync(p => p.appId == _weChatOptions.WeiXinAppId && p.appType == (int)GlobalEnumVars.AccessTokenEnum.WeiXinAccessToken);
                    if (entity == null || entity.expireTimestamp <= DateTimeOffset.Now.ToUnixTimeSeconds())
                    {
                        var client = _weChatApiHttpClientFactory.CreateWeXinClient();
 
                        var request = new CgibinTokenRequest();
                        var response = await client.ExecuteCgibinTokenAsync(request);
                        if (!response.IsSuccessful())
                        {
                            //插入日志
                            var log = new SysTaskLog
                            {
                                createTime = DateTime.Now,
                                isSuccess = false,
                                name = "定时刷新获取微信AccessToken",
                                parameters = $"刷新 AppId 为 {_weChatOptions.WeiXinAppId} 微信 AccessToken 失败(状态码:{response.RawStatus},错误代码:{response.ErrorCode},错误描述:{response.ErrorMessage})。"
                            };
                            await _taskLogServices.InsertAsync(log);
                        }
                        else
                        {
                            // 提前十分钟过期,以便于系统能及时刷新,防止因在过期临界点时出现问题
                            long nextExpireTimestamp = DateTimeOffset.Now.AddSeconds(response.ExpiresIn).AddMinutes(-10).ToUnixTimeSeconds();
 
                            if (entity == null)
                            {
                                entity = new WeChatAccessToken();
 
                                entity.appId = _weChatOptions.WeiXinAppId;
                                entity.accessToken = response.AccessToken;
                                entity.appType = (int)GlobalEnumVars.AccessTokenEnum.WeiXinAccessToken;
                                entity.expireTimestamp = nextExpireTimestamp;
                                entity.createTimestamp = DateTimeOffset.Now.ToUnixTimeSeconds();
                                entity.updateTimestamp = entity.createTimestamp;
 
                                entity.id = await _weChatAccessTokenServices.InsertAsync(entity);
                            }
                            else
                            {
                                entity.accessToken = response.AccessToken;
                                entity.expireTimestamp = nextExpireTimestamp;
                                entity.updateTimestamp = DateTimeOffset.Now.ToUnixTimeSeconds();
                                await _weChatAccessTokenServices.UpdateAsync(entity);
                            }
                            await _redisOperationRepository.SetAsync(GlobalEnumVars.AccessTokenEnum.WeiXinAccessToken.ToString(), entity, TimeSpan.FromMinutes(120));
 
                            //获取js-token并且全局缓存
                            var requestJsTicket = new CgibinTicketGetTicketRequest();
                            requestJsTicket.AccessToken = response.AccessToken;
 
                            var responseJsTicket = await client.ExecuteCgibinTicketGetTicketAsync(requestJsTicket);
                            if (responseJsTicket.IsSuccessful())
                            {
                                //插入缓存
                                await _redisOperationRepository.SetAsync(GlobalEnumVars.JsApiTicketEnum.WeiXinJsApiTicket.ToString(), responseJsTicket, TimeSpan.FromMinutes(120));
                            }
 
                            
                            //插入日志
                            var model = new SysTaskLog
                            {
                                createTime = DateTime.Now,
                                isSuccess = true,
                                name = "定时刷新获取微信AccessToken",
                                parameters = JsonConvert.SerializeObject(entity)
                            };
                            await _taskLogServices.InsertAsync(model);
                        }
                    }
                    else
                    {
                        //插入日志
                        var model = new SysTaskLog
                        {
                            createTime = DateTime.Now,
                            isSuccess = true,
                            name = "定时刷新获取微信AccessToken",
                            parameters = "无需刷新AccessToken,AccessToken 未过期"
                        };
                        await _taskLogServices.InsertAsync(model);
                    }
                }
                //微信小程序也刷新
                if (!string.IsNullOrEmpty(_weChatOptions.WxOpenAppId) && !string.IsNullOrEmpty(_weChatOptions.WxOpenAppSecret))
                {
                    var entity = await _weChatAccessTokenServices.QueryByClauseAsync(p => p.appId == _weChatOptions.WxOpenAppId && p.appType == (int)GlobalEnumVars.AccessTokenEnum.WxOpenAccessToken);
                    if (entity == null || entity.expireTimestamp <= DateTimeOffset.Now.ToUnixTimeSeconds())
                    {
                        var client = _weChatApiHttpClientFactory.CreateWxOpenClient();
 
                        var request = new CgibinTokenRequest();
                        var response = await client.ExecuteCgibinTokenAsync(request);
                        if (response.IsSuccessful())
                        {
                            // 提前十分钟过期,以便于系统能及时刷新,防止因在过期临界点时出现问题
                            long nextExpireTimestamp = DateTimeOffset.Now.AddSeconds(response.ExpiresIn).AddMinutes(-10).ToUnixTimeSeconds();
 
                            if (entity == null)
                            {
                                entity = new WeChatAccessToken();
 
                                entity.appId = _weChatOptions.WxOpenAppId;
                                entity.accessToken = response.AccessToken;
                                entity.appType = (int)GlobalEnumVars.AccessTokenEnum.WxOpenAccessToken;
                                entity.expireTimestamp = nextExpireTimestamp;
                                entity.createTimestamp = DateTimeOffset.Now.ToUnixTimeSeconds();
                                entity.updateTimestamp = entity.createTimestamp;
 
                                await _weChatAccessTokenServices.InsertAsync(entity);
                            }
                            else
                            {
                                entity.accessToken = response.AccessToken;
                                entity.expireTimestamp = nextExpireTimestamp;
                                entity.updateTimestamp = DateTimeOffset.Now.ToUnixTimeSeconds();
                                await _weChatAccessTokenServices.UpdateAsync(entity);
                            }
 
                            await _redisOperationRepository.SetAsync(
                                GlobalEnumVars.AccessTokenEnum.WxOpenAccessToken.ToString(), entity,
                                TimeSpan.FromMinutes(120));
 
                            //插入日志
                            var model = new SysTaskLog
                            {
                                createTime = DateTime.Now,
                                isSuccess = true,
                                name = "定时刷新获取微信AccessToken",
                                parameters = JsonConvert.SerializeObject(entity)
                            };
                            await _taskLogServices.InsertAsync(model);
                        }
                        else
                        {
                            //插入日志
                            var log = new SysTaskLog
                            {
                                createTime = DateTime.Now,
                                isSuccess = false,
                                name = "定时刷新获取微信AccessToken",
                                parameters = $"刷新 AppId 为 {_weChatOptions.WeiXinAppId} 微信 AccessToken 失败(状态码:{response.RawStatus},错误代码:{response.ErrorCode},错误描述:{response.ErrorMessage})。"
                            };
                            await _taskLogServices.InsertAsync(log);
                        }
                    }
                    else
                    {
                        //插入日志
                        var model = new SysTaskLog
                        {
                            createTime = DateTime.Now,
                            isSuccess = true,
                            name = "定时刷新获取微信AccessToken",
                            parameters = "无需刷新AccessToken,AccessToken 未过期"
                        };
                        await _taskLogServices.InsertAsync(model);
                    }
                }
            }
            catch (Exception ex)
            {
                //插入日志
                var model = new SysTaskLog
                {
                    createTime = DateTime.Now,
                    isSuccess = false,
                    name = "定时刷新获取微信AccessToken",
                    parameters = JsonConvert.SerializeObject(ex)
                };
                await _taskLogServices.InsertAsync(model);
            }
        }
    }
}