/*判断token文件是否存在*/
if (file_exists("access_token.json"))
{
$result = json_decode(file_get_contents("access_token.json"),true);
//file_get_content()读取文件可以使用
//$fp = fopen($filename, 'r')
//$content = fread($fp, filesize($filename));
// fclose($fp);
$token = $result['token'];
}else{
$result['token'] = '';
$result['expires_in'] = '';
}
/*判断token是否过期*/
if( $result['token'] == '' || $result['expires_in'] < time() ){
$str = $this->AppID.$this->AppSecret.$this->SignKey;
$Sign= MD5($str);/*签名*/
$data = array(
'AppID' => $this->AppID,
'AppSecret' => $this->AppSecret,
'Sign' =>$Sign,
);
$token_json = $this->http_request($this->tokeurl,$data);
$token = json_decode($token_json,true)['token'];
$reflesh = [];
$reflesh['expires_in'] = time()+3600;
$reflesh['token'] = $token;
$fp = fopen("access_token.json", "w");
fwrite($fp, json_encode($reflesh));
fclose($fp);
}
return $this->token =$token;
2
/**
* 写入文件
* @param string $filename 完整文件名称(包括路径和后缀)
* @param string $writetext 要写入的字符串
* @param string $openmod
*
* return bool
*/
function write_file($filename, $text, $openmod='w')
{
if(@$fp = fopen($filename, $openmod))
{
flock($fp, 2);
fwrite($fp, $text);
fclose($fp);
return true;
}
else
{
return false;
}
}
function read_file($filename)
{
$content = '';
if(function_exists('file_get_contents'))
{
@$content = file_get_contents($filename);
}
else
{
if(@$fp = fopen($filename, 'r'))
{
@$content = fread($fp, filesize($filename));
@fclose($fp);
}
}
return $content;
}
var $token_file = ROOT_PATH . 'data/zmyf_token.txt';
public function __construct(){
//读取本地保存的token
if (file_exists($this->token_file))
{
$token_str = read_file($this->token_file);
$token_arr = json_decode($token_str,true,512,JSON_BIGINT_AS_STRING);
}
//判断token是否过期
if ($token_arr['token'] == '' || $token_arr['expires_time'] < gmtime()) {
$data = array(
'grant_type' => $this->grant_type,
'client_id' => $this->client_id,
'client_secret' => $this->client_secret,
);
$url = $this->apiurl . 'v1/auth/token';
$token_json = $this->http_request($url, $data);
$token_arr = json_decode($token_json, true);
$token_arr['expires_time'] = gmtime() + $token_arr['expires_at'];
$token_str = json_encode($token_arr,JSON_UNESCAPED_SLASHES);
write_file($this->token_file, $token_str);
}
return $this->token = $token_arr['data']['token'];
}