feat: 新增微信小程序模块
This commit is contained in:
@@ -0,0 +1,28 @@
|
||||
using Microsoft.Extensions.Caching.Distributed;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Volo.Abp.Caching;
|
||||
|
||||
namespace Yi.Framework.WeChat.MiniProgram.Token;
|
||||
|
||||
internal class CacheMiniProgramToken : DefaultMinProgramToken, IMiniProgramToken
|
||||
{
|
||||
private IDistributedCache<string> _cache;
|
||||
private const string CacheKey = "MiniProgramToken";
|
||||
|
||||
public CacheMiniProgramToken(IOptions<WeChatMiniProgramOptions> options, IDistributedCache<string> cache) :
|
||||
base(options)
|
||||
{
|
||||
_cache = cache;
|
||||
}
|
||||
|
||||
public async Task<string> GetTokenAsync()
|
||||
{
|
||||
return await _cache.GetOrAddAsync("MiniProgramToken", async () => { return await base.GetTokenAsync(); }, () =>
|
||||
{
|
||||
return new DistributedCacheEntryOptions()
|
||||
{
|
||||
AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(2) - TimeSpan.FromMinutes(1)
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
using System.Net.Http.Json;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Yi.Framework.Core.Extensions;
|
||||
using Yi.Framework.WeChat.MiniProgram.HttpModels;
|
||||
|
||||
namespace Yi.Framework.WeChat.MiniProgram.Token;
|
||||
|
||||
internal class DefaultMinProgramToken:IMiniProgramToken
|
||||
{
|
||||
private const string Url = "https://api.weixin.qq.com/cgi-bin/token";
|
||||
private WeChatMiniProgramOptions _options;
|
||||
public DefaultMinProgramToken(IOptions<WeChatMiniProgramOptions> options)
|
||||
{
|
||||
_options = options.Value;
|
||||
}
|
||||
public async Task<string> GetTokenAsync()
|
||||
{
|
||||
var token = await this.GetAccessToken();
|
||||
return token.access_token;
|
||||
}
|
||||
public async Task<AccessTokenResponse> GetAccessToken()
|
||||
{
|
||||
var req = new AccessTokenRequest();
|
||||
req.appid = _options.AppID;
|
||||
req.secret = _options.AppSecret;
|
||||
req.grant_type = "client_credential";
|
||||
using (HttpClient httpClient = new HttpClient())
|
||||
{
|
||||
string queryString = req.ToQueryString();
|
||||
var builder = new UriBuilder(Url);
|
||||
builder.Query = queryString;
|
||||
HttpResponseMessage response = await httpClient.GetAsync(builder.ToString());
|
||||
|
||||
response.EnsureSuccessStatusCode();
|
||||
|
||||
var responseBody = await response.Content.ReadFromJsonAsync<AccessTokenResponse>();
|
||||
return responseBody;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
namespace Yi.Framework.WeChat.MiniProgram.Token;
|
||||
|
||||
public interface IMiniProgramToken
|
||||
{
|
||||
public Task<string> GetTokenAsync();
|
||||
}
|
||||
Reference in New Issue
Block a user