企業微信開發: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();
            }
        }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM