66 lines
2.1 KiB
C#
66 lines
2.1 KiB
C#
using System.Timers;
|
||
using Microsoft.Extensions.Logging;
|
||
using Newtonsoft.Json;
|
||
using Newtonsoft.Json.Linq;
|
||
using Timer = System.Timers.Timer;
|
||
|
||
namespace WeChatSharp.Services;
|
||
|
||
public class WeChatAccessTokenService
|
||
{
|
||
public const string _AccessToken = "access_token";
|
||
private readonly HttpClient _httpClient;
|
||
private readonly IWeChatSettings _weChatSettings;
|
||
private readonly Timer _timer=new();
|
||
private readonly ILogger<WeChatAccessTokenService> _logger;
|
||
private string AccessToken { get; set; }=string.Empty;
|
||
|
||
public WeChatAccessTokenService(HttpClient httpClient, IWeChatSettings weChatSettings, ILogger<WeChatAccessTokenService> logger)
|
||
{
|
||
_httpClient = httpClient;
|
||
_weChatSettings = weChatSettings;
|
||
_logger = logger;
|
||
_timer.AutoReset = true;
|
||
_timer.Interval = 3600 * 1000;
|
||
_timer.Elapsed+=_GetAccessToken;
|
||
}
|
||
private async void _GetAccessToken(object? sender, ElapsedEventArgs? e)
|
||
{
|
||
AccessToken = await GetAccessTokenAsync();
|
||
}
|
||
|
||
public async Task<string> GetAccessTokenAsync()
|
||
{
|
||
var newAccessToken = AccessToken;
|
||
if (!string.IsNullOrEmpty(newAccessToken)) return newAccessToken;
|
||
var url =
|
||
$"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={_weChatSettings.AppId}&secret={_weChatSettings.AppSecret}&token={_weChatSettings.Token}";
|
||
var json = await _httpClient.GetStringAsync(url);
|
||
var jObject = JsonConvert.DeserializeObject<JObject>(json);
|
||
if (jObject is null)
|
||
{
|
||
_logger.LogWarning(json);
|
||
throw new NullReferenceException("json为空值");
|
||
}
|
||
if (jObject.TryGetValue("errcode", out var errcode) && jObject.TryGetValue("errmsg",out var errmsg))
|
||
{
|
||
switch (errcode.ToObject<int>())
|
||
{
|
||
case 40164:
|
||
_logger.LogWarning("调用接口的IP地址不在白名单中,请在接口IP白名单中进行设置。");
|
||
break;
|
||
}
|
||
throw new Exception(errmsg.ToObject<string>());
|
||
}
|
||
if (jObject.TryGetValue("access_token", out var token))
|
||
{
|
||
return newAccessToken = token.ToObject<string>() ?? string.Empty;
|
||
}
|
||
_logger.LogWarning(json);
|
||
throw new InvalidOperationException("获取AccessToken失败")
|
||
{
|
||
Source = json,
|
||
};
|
||
}
|
||
|
||
} |