由于本项目中使用自定义菜单接口、获取用户信息接口、用户分组接口、消息发送接口等,都需要传入一个相同的参数access_token,其有效期 是7200秒(两小时),在有效期内可以使用,一旦access_token过期,需要重新通过调用微信接口获取。目前微信接口上面获取 access_token每日限额为2000次,如果Oauth2.0授权、发送主动消息、获取用户信息、群发信息之前都去获取,必然会达到该接口的频率 限制,因此需要把获取到的access_token存储起来,然后设置有效期,在有效期过期后再去获取,以保证access_token实时的有效性。详 细代码如下:
a. 新建xml文件,命名为XMLToken.xml。
<?xml version="1.0" encoding="utf-8"?>
<xml>
<AccessToken></AccessToken>
<AccessExpires></AccessExpires>
</xml>
b. AccessToken实体结构如下:
public class AccessToken
{
public stringaccess_token { get; set;}
public int expires_in{ get; set; }
}
c. 获取AccessToken()和getJson()方法如下:
public AccessTokenGetAccessToken(string CorpId, string Secret)
{
string str_accessToken ="https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="+ CorpId +"&corpsecret=" +Secret;
string accessToken = GetJson(str_accessToken);
AccessToken getAccessToken =js.Deserialize<AccessToken>(accessToken);
return getAccessToken;
}
public stringGetJson(string url)
{
WebClient wc = newWebClient();
wc.Credentials = CredentialCache.DefaultCredentials;
wc.Encoding = Encoding.UTF8;
string returnText = wc.DownloadString(url);
if (returnText.Contains("errcode"))
{
//可能出错
}
return returnText;
}
d. 校验AccessToken是否过期方法 GetExistAccessToken()如下:
public stringGetExistAccessToken()
{
string filepath = System.Web.HttpContext.Current.Server.MapPath("XMLToken.xml");
StreamReader str = newStreamReader(filepath ,System.Text.Encoding.UTF8);
XmlDocument xml = newXmlDocument();
xml.Load(str);
str.Close();
str.Dispose();
string token = xml.SelectSingleNode("xml").SelectSingleNode("AccessToken").InnerText;
string time = xml.SelectSingleNode("xml").SelectSingleNode("AccessExpires").InnerText;
if (string.IsNullOrEmpty(token)||string.IsNullOrEmpty(time))
{
AccessToken getAccessToken =GetAccessToken(str_CorpId, str_Secret);
xml.SelectSingleNode("xml").SelectSingleNode("AccessToken").InnerText =getAccessToken.access_token;
DateTime _accessExpires =DateTime.Now.AddSeconds(getAccessToken.expires_in);
xml.SelectSingleNode("xml").SelectSingleNode("AccessExpires").InnerText =_accessExpires.ToString();
xml.Save(filepath);
token = getAccessToken.access_token;
}
else if (!string.IsNullOrEmpty(token) || !string.IsNullOrEmpty(time))
{
DateTime AccessExpires =Convert.ToDateTime(time);
if (DateTime.Now> AccessExpires)
{
AccessToken getAccessToken =GetAccessToken(str_CorpId, str_Secret);
xml.SelectSingleNode("xml").SelectSingleNode("AccessToken").InnerText =getAccessToken.access_token;
DateTime _accessExpires =DateTime.Now.AddSeconds(getAccessToken.expires_in);
xml.SelectSingleNode("xml").SelectSingleNode("AccessExpires").InnerText =_accessExpires.ToString();
xml.Save(filepath);
token = getAccessToken.access_token;
}
}
return token;
}