企业微信开发:3 C#获取AccessToken

获取 AccessToken 官方文档

https://work.weixin.qq.com/api/doc/90000/90135/91039 

详细的参数说明文档都有介绍

Controller层

[HttpGet]
        public string Get(bool refresh = false)
        {
            try
            {
                string accessToken = JsSdkProcess.GetCurrentAccessToken(refresh);
                return accessToken;

            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

注意事项:
开发者需要缓存access_token,用于后续接口的调用(注意:不能频繁调用gettoken接口,否则会受到频率拦截)。当access_token失效或过期时,需要重新获取。

缓存

 public class JsSdkProcess
    {
        /// <summary>
        /// 全局验证器缓存容器
        /// </summary>
        private static MemoryCacheClient MemoryCache = new MemoryCacheClient();
       
        /// <summary>
        /// 获取普通access_token并进行缓存
        /// </summary>
        /// <returns></returns>
        public static string GetCurrentAccessToken(bool refresh = false)
        {
            try
            {
                //需要强制刷新
                if (refresh)
                {
                    var accessToken = AccessTokenService.GetAccessToken();
                    if (!accessToken.StartsWith("Exception:"))
                    {
                        MemoryCache.Set("GetCurrentAccessToken()", accessToken, DateTime.Now.AddSeconds(7200));
                    }
                    return accessToken;
                }
                //不需要强制刷新
                else
                {
                    var accessToken = MemoryCache.Get<string>("GetCurrentAccessToken()");
                    if (string.IsNullOrWhiteSpace(accessToken))
                    {
                        accessToken = AccessTokenService.GetAccessToken();
                        if (!accessToken.StartsWith("Exception:"))
                        {
                            MemoryCache.Set("GetCurrentAccessToken()", accessToken, DateTime.Now.AddSeconds(7200));
                        }
                    }
                    return accessToken;
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
    }

Service层

 public static string GetAccessToken()
        {
            try
            {
                string wxUrl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={0}&corpsecret={1}";
                wxUrl = wxUrl.Fmt(corpid, corpsecret);
                var json = wxUrl.GetStringFromUrl();
                var data = json.FromJson<Dictionary<string, string>>();
                if (data["errcode"] == "0")
                {
                    return data["access_token"];
                }
                return "NotAccessToken:" + data.ToJsv();
            }
            catch (System.Exception ex)
            {
                return "Exception:" + ex.ToString();
            }
        }

猜你喜欢

转载自www.cnblogs.com/liushoushou/p/12101067.html
今日推荐