php微信公众号在access_token失效时重新请求并保存在本地文档

我们在调用微信公众号的api时基本会用到access_token,但是微信的access_token有效时间是7200s,并且每天请求的次数有限。

本文介绍将请求的access_token保存在本地文档并设置失效时限,与存在数据库中的流程一样。

文档welcome.txt中的值,token值与时间戳用&&符号进行分割

1、首先,我们要有一个请求token值的方法:

//curl获取token值
	    function curl_get_token(){
		$curl = curl_init();
	    //设置抓取的url
	    curl_setopt($curl, CURLOPT_URL, 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=yourappid&secret=yoursecret');
	    //设置头文件的信息作为数据流输出
	    curl_setopt($curl, CURLOPT_HEADER, 0);
	    //设置获取的信息以文件流的形式返回,而不是直接输出。
	    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
	    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true);  // 从证书中检查SSL加密算法是否存在
	    //执行命令
	    $data = curl_exec($curl);
	    //关闭URL请求
	    $http_code=curl_getinfo($curl,CURLINFO_HTTP_CODE); //我知道HTTPSTAT码哦~
	    curl_close($curl);
	    if($http_code==200){
	    	$data=json_decode($data,true);
	    	$reponse_result=array("token"=>$get_token);
	    	accept_token($reponse_result) ;//请求成功返回token
	    }else{
	    	//否则,抛出错误
	    	echo 'token请求出错,请刷新页面';
	    	exit;
	    }
	}

2、保存获取到的token值:

//storage写入token值
	function accept_token($get_data){
		$zero1=strtotime (date("y-m-d h:i:s")); //当前时间  
		$txt = $get_data['token']."&&".$zero1;//拼接字符串,将token与时间戳拼接在一起
   		$filename = "lin_storage/welcome.txt";
   		$file=fopen($filename,"w") or exit("Unable to open file!");
		fwrite($file, $txt);//将拼接好的字符串写入文档
              echo json_encode(array("token"=>$get_data['token']));//输出token值
             fclose($file);

3、判断token是否过期

//先从本地读取
		$zero1=strtotime (date("y-m-d h:i:s")); //当前时间  
		
   		$filename = "lin_storage/storage_token.txt";
   		$file=fopen($filename,"r+") or exit("Unable to open file!");
		while(!feof($file))
		{
		   	$str=explode('&&',fgets($file));
		   	if($zero1-$str[1]>7200){
		   		//如果超时,则重新请求
		   		curl_get_token();
		   	}else{
		   		//否则,输出保存的token值
                            echo json_encode(array("token"=>$str[0],"jsapi"=>$str[2]));
}}fclose($file);


以上为实现功能的全部代码,由于本人是php初学者,很多地方没有做处理,以后会继续完善。


猜你喜欢

转载自blog.csdn.net/weixin_41187842/article/details/80416236