You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

68 lines
3.2 KiB

using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using SKIT.FlurlHttpClient.Wechat.Api;
using SKIT.FlurlHttpClient.Wechat.Api.Models;
using Zncy.CloudCar.WeChat.Service.Options;
using Zncy.CloudCar.WeChat.Service.Services.HttpClients;
using Znyc.CloudCar.Caching;
using Znyc.CloudCar.Configuration;
namespace Znyc.CloudCar.Task.TaskJobs
{
/// <summary>
/// 定时刷新获取微信AccessToken
/// </summary>
public class RefreshWeChatAccessTokenJob
{
private readonly IRedisOperationRepository _redisOperationRepository;
private readonly WeChatOptions _weChatOptions;
private readonly IWeChatApiHttpClientFactory _weChatApiHttpClientFactory;
private readonly ILogger<RefreshWeChatAccessTokenJob> _logger;
public RefreshWeChatAccessTokenJob(IRedisOperationRepository redisOperationRepository, IOptions<WeChatOptions> weChatOptions, IWeChatApiHttpClientFactory weChatApiHttpClientFactory, ILogger<RefreshWeChatAccessTokenJob> logger)
{
_logger = logger;
_redisOperationRepository = redisOperationRepository;
_weChatApiHttpClientFactory = weChatApiHttpClientFactory;
_weChatOptions = weChatOptions.Value;
}
public async System.Threading.Tasks.Task Execute()
{
Console.WriteLine($"{DateTime.Now}定时刷新获取微信AccessToken");
try
{
if (!string.IsNullOrEmpty(_weChatOptions.WxOpenAppId) && !string.IsNullOrEmpty(_weChatOptions.WxOpenAppSecret))
{
var accessToken = await _redisOperationRepository.GetAsync(GlobalEnumVars.AccessTokenEnum.WxOpenAccessToken.ToString());
if (accessToken == null)
{
var client = _weChatApiHttpClientFactory.CreateWxOpenClient();
var request = new CgibinTokenRequest();
var response = await client.ExecuteCgibinTokenAsync(request);
if (response.IsSuccessful())
{
await _redisOperationRepository.SetAsync(
GlobalEnumVars.AccessTokenEnum.WxOpenAccessToken.ToString(), response.AccessToken, TimeSpan.FromDays(30));
_logger.LogDebug($"定时刷新获取微信AccessToken:{response.AccessToken}");
}
else
{
_logger.LogError($"定时刷新获取微信AccessToken,刷新 AppId 为 {_weChatOptions.WeiXinAppId} 微信 AccessToken 失败(状态码:{response.RawStatus},错误代码:{response.ErrorCode},错误描述:{response.ErrorMessage}");
}
}
else
{
_logger.LogDebug($"定时刷新获取微信AccessToken,无需刷新AccessToken,AccessToken 未过期");
}
}
}
catch (Exception ex)
{
_logger.LogDebug($"定时刷新获取微信AccessToken,{ex.Message}");
}
}
}
}