C#微信公众平台开发之access_token的获取存储与更新

一、什么是access_token?

    access_token是公众号的全局唯一票据,公众号调用各接口时都需使用access_token。正常情况下access_token有效期为7200秒,重复获取将导致上次获取的access_token失效。由于获取access_token的api调用次数非常有限,建议开发者全局存储与更新access_token,频繁刷新access_token会导致api调用受限,影响自身业务。

二、要解决的问题

1、如何获取access_token。

2、由于access_token的有效期为7200秒,即2小时,并且重复获取将导致上次获取的access_token失效,获取access_token的api调用次数非常有限,所以要解决如何全局存储与更新access_token。

3、多人请求access_token引起高并发

三、获取token

protected OAuth_Token Get_token()
 {
      appid = "appid";
      appsecret = "appsecret ";
       //获取微信回传的openid、access token
       string Str = GetJson("https://api.weixin.qq.com/cgi-bin/token?appid=" + appid + "&secret=" + appsecret + "&grant_type=client_credential");
       //微信回传的数据为Json格式,将Json格式转化成对象
       OAuth_Token Oauth_Token_Model = JsonHelper.ParseFromJson<OAuth_Token>(Str);
       return Oauth_Token_Model;
}

判断token是否过期

#region 验证Token是否过期
/// <summary>
/// 验证Token是否过期
/// </summary>
public static bool TokenExpired(string access_token)
{
 string jsonStr = HttpRequestUtil.RequestUrl(string.Format("https://api.weixin.qq.com/cgi-bin/menu/get?access_token={0}", access_token));
 if (Tools.GetJsonValue(jsonStr, "errcode") == "42001")
 {
  return true;
 }
 return false;
}
#endregion

注:每个人请求token会导致api调用受限,在项目中就遇到这个问题,把token保存到数据库并且只能限制几个人可以去获取token,这样次数少不会让api受限,只是那个人比较麻烦一点需要去刷新

猜你喜欢

转载自blog.csdn.net/LYfrighting/article/details/82798564