创建access_token.json文件,将access_token 和 生成时间expires 保存在其中,
{"access_token":"xxxx","expires":1478799661}
function getToken(){ $appid=‘你的appid‘; $appsecret=‘你的appsecret‘; $file = file_get_contents("./access_token.json",true); $result = json_decode($file,true); echo time() - $result[‘expires‘].":"; if (time() > $result[‘expires‘]){ $data = array(); $data[‘access_token‘] = getNewToken($appid,$appsecret); $data[‘expires‘]=time()+7000; $jsonStr = json_encode($data); $fp = fopen("./access_token.json", "w"); fwrite($fp, $jsonStr); fclose($fp); return $data[‘access_token‘]; }else{ return $result[‘access_token‘]; } } function getNewToken($appid,$appsecret){ $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appsecret}"; $access_token_Arr = https_request($url); return $access_token_Arr[‘access_token‘]; } function https_request ($url){ $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); $out = curl_exec($ch); curl_close($ch); return json_decode($out,true); }
时间: 2024-10-10 08:14:41