1 //PHP创建access_token.json文件,将access_token 和 生成时间expires 保存在其中, 2 //{"access_token":"xxxx","expires":1478799661} 3 function getToken(){ 4 $appid=‘*‘; 5 $appsecret=‘**‘; 6 $file = file_get_contents("./access_token.json",true); 7 $result = json_decode($file,true); 8 echo $time(); 9 if (time() > $result[‘expires‘]){ 10 $data = array(); 11 $data[‘access_token‘] = getNewToken($appid,$appsecret); 12 $data[‘expires‘]=time()+7000; 13 $jsonStr = json_encode($data); 14 $fp = fopen("./access_token.json", "w"); 15 fwrite($fp, $jsonStr); 16 fclose($fp); 17 return $data[‘access_token‘]; 18 }else{ 19 return $result[‘access_token‘]; 20 } 21 } 22 function getNewToken($appid,$appsecret){ 23 $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appsecret}"; 24 $access_token_Arr = https_request($url); 25 return $access_token_Arr[‘access_token‘]; 26 } 27 function https_request ($url){ 28 $ch = curl_init(); 29 curl_setopt($ch, CURLOPT_URL, $url); 30 curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); 31 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 32 $out = curl_exec($ch); 33 curl_close($ch); 34 return json_decode($out,true); 35 } 36 echo getToken();
时间: 2024-10-13 16:13:16