**微信企业号开发,需要调用微信企业号的相关接口,则必须使用AccessToken,但AccessToken需要corpid,corpsecret两个参数调用相关接口才能获取。**
**而且每一个接口都有一定的次数限制,当然获取AccessToken的接口也有这个限制。每一个AccessToken的有效期为7200秒,也就是两个小时,在有效期内调用接口,则自动续期。因此建议在获取到AccessToken后,保存在在某一个地方,等到快过期时在重新获取。其实AccessToken有点类似于web程序中的session,这个有效期7200秒相当于session的有效期,调用接口,则自动续期,就相当于web程序中用户登陆后,和服务端有交互,session的有效期自然延长了。**
核心代码AccessTokenInfo类:
~~~
public class AccessTokenInfo
{
/// <summary>
/// access_token
/// </summary>
public string access_token { get; set; }
/// <summary>
/// 凭证有效时间,单位:秒
/// </summary>
public long expires_in { get; set; }
/// <summary>
/// 获取时间
/// </summary>
public DateTime GetTime { get; set; }
}
~~~
BLLAccessToken类
~~~
/// <summary>
/// 获取企业登陆access_token
/// </summary>
public static class BLLAccessToken
{
static AccessTokenInfo TokenInfo = null;
public static string GetAccessToken()
{
string AccessToken = "";
DateTime now=DateTime.Now;
if (TokenInfo == null) //首次获取
{
TokenInfo = UpDateAccessToken();
}
else
{
if (TokenInfo.GetTime.AddSeconds(TokenInfo.expires_in - 30) < now) //提前30秒重新获取
{
TokenInfo = UpDateAccessToken();
}
}
AccessToken = TokenInfo.access_token;
return AccessToken;
}
private static AccessTokenInfo UpDateAccessToken()
{
string CorpId = AppIdInfo.GetCorpId();//corpid
string Secret = AppIdInfo.GetSecret(); //corpsecret
AccessTokenInfo info = new AccessTokenInfo();
WebUtils ut = new WebUtils();
/// https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wxb7f1db8fd6aa9d68&corpsecret=aoxZ7D5-SgLRUbKY2fwQykW36RqxoIdNIn1pIiGy9iSdXgMHwQCzUsniQVAsBCTt
string urlFormat = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={0}&corpsecret={1}";
var url = string.Format(urlFormat, CorpId, Secret);
string temp = ut.DoGet(url);
try
{
AccessTokenInfo tempAccessTokenjson = Tools.JsonStringToObj<AccessTokenInfo>(temp);
info.access_token = tempAccessTokenjson.access_token;
info.expires_in = tempAccessTokenjson.expires_in;
info.GetTime = DateTime.Now;
}
catch(Exception ex)
{
LogInfo.Error("获取AccessToken异常", ex);
}
return info;
}
}
~~~
[微信企业号开发:常用的参数](http://blog.csdn.net/xuexiaodong009/article/details/46906867)
[微信企业号开发:corpsecret到底在哪块呢?](http://blog.csdn.net/xuexiaodong009/article/details/46895401)
[获取AccessToken官方文档](http://qydev.weixin.qq.com/wiki/index.php?title=%E4%B8%BB%E5%8A%A8%E8%B0%83%E7%94%A8)