PHP获取access_token
时间:2021-07-01 10:21:17
帮助过:21人阅读
*
* 获取accesstoken
*
* @param int $id
* @return \think\Response
*/
public function AccessToken(
$appid)
{
//获取url
$file =
$this->
accesstoken_url;
if(!
file_exists(
$file)){
$token =
$this->get_accesstoken(
$appid);
}else{
$fileInfo =
explode(",",
file_get_contents(
$file));
if(!
empty(
trim(
$fileInfo[0])) &&
$fileInfo[1] >=
time()){
$token =
$fileInfo[0
];
}else{
$token =
$this->get_accesstoken(
$appid);
}
}
return $token;
}
/**
* 获取token
*/
private function get_accesstoken(
$appid)
{
$data =
[
"grant_type"=>"client_credential",
"appid"=>
$appid,
"secret"=>
$this->
AppSecret
];
$url =
$this->
url_token;
$tokeninfo =
$this->jsonDecode(https_request(
$url,
$data),"access_token"
);
if(
$tokeninfo){
$text =
$tokeninfo.",".(
time()+7000
);
//写入文件中
$file =
$this->
accesstoken_url;
if(!
file_exists(
$file)){
fopen(
$file,"wb"
);
}
//把值存入文件中
$myfile =
fopen(
$file,"w"
);
fwrite(
$myfile,
$text);
//写入文件
fclose(
$myfile);
//关闭文件
}
return $tokeninfo;
}
/**
* json数据处理
*/
private function jsonDecode(
$data,
$key)
{
$new_data = json_decode(
$data,
true);
if(
array_key_exists(
$key,
$new_data)){
return $new_data[
$key];
}
return $data;
}
PHP获取access_token
标签:get res amp app grant vat write pen code