using Newtonsoft.Json;using System;using System.Collections.Generic;using System.Linq;using System.Net;using System.Threading.Tasks;namespace report.Utils{ public class WeChatHelper { public static string GetToken(string appId, string appSecret) { string tokenUrl = $"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appId}&secret={appSecret}"; var wc = new WebClient(); var strReturn = wc.DownloadString(tokenUrl); return strReturn; } //token缓存键值对 private static DictionarytokenCache = new Dictionary (); /// /// 获取缓存令牌 /// public static string GetAccessToken(string appid, string secret) { //token缓存 AccessToken result = null; //判断缓存是否存在键:appid,就将缓存中的token赋给result if (tokenCache.ContainsKey(appid)) { result = tokenCache[appid]; } //不存在则获取token if (result == null) { result = JsonConvert.DeserializeObject(GetToken(appid, secret)); result.CreateTime = DateTime.Now; tokenCache.Add(appid, result); } //判断是否在有效期内,过期重新获取token 给10s延迟时间 else if (System.DateTime.Compare(result.CreateTime.AddSeconds(result.Expires_In), System.DateTime.Now) < 10) { result = JsonConvert.DeserializeObject (GetToken(appid, secret)); result.CreateTime = DateTime.Now; tokenCache[appid] = result; } return result.Access_token; } } public class AccessToken { public string Access_token { get; set; } public int Expires_In { get; set; } public DateTime CreateTime { get; set; } }}