摘自:http://blog.csdn.net/hechurui/article/details/22398849
首先建立一个Access_token类
- /// <summary>
- ///Access_token 的摘要说明
- /// </summary>
- public class Access_token
- {
- public Access_token()
- {
- //
- //TODO: 在此处添加构造函数逻辑
- //
- }
- 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; }
- }
- }
用下面的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>
改造一下之前获得Access_token的方法,让他给Access_token实例赋值
- public static Access_token GetAccess_token()
- {
- string appid = 你的appid ;
- string secret = 你的secret;
- 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();
- //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;
- }
以上的方法用到了Json对象的处理,所以我把JsonHelper的代码一贴出来供大家参考,一下就是JsonHelper.cs的代码:
- using System;
- using System.IO;
- using System.Text;
- using System.Runtime.Serialization.Json;
- 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);
- }
- }
- }
我们还需要些一个判断access_token是否过期如果过期更新XML文件的方法。
- /// <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 = 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;
- }
好了,完成了上面的工作,我只需要在使用到access_token的时如下调用就OK了,“客户再也不用担心token的过期”。
string _access_token = IsExistAccess_Token();