在微信获取中要用到一些包,和一些引入。
1.获取客户端的包:(可下载) install-package Microsoft.Extensions.DependencyInjection
2.获取Redis缓存的包:(可下载) Install-Package ServiceStack.Redis
3获取 json的包:(可下载) Install-Package Newtonsoft.Json -Version 12.0.1
需要引入的命名空间:
using ServiceStack.Redis;
using Newtonsoft.Json;
using System.Net.Http;
具体代码如下:
public class Access_token
{
public static string Gettoken()
{
RedisClient redclicen = new RedisClient();
//先从缓存获取
string token = redclicen.Get<string>("token");
if (token != null)
return token;
//缓存中没有找到从外网获取
HttpClient http = new HttpClient();
string resulttoken = http.GetAsync("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx9d95d04d58ded7ec&secret=8dcb3737f1153f21db6134cecb3b9f82").Result.Content.ReadAsStringAsync().Result;
Access_DTO accessdto = JsonConvert.DeserializeObject<Access_DTO>(resulttoken);
//TimeSpan.FromMilliseconds(accessdto.expless_in-160) 让时间缓慢160秒
//把token写入缓存
redclicen.Set<string>("token", accessdto.access_token,TimeSpan.FromMilliseconds(accessdto.expless_in-160));
return accessdto.access_token;
}
}
封装一个结果类。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DTO
{
public class Access_DTO
{
public string access_token { get; set; }
public int expires_in { get; set; }
}
}