Files
CoreShop/CoreCms.Net.Task/RefreshWeChatAccessTokenJob.cs
T
大灰灰 94e5145b7b !92 调整redis队列,删除盛派【Senparc】相关组件等更新
* 1、【后端】移除业务逻辑中的【MediatR】及中介者模式,启用【Redis队列】处理。
* Merge branch 'develop' into dahuihui/develop
* 升级编辑器为CKEditor5
* Merge branch 'develop' into dahuihui/develop
* Merge branch 'develop' into dahuihui/develop
* 【后端】优化后端设置权限角色,反射controller和action的效率问题。
* 【后端】修复后端编辑商品问题。
* 【后端】修复腾讯云cos存储未调用bucket问题。#I42DF0
* Merge branch 'develop' into dahuihui/develop
* 启用新域名及演示平台
* Merge branch 'develop' into dahuihui/develop
* Merge branch 'develop' into dahuihui/develop
* 调整说明
* Merge branch 'develop' into dahuihui/develop
* 删除不需要的菜单
* 修复域名转发获取ip地址长度过长问题。
* 1、【后端】调整全局错误返回提示语。2、【数据库】修复20日删除3个表后,未清理干净问题。
* Merge branch 'develop' into dahuihui/develop
* Merge branch 'develop' into dahuihui/develop
* 调整全局错误返回提示语
* 修复商品批量处理报错的问题并优化展示界面。#I3X8PP
* Merge branch 'develop' into dahuihui/develop
* Merge branch 'develop' into dahuihui/develop
* 增加过滤敏感词的功能。#I3W6CM
* 增加Issue 和 Pull Request 模板
* 修复自定义上传路径上传至站点根目录,而非wwwroot的问题 #I41TD1
* Merge branch 'develop' into dahuihui/develop
* 修复自定义上传路径的表单命名异常问题
* 使用新数据库
* 【数据库】修复mysql数据库decimal类型未带小数的问题。#I3WAUY
* 更新数据库及脚本
* 2021-07-20
* Merge branch 'develop' into dahuihui/develop
* 修复webapi不进入调试断点的问题。
* Merge branch 'develop' into dahuihui/develop
* 修复后台前后端分离table面板启用自定义域名问题。
* 修复后台前后端分离域名未增加到html问题。
* Merge branch 'develop' into dahuihui/develop
* 【后端】修复修改登录用户真实姓名长度问题。
* 修复后台管理配送方式维护错误问题
* 1、修复小程序注册问题,导致交互事情。不然盛派的组件有bug,在不注册微信公众号只注册微信小程序的时候,进行小程序消息操作,默认还是走的是微…
* 修复消息模板不推送的问题
* Merge branch 'develop' into dahuihui/develop
* Merge branch 'develop' into dahuihui/develop
* 修复过期失效文档
* 调整代码生成器,增加初始化事务
* 调整接口端提示界面
* 修复弹窗不居中问题
* 调整一些命名方式
* 修复uni-app前端,用户订单列表【确认收货】按钮失效问题
* 1、修复mysql数据库下,报表统计sql的语法错误。2、为方便前端在不部署接口及后端的情况下测试uni-app前端,默认增加了测试接口地址…
* Merge branch 'develop' into dahuihui/develop
* 调整命名
* 增加docker-compose部署
* Merge branch 'develop' into dahuihui/develop
* 修复因linux下存在数据与文件名称大小写不对应,导致找不到数据库表的问题,特重新发布一份表名与实体名称一一对应脚本。
* 新mysql表名存在大小写问题
2021-08-01 09:47:47 +00:00

228 lines
12 KiB
C#

/***********************************************************************
* Project: CoreCms.Net *
* Web: https://CoreCms.Net *
* ProjectName: 核心内容管理系统 *
* Author: 大灰灰 *
* Email: JianWeie@163.com *
* CreateTime: 2020-08-25 1:25:29
* 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.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();
client.Configure(settings =>
{
settings.JsonSerializer = new FlurlNewtonsoftJsonSerializer();
});
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.Set(GlobalEnumVars.AccessTokenEnum.WeiXinAccessToken.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 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();
client.Configure(settings =>
{
settings.JsonSerializer = new FlurlNewtonsoftJsonSerializer();
});
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.Set(
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);
}
}
}
}