/// <summary> /// 获得令牌 /// </summary> /// <param name="AppId"></param> /// <param name="AppSecret"></param> /// <returns></returns> public string GetAccess_Token(string AppId = null, string AppSecret = null) { string cacheKey = "access_token"; string result; /*如果未输入则使用系统默认配置的帐户*/ if (string.IsNullOrEmpty(AppId) || string.IsNullOrEmpty(AppSecret)) { AppId = config.AppId; AppSecret = config.AppSecret; } //如果缓存中没有access_token 则向微信发请求获取 if (!_memoryCache.TryGetValue(cacheKey, out result)) { //判断是否需要向微信发起请求 var file_result = GetAccess_TokenByJsonFile(); if (string.IsNullOrEmpty(file_result.Item1)) { string url = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", AppId, AppSecret); HttpClient httpClient = new HttpClient(); var t = httpClient.GetStringAsync(url); t.Wait(); result = t.Result; //解析json Hashtable ht = JsonConvert.DeserializeObject <Hashtable>(result); string acctoken = ht["access_token"].ToString(); //写入缓存 _memoryCache.Set(cacheKey, acctoken, new MemoryCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromSeconds(7000))); //写入json文件 WechatModel model = new WechatModel(); model.access_token = acctoken; model.ExportTime = 7000; model.createtime = DateTime.Now; model.AppId = AppId; model.AppSecret = AppSecret; //生成json string writejson = JsonConvert.SerializeObject(model); //写入json文件 WriteFile(writejson); return(acctoken); } else { //将文件中的令牌设置到缓存中 _memoryCache.Set(cacheKey, file_result.Item1, new MemoryCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromSeconds(file_result.Item2))); //返回文件中的令牌 return(file_result.Item1); } } else { //从缓存中获取access_token return(_memoryCache.Get <string>("access_token")); } }
/// <summary> /// 注入配置信息,这里本来想通过DI或者什么方法来 解除注入 还没找到方法 /// </summary> /// <param name="option"></param> public WechatHelper(IOptions <WechatModel> option) { config = option.Value; }