因為access_token,在以後的高級功能裡面會經常用到,所以這裡不得不這裡對前面所講解的access_token改造一下。另外需要說明的是access_token是變化的,有自己的周期,官方解釋為:"有效期為7200秒",這就要求我們把獲得的access_token存入一個物理文件或者Appl ...
因為access_token,在以後的高級功能裡面會經常用到,所以這裡不得不這裡對前面所講解的access_token改造一下。
另外需要說明的是access_token是變化的,有自己的周期,官方解釋為:"有效期為7200秒",這就要
求我們把獲得的access_token存入一個物理文件或者Application中,請求到過期後修改這些內容,需要用的時候讀出來.
有些人可能想到了,如果過期我就在獲得一個就好了,不用物理文件和Application也可以達到同樣的效果,但是需要註意了微信平臺對每天獲得
access_token的次數也作了限制,一個用戶出發多次,如果用戶多,那肯定就超出了。所以我們還是按照以上的思路實現這些功能:
在此之前我們已經瞭解了獲得access_token的方法(連接),現在只需要保證它的隨時更新就好了.
首先建立一個Access_token類
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Topevery.EOffice.Web.WX { public class Access_token { public Access_token() { } string _access_token; string _expires_in; /// <summary> /// 獲取的憑證 /// </summary> public string access_token { get { return _access_token; } set { _access_token = value; } } /// <summary> /// 憑證的有效時間,單位:秒 /// </summary> public string expires_in { get { return _expires_in; } set { _expires_in = value; } } } }
/// <summary> /// 獲取審批數據 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Button5_Click(object sender, EventArgs e) { string _access_token = IsExistAccess_Token(); string url = "https://qyapi.weixin.qq.com/cgi-bin/corp/getapprovaldata?access_token=" + _access_token; qywxpara para = new qywxpara(); para.starttime = Stamp(TextStartTime.Text); para.endtime = Stamp(TextEndTime.Text); string json = JsonConvert.SerializeObject(para); string ss = HttpPost(url, json); }
/// <summary> /// 根據當前日期 判斷Access_Token 是否超期 如果超期返回新的Access_Token 否則返回之前的Access_Token /// </summary> /// <param name="datetime"></param> /// <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; }
//POST請求,獲取新的Access_token public static Access_token GetAccess_token() { string appid = "你的appid"; string secret = "你的secret"; string strUrl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + appid + "&corpsecret=" + 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(); //Response.Write(content); //在這裡對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; }
用下麵的XML文件來存放access_token,建立一個XMLFile.xml,把Access_YouXRQ標簽的內容寫成一個已經過去的時間,這樣我們好在一開始調用的時候,發現已經過期,然後獲取新的access_token。
<?xml version="1.0" encoding="utf-8"?> <xml> <Access_Token>初始值可以隨便寫</Access_Token> <Access_YouXRQ>1980/12/12 16:06:38</Access_YouXRQ> </xml>
以上的方法用到了Json對象的處理,所以我把JsonHelper的代碼一貼出來供大家參考,一下就是JsonHelper.cs的代碼:
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Serialization.Json; using System.Text; using System.Web; namespace Topevery.EOffice.Web.WX { public class JsonHelper { /// <summary> /// 生成Json格式 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> /// <returns></returns> public static string GetJson<T>(T obj) { DataContractJsonSerializer json = new DataContractJsonSerializer(obj.GetType()); using (MemoryStream stream = new MemoryStream()) { json.WriteObject(stream, obj); string szJson = Encoding.UTF8.GetString(stream.ToArray()); return szJson; } } /// <summary> /// 獲取Json的Model /// </summary> /// <typeparam name="T"></typeparam> /// <param name="szJson"></param> /// <returns></returns> public static T ParseFromJson<T>(string szJson) { T obj = Activator.CreateInstance<T>(); using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson))) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType()); return (T)serializer.ReadObject(ms); } } } }