RsCode.WeChat内封装多个常用的获取accesstoken的方法,自动处理accesstoken的有效期。
它定义于接口IWechatTokenManager
中
csharp
//获取指定AppId的accessToken
Task<string> GetAccessTokenAsync(string appId);
//微信用户授权后获取到的token
Task<string> GetAccessTokenAsync( string appId,string code);
//第三方平台的componentAccessToken
Task<string> GetComponentTokenAsync(string componentAppId);
//第三方平台获取预授权码
Task<string> GetPreAuthCodeAsync(string componentAppId, string componentAccessToken);
注入IWeChatClient ,调用UseAppId("your appid")
csharp
public class Demo
{
WeChatOptions WeChatOptions;
IWeChatClient wechat;
public Demo(IWeChatClient _wechat)
{
wechat=_wechat;
WeChatOptions=wechat.UseAppId("your appid");
}
public async Task<object> GetAccessTokenAsync()
{
// cgi-bin/token
await wechat.SendAsync<AppAccessTokenResponse>(new AppAccessTokenRequest(WeChatOptions.AppId,WeChatOptions.AppSecret));
// sns/oauth2
string code="";//用户授权的code
await wechat.SendAsync<OAuthTokenResponse>(new OAuthTokenRequest(WeChatOptions.AppId,WeChatOptions.AppSecret,code));
}
}
注意:该方法要缓存保存token
推荐:使用IWechatTokenManager ,它会将token自动缓存至内存中
csharp
public test(IWechatTokenManager _wechatTokenManager)
{
wechatTokenManager = _wechatTokenManager;
}
public void GetToken()
{
string appid="";
//获取apptoken
var token = await wechatTokenManager.GetAccessTokenAsync(appid);
//获取用户token
var token = await wechatTokenManager.GetAccessTokenAsync(appid,code);
}
定义类StoreHelper.cs,重新定义存储token的方法,例如
csharp
public class StoreHelper : IStoreHelper
{
ICacheProvider cache;
public StoreHelper(IEnumerable<ICacheProvider>caches)
{
cache = caches.FirstOrDefault(c => c.CacheName == "redis");
}
public T Get<T>(string key)
{
return cache.Get<T>(key);
}
public void Set(string key, object obj, int seconds = 7000)
{
cache.Set(key, obj, seconds);
}
}
添加存储AccessToken的方式
csharp
services.AddScoped<IWechatStore,WechatStore>();
也可自定义AccessToken存储,例
csharp
public class StoreHelper : IWechatStore
{
ICacheProvider cache;
public StoreHelper(IEnumerable<ICacheProvider>caches)
{
cache = caches.FirstOrDefault(c => c.CacheName == "redis");
}
public T Get<T>(string key)
{
return cache.Get<T>(key);
}
public List<WeChatRequestData> GetData(int page = 1, int pageSize = 20)
{
return GetDataAsync(page, pageSize).GetAwaiter().GetResult();
}
public Task<List<WeChatRequestData>> GetDataAsync(int page = 1, int pageSize = 20)
{
return null;
}
public void SaveData(WeChatRequestData data)
{
SaveDataAsync(data).GetAwaiter().GetResult();
}
public Task SaveDataAsync(WeChatRequestData data)
{
string key = "wechat-request-data";
cache.Set(key, data);
return Task.CompletedTask;
}
public void Set(string key, object obj, int seconds = 7000)
{
cache.Set(key, obj, seconds);
}
}
services.AddScoped<IWechatStore,StoreHelper>();