/**
* 获取服务号token
* @throws \Exception
* 自动检测token是否失效
*/
private function get_token(){
$data=WechatToken::findOne(['appid'=>self::appid]);
if ($data){
if (strtotime($data['end_time'])<time()){
$query=WechatToken::deleteAll(['appid'=>self::appid]);
there:
$appid=self::appid;
$appsecret=self::appsecret;
$url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appsecret}";
$wxmsg=json_decode(file_get_contents($url),true);
if (isset($wxmsg['errcode'])){
throw new \Exception('请求失败');
}
$model=new WechatToken();
$model->wechat_token=$wxmsg['access_token'];
$model->end_time=date("Y-m-d H:i:s",time()+$wxmsg['expires_in']);
$model->appid=self::appid;
$model->secret=self::appsecret;
if ($model->save()){
return $wxmsg['access_token'];
}
throw new \Exception('保存失败');
}
return $data['wechat_token'];
}
goto there;
}
其中我选择存放数据库,也可以选择存放缓存,我选用的是yii框架。
数据库格式如下: