微信开发,access_token,时间上没有过期,但已失效的问题

做微信开发的人都知道,access_token是公众号的全局唯一接口调用凭据,公众号调用各接口时都需使用access_token,我前几天做项目的时候,偶尔会有好多用户的信息获取不到,还有生成二维码报错,打印log才发现,access_token已经失效,但access_token的有效期是7200S也就是两个小时,但我的token失效的时候才30分钟左右,其他地方也没有单独调用获取token的接口,让人匪夷所思。

实在没有办法了,只能用一个迂回的招,就是调用微信一个没有次数限制的接口,把access_token传过去,接受返回值判断token的有效性。



首先是判断token的有效期 public string isExpires() { string sqlStr = "select ACCESS_TOKEN,ROW_ID,END_DATE from CD_TOKEN where DELETE_FLAG='N'"; //进行判断 string nowTag = getTimestamp();//当前时间的秒数 DataSet ds=dao.GetDataSet(sqlStr); if (ds.Tables[0].Rows.Count == 1) { if (Convert.ToInt32(ds.Tables[0].Rows[0]["END_DATE"].ToString()) > Convert.ToInt32(nowTag)) { return ds.Tables[0].Rows[0]["ACCESS_TOKEN"].ToString(); } else { return "false"; } } return "false"; }


然后重点来了,当token没有过期,但已经失效的情况怎么办呢。 public string GetNewAccess_token() { //判断access-token是否有效? string result = access_tokenDao.isExpires(); if (result == "false")//无效 { //刷新access_token string token = GetAccess_token().access_token;//获取最新的access_token //将新的token存入进数据库 string startDate = getTimestamp(); string endDate = (Convert.ToInt32(startDate) + 6000) + ""; Boolean t = access_tokenDao.refreshToken(token, startDate, endDate, "7200"); return token; } //调用第三个接口,验证token有效性 string url = "https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token="+result; string ip = new ApplicationUtil().DealGet(url); //Log.Info("err", s); IPtest iptest = new IPtest(); iptest = WXJSONHelper.ParseFromJson<iptest>(ip); string errorcode = iptest.errcode; if (errorcode != null) { string token = GetAccess_token().access_token;//获取最新的access_token //将新的token存入进数据库 string startDate = getTimestamp(); string endDate = (Convert.ToInt32(startDate) + 6000) + ""; Boolean t = access_tokenDao.refreshToken(token, startDate, endDate, "7200"); return token; } return result; } </iptest>



差不多就这样吧,第一次写。。。





你可能感兴趣的:(微信,access_token)