每次在于微信交互时,都要用到access_token,但是这个值限制的是有时间的,但是access_token,在以后的高级功能里面会经常用到,所以这里不得不这里对前面所讲解的access_token改造一下。
另外需要说明的是access_token是变化的,有自己的周期,官方解释为:"有效期为7200秒",这就要求我们把获得的access_token存入一个物理文件或者Application中,请求到过期后修改这些内容,需要用的时候读出来.或者是存入数据库,到期时修改改access_token的值。
有些人可能想到了,如果过期我就在获得一个就好了,不用物理文件和Application也可以达到同样的效果,但是需要注意了微信平台对每天获得,access_token的次数也作了限制,一个用户出发多次,如果用户多,那肯定就超出了。所以我们还是按照以上的思路实现这些功能:
在此之前我们已经了解了获得access_token的方法(连接)http://www.cnblogs.com/QLJ1314/p/3838058.html,现在只需要保证它的随时更新就好了.
首先建立一个Access_token类
1 /// <summary> 2 ///Access_token 的摘要说明 3 /// </summary> 4 public class Access_token 5 { 6 public Access_token() 7 { 8 // 9 //TODO: 在此处添加构造函数逻辑 10 // 11 } 12 string _access_token; 13 string _expires_in; 14 15 /// <summary> 16 /// 获取到的凭证 17 /// </summary> 18 public string access_token 19 { 20 get { return _access_token; } 21 set { _access_token = value; } 22 } 23 24 /// <summary> 25 /// 凭证有效时间,单位:秒 26 /// </summary> 27 public string expires_in 28 { 29 get { return _expires_in; } 30 set { _expires_in = value; } 31 } 32 }
1 /// <summary> 2 ///Access_token 的摘要说明 3 /// </summary> 4 public class Access_token 5 { 6 public Access_token() 7 { 8 // 9 //TODO: 在此处添加构造函数逻辑 10 // 11 } 12 string _access_token; 13 string _expires_in; 14 15 /// <summary> 16 /// 获取到的凭证 17 /// </summary> 18 public string access_token 19 { 20 get { return _access_token; } 21 set { _access_token = value; } 22 } 23 24 /// <summary> 25 /// 凭证有效时间,单位:秒 26 /// </summary> 27 public string expires_in 28 { 29 get { return _expires_in; } 30 set { _expires_in = value; } 31 } 32 }
用下面的XML文件来存放access_token,建立一个XMLFile.xml,把Access_YouXRQ标签的内容写成一个已经过去的时间,这样我们好在一开始调用的时候,发现已经过期,然后获取新的access_token。
1 <?xml version="1.0" encoding="utf-8"?> 2 <xml> 3 <Access_Token>初始值可以随便写</Access_Token> 4 <Access_YouXRQ>1990/12/12 16:06:38</Access_YouXRQ> 5 </xml>
1 <?xml version="1.0" encoding="utf-8"?> 2 <xml> 3 <Access_Token>初始值可以随便写</Access_Token> 4 <Access_YouXRQ>1990/12/12 16:06:38</Access_YouXRQ> 5 </xml>
之前获得Access_token的方法改造一下,让他给Access_token实例赋值
1 public static Access_token GetAccess_token() 2 { 3 string appid = 你的appid ; 4 string secret = 你的secret; 5 string strUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret; 6 Access_token mode = new Access_token(); 7 8 HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(strUrl); 9 10 req.Method = "GET"; 11 using (WebResponse wr = req.GetResponse()) 12 { 13 HttpWebResponse myResponse = (HttpWebResponse)req.GetResponse(); 14 15 StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8); 16 17 string content = reader.ReadToEnd(); 18 //Response.Write(content); 19 //在这里对Access_token 赋值 20 Access_token token = new Access_token(); 21 token = JsonHelper.ParseFromJson<Access_token>(content); 22 mode.access_token = token.access_token; 23 mode.expires_in = token.expires_in; 24 } 25 return mode; 26 }
1 public static Access_token GetAccess_token() 2 { 3 string appid = 你的appid ; 4 string secret = 你的secret; 5 string strUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret; 6 Access_token mode = new Access_token(); 7 8 HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(strUrl); 9 10 req.Method = "GET"; 11 using (WebResponse wr = req.GetResponse()) 12 { 13 HttpWebResponse myResponse = (HttpWebResponse)req.GetResponse(); 14 15 StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8); 16 17 string content = reader.ReadToEnd(); 18 //Response.Write(content); 19 //在这里对Access_token 赋值 20 Access_token token = new Access_token(); 21 token = JsonHelper.ParseFromJson<Access_token>(content); 22 mode.access_token = token.access_token; 23 mode.expires_in = token.expires_in; 24 } 25 return mode; 26 }
以上的方法用到了Json对象的处理,所以我把JsonHelper的代码一贴出来供大家参考,一下就是JsonHelper.cs的代码:
1 using System; 2 using System.IO; 3 using System.Text; 4 using System.Runtime.Serialization.Json; 5 6 7 8 public class JsonHelper 9 { 10 /// <summary> 11 /// 生成Json格式 12 /// </summary> 13 /// <typeparam name="T"></typeparam> 14 /// <param name="obj"></param> 15 /// <returns></returns> 16 public static string GetJson<T>(T obj) 17 { 18 DataContractJsonSerializer json = new DataContractJsonSerializer(obj.GetType()); 19 using (MemoryStream stream = new MemoryStream()) 20 { 21 json.WriteObject(stream, obj); 22 string szJson = Encoding.UTF8.GetString(stream.ToArray()); return szJson; 23 } 24 } 25 /// <summary> 26 /// 获取Json的Model 27 /// </summary> 28 /// <typeparam name="T"></typeparam> 29 /// <param name="szJson"></param> 30 /// <returns></returns> 31 public static T ParseFromJson<T>(string szJson) 32 { 33 T obj = Activator.CreateInstance<T>(); 34 using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson))) 35 { 36 DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType()); 37 return (T)serializer.ReadObject(ms); 38 } 39 } 40 }
1 using System; 2 using System.IO; 3 using System.Text; 4 using System.Runtime.Serialization.Json; 5 6 7 8 public class JsonHelper 9 { 10 /// <summary> 11 /// 生成Json格式 12 /// </summary> 13 /// <typeparam name="T"></typeparam> 14 /// <param name="obj"></param> 15 /// <returns></returns> 16 public static string GetJson<T>(T obj) 17 { 18 DataContractJsonSerializer json = new DataContractJsonSerializer(obj.GetType()); 19 using (MemoryStream stream = new MemoryStream()) 20 { 21 json.WriteObject(stream, obj); 22 string szJson = Encoding.UTF8.GetString(stream.ToArray()); return szJson; 23 } 24 } 25 /// <summary> 26 /// 获取Json的Model 27 /// </summary> 28 /// <typeparam name="T"></typeparam> 29 /// <param name="szJson"></param> 30 /// <returns></returns> 31 public static T ParseFromJson<T>(string szJson) 32 { 33 T obj = Activator.CreateInstance<T>(); 34 using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson))) 35 { 36 DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType()); 37 return (T)serializer.ReadObject(ms); 38 } 39 } 40 }
其实还可以直接饮用Newtonsoft.Json.dll 可以直接操作json,这样更方便一些。
我们还需要写一个判断access_token是否过期如果过期更新XML文件的方法。
1 /// <summary> 2 /// 根据当前日期 判断Access_Token 是否超期 如果超期返回新的Access_Token 否则返回之前的Access_Token 3 /// </summary> 4 /// <param name="datetime"></param> 5 /// <returns></returns> 6 public static string IsExistAccess_Token() 7 { 8 9 string Token = string.Empty; 10 DateTime YouXRQ; 11 // 读取XML文件中的数据,并显示出来 ,注意文件路径 12 string filepath = Server.MapPath("XMLFile.xml"); 13 14 StreamReader str = new StreamReader(filepath, System.Text.Encoding.UTF8); 15 XmlDocument xml = new XmlDocument(); 16 xml.Load(str); 17 str.Close(); 18 str.Dispose(); 19 Token = xml.SelectSingleNode("xml").SelectSingleNode("Access_Token").InnerText; 20 YouXRQ = Convert.ToDateTime(xml.SelectSingleNode("xml").SelectSingleNode("Access_YouXRQ").InnerText); 21 22 if (DateTime.Now > YouXRQ) 23 { 24 DateTime _youxrq = DateTime.Now; 25 Access_token mode = GetAccess_token(); 26 xml.SelectSingleNode("xml").SelectSingleNode("Access_Token").InnerText = mode.access_token; 27 _youxrq = _youxrq.AddSeconds(int.Parse(mode.expires_in)); 28 xml.SelectSingleNode("xml").SelectSingleNode("Access_YouXRQ").InnerText = _youxrq.ToString(); 29 xml.Save(filepath); 30 Token = mode.access_token; 31 } 32 return Token; 33 }
1 /// <summary> 2 /// 根据当前日期 判断Access_Token 是否超期 如果超期返回新的Access_Token 否则返回之前的Access_Token 3 /// </summary> 4 /// <param name="datetime"></param> 5 /// <returns></returns> 6 public static string IsExistAccess_Token() 7 { 8 9 string Token = string.Empty; 10 DateTime YouXRQ; 11 // 读取XML文件中的数据,并显示出来 ,注意文件路径 12 string filepath = Server.MapPath("XMLFile.xml"); 13 14 StreamReader str = new StreamReader(filepath, System.Text.Encoding.UTF8); 15 XmlDocument xml = new XmlDocument(); 16 xml.Load(str); 17 str.Close(); 18 str.Dispose(); 19 Token = xml.SelectSingleNode("xml").SelectSingleNode("Access_Token").InnerText; 20 YouXRQ = Convert.ToDateTime(xml.SelectSingleNode("xml").SelectSingleNode("Access_YouXRQ").InnerText); 21 22 if (DateTime.Now > YouXRQ) 23 { 24 DateTime _youxrq = DateTime.Now; 25 Access_token mode = GetAccess_token(); 26 xml.SelectSingleNode("xml").SelectSingleNode("Access_Token").InnerText = mode.access_token; 27 _youxrq = _youxrq.AddSeconds(int.Parse(mode.expires_in)); 28 xml.SelectSingleNode("xml").SelectSingleNode("Access_YouXRQ").InnerText = _youxrq.ToString(); 29 xml.Save(filepath); 30 Token = mode.access_token; 31 } 32 return Token; 33 }
好了,完成了上面的工作,我只需要在使用到access_token的时调用如下就OK了,“客户再也不用担心token的过期”
string _access_token = IsExistAccess_Token();