验证中...
token过期前280秒回进行刷新,进入token的平滑过渡期
Raw Copy
public function curl_get($url)
{
$info = curl_init();
curl_setopt($info, CURLOPT_RETURNTRANSFER, true);
curl_setopt($info, CURLOPT_HEADER, 0);
curl_setopt($info, CURLOPT_NOBODY, 0);
curl_setopt($info, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($info, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($info, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($info, CURLOPT_URL, $url);
$output = curl_exec($info);
curl_close($info);
return $output;
}
//————————————————
//版权声明:本文为CSDN博主「灼灼桃花夭」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
//原文链接:https://blog.csdn.net/qq_39835505/article/details/85230199
/**
* 获取accesstoken 从文件中或刷新
*/
protected function wxAccessToken1()
{
$fileName = 'ookkcc.txt';
if (file_exists($fileName)) {
// $result = file_get_contents($fileName);
$file = fopen($fileName, 'r');
$result = fread($file, 1024);
fclose($file);
if ($result == '') { // 文件内容为空的处理
$this->reqAccessToken($fileName);
}
// 处理文件内容不为空 ,判断token 的过期时间
$tokenJson = \GuzzleHttp\json_decode($result);
$refresh = $tokenJson->refresh;
if (time() > $refresh) {
Log::log(time() . '微信accesstoken过期');
$this->reqAccessToken($fileName);
}
} else { // 不存在文件的处理
$this->reqAccessToken($fileName);
}
return $result;
}
private function reqAccessToken($fileName)
{
Log::log(time() . '微信accesstoken-新建');
$tiqian = 280;// 提前不到五分钟 刷新token
$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $this->appid . '&secret=' . $this->appsecret;
$result = $this->curl_get($url);
$file = fopen($fileName, 'w+') or die("Unable to open file!");
//写入真实刷新token的时间
$tokenJson = \GuzzleHttp\json_decode($result);
$expire = $tokenJson->expires_in;
$myExpire = $expire - $tiqian;
$refreshTime = time() + $myExpire;
$tokenJson->refresh = $refreshTime;
$tokenEncode = \GuzzleHttp\json_encode($tokenJson);
$txt = $tokenEncode;
fwrite($file, $txt);
//关闭文件
fclose($file);
$this->wxAccessToken1();
}

Comment list( 0 )

Sign in for post a comment

Help Search