1. 程式人生 > >微信企業號 獲取AccessToken

微信企業號 獲取AccessToken

/// <summary>
/// 微信企業號操作
/// </summary>
public class WXQYHHelper
{
    private WXQYHHelper() { }

    static string CORPID;
    static string SECRET;

    /// <summary>
    /// .Ctor
    /// </summary>
    static WXQYHHelper()
    {
        CORPID = ConfigurationManager.AppSettings["CorpID"];
        SECRET = ConfigurationManager.AppSettings["Secret"];
    }

    /// <summary>
    /// ACCESS_TOKEN最後一次更新時間
    /// </summary>
    static DateTime _lastGetTimeOfAccessToken = DateTime.Now.AddSeconds(-7201);

    /// <summary>
    /// 儲存微信訪問憑證
    /// </summary>
    static string _AccessToken;

    /// <summary>
    /// 獲取微信訪問憑證
    /// </summary>
    public static string GetAccessToken()
    {
        try
        {
            if (_lastGetTimeOfAccessToken < DateTime.Now)
            {

                string url = string.Format("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={0}&corpsecret={1}", CORPID, SECRET);
                string responseText = HttpHelper.Instance.get(url); // 封裝的get請求
                /*
                    API:http://qydev.weixin.qq.com/wiki/index.php?title=%E4%B8%BB%E5%8A%A8%E8%B0%83%E7%94%A8#.E8.8E.B7.E5.8F.96AccessToken
                    正確的Json返回示例:
                    {
                       "access_token": "accesstoken000001",
                       "expires_in": 7200
                    }
                    錯誤的Json返回示例:
                    {
                       "errcode": 43003,
                       "errmsg": "require https"
                    }
                */
                var rsEntity = new { access_token = "", expires_in = 0, errcode = 0, errmsg = "" };
                dynamic en = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType<object>(responseText, rsEntity); // Newtonsoft.Json提供的匿名類反序列化
                _lastGetTimeOfAccessToken = DateTime.Now.AddSeconds((double)en.expires_in - 1);
                _AccessToken = en.access_token;
            }
            return _AccessToken;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}