def getAccessToken(self, stamp=None): token = None token_info = OauthAccessToken.query.filter( OauthAccessToken.expired_time >= getCurrentDate()).first() if token_info: token = token_info.access_token return token if stamp is None: config_mina = app.config['MINA_APP'] url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}" \ .format(config_mina['appid'], config_mina['appkey']) r = requests.get(url=url) if r.status_code != 200 or not r.text: return token data = json.loads(r.text) now = datetime.datetime.now() date = now + datetime.timedelta(seconds=data['expires_in'] - 200) model_token = OauthAccessToken() model_token.access_token = data['access_token'] model_token.expired_time = date.strftime("%Y-%m-%d %H:%M:%S") model_token.created_time = getCurrentDate() db.session.add(model_token) db.session.commit() return data['access_token'] else: config_mina = app.config['MINA_APP'][stamp] url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}" \ .format(config_mina['appid'], config_mina['appkey']) r = requests.get(url=url) if r.status_code != 200 or not r.text: return token data = json.loads(r.text) now = datetime.datetime.now() date = now + datetime.timedelta(seconds=data['expires_in'] - 200) model_token = OauthAccessToken() model_token.access_token = data['access_token'] model_token.expired_time = date.strftime("%Y-%m-%d %H:%M:%S") model_token.created_time = getCurrentDate() db.session.add(model_token) db.session.commit() return data['access_token']
def getAccessToken(self): token = None # 先查询是否有未过期的access_token token_info = OauthAccessToken.query.filter( OauthAccessToken.expired_time >= getCurrentDate()).first() if token_info: token = token_info.access_token return token config_mina = app.config['MINA_APP'] url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}'.format( config_mina['appid'], config_mina['appkey']) # get请求方式获取Access token r = requests.get(url=url) if r.status_code != 200 or not r.text: return token # 开发者文档此处的返回值是json格式数据 data = json.loads(r.text) app.logger.info(data) # 到期时间对应的时间戳(expires_in = 7200) now = datetime.datetime.now() date = now + datetime.timedelta(seconds=data['expires_in'] - 200) # 存取获取到的access_token到数据库 model_token = OauthAccessToken() model_token.access_token = data['access_token'] # 设置过期时间 model_token.expired_time = date.strftime("%Y-%m-%d %H:%M:%S") model_token.created_time = getCurrentDate() db.session.add(model_token) db.session.commit() return data['access_token']