//===================== 初始化静态数据 ==========================
#region
private static DateTime TokenExpTime = DateTime.Now.AddDays(-5); //Access_Token过期时间
private static string Access_Token = ""; //微信接口的通行证
#endregion
/// <summary>
/// //获取access_token ,但是会过期,时间为7200秒。经常用又会被限制,所以得使用静态存储
/// </summary>
/// <returns></returns>
public String Get_access_token()
#region
{
DateTime nowtime = DateTime.Now;
if (nowtime > TokenExpTime)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + this.CorpID + "&corpsecret=" + this.Secret);
webRequest.Method = "GET";
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
StreamReader sr = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8);
string json = sr.ReadToEnd();
JsonData data = JsonMapper.ToObject(json);
if (data["access_token"] == null)
{
log.WriteLog("获取access_token出错,错误信息为:" + json);
Access_Token = "";
}
Access_Token = data["access_token"].ToString();
TokenExpTime = nowtime.AddMinutes(90);//重新设置过期时间
}
return Access_Token;
}
#endregion