access_token是公眾號的全局唯一票據,公眾號調用各接口時都需使用access_token。正常情況下access_token有效期為7200秒,重復獲取將導致上次獲取的access_token失效。
公眾號可以使用AppID和AppSecret調用本接口來獲取access_token。AppID和AppSecret可在微信公眾平台官網-開發者中心頁中獲得(需要已經成為開發者,且帳號沒有異常狀態)。注意調用所有微信接口時均需使用https協議。
獲取access_token的思路是:用XML文檔存放access_token信息,獲取access_token的時候根據XML存放的上次生成時間判斷是否過期,如果過期重新獲取。
一、新建一個XML文檔,用來存放access_token和時間信息
<?xml version="1.0" encoding="utf-8"?> <xml> <Access_Token>存放Access_Toke,新建的時候可以隨便寫,后面調用的時候會更新的</Access_Token> <Access_YouXRQ>2016/7/22 16:13:15</Access_YouXRQ> </xml>
二、獲取access_token,appid和secret需要輸入自己微信公眾號的就可以了
/// <summary> /// 通過appID和appsecret獲取Access_token /// </summary> /// <returns></returns> private static Access_token GetAccess_token() { string appid = "appid"; string secret = "appsecret"; string strUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret; Access_token mode = new Access_token(); HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(strUrl); req.Method = "GET"; using (WebResponse wr = req.GetResponse()) { HttpWebResponse myResponse = (HttpWebResponse)req.GetResponse(); StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8); string content = reader.ReadToEnd();//在這里對Access_token 賦值 Access_token token = new Access_token(); token = JsonHelper.ParseFromJson<Access_token>(content); mode.access_token = token.access_token; mode.expires_in = token.expires_in; } return mode; }
三、由於access_token會過期,所以獲取access_token的時候要驗證是否過期了
/// <summary> /// 獲取Access_token值 /// </summary> /// <returns></returns> public static string IsExistAccess_Token() { string Token = string.Empty; DateTime YouXRQ; // 讀取XML文件中的數據,並顯示出來 ,注意文件路徑 string filepath = System.Web.HttpContext.Current.Server.MapPath("XMLFile.xml"); StreamReader str = new StreamReader(filepath, System.Text.Encoding.UTF8); XmlDocument xml = new XmlDocument(); xml.Load(str); str.Close(); str.Dispose(); Token = xml.SelectSingleNode("xml").SelectSingleNode("Access_Token").InnerText; YouXRQ = Convert.ToDateTime(xml.SelectSingleNode("xml").SelectSingleNode("Access_YouXRQ").InnerText); if (DateTime.Now > YouXRQ) { DateTime _youxrq = DateTime.Now; Access_token mode = GetAccess_token(); xml.SelectSingleNode("xml").SelectSingleNode("Access_Token").InnerText = mode.access_token; _youxrq = _youxrq.AddSeconds(int.Parse(mode.expires_in)); xml.SelectSingleNode("xml").SelectSingleNode("Access_YouXRQ").InnerText = _youxrq.ToString(); xml.Save(filepath); Token = mode.access_token; } return Token; }
四、直接調用IsExistAccess_Token()就可以獲取了
string AccessToken = IsExistAccess_Token();