zoukankan      html  css  js  c++  java
  • 获取微信AccessToken,保存在内存中,过期后重新获取

    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 Dictionary<string, AccessToken> tokenCache = new Dictionary<string, AccessToken>();
    
            /// <summary>
            /// 获取缓存令牌
            /// </summary>
            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<AccessToken>(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<AccessToken>(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; }
        }
    }
  • 相关阅读:
    2020/10/23-大族激光
    Windows权限维持总结
    了解蓝军--jsonhijack漏洞学习
    white-space、word-break、word-wrap傻傻分不清楚
    Vue其他指令(v-cloak和v-text,v-html,v-pre,v-once)
    Vue循环渲染(v-for)
    Vue条件渲染(v-if)
    Vue绑定事件监听器(v-on)
    Vue绑定数据和元素属性(v-bind)
    记录一下,破解idea
  • 原文地址:https://www.cnblogs.com/SmilePastaLi/p/10006504.html
Copyright © 2011-2022 走看看