公用获取token,并保存到文件中,而且距离快过期5分钟会自动获取

公用获取token,并保存到文件中,而且距离快过期5分钟会自动获取

很实用的代码

//生成accesstoken
function getAccessToken()
{
    $appid = APPID;
    $appsecret = APPSECRET;

    //存access_token文件
    $logfilename = dirname(dirname(__FILE__)).'/public/accessToken/accesstoken.txt';

    //如果不存在则创建一份文件
    if(!file_exists($logfilename)){
        file_put_contents($logfilename,'');
        //system("chmod 777 /data/wwwroot/dxssc/public/accessToken/accesstoken.txt");
    }

    //读取内容
    $tokeninfo = file_get_contents($logfilename);

    //文件里面有内容
    if(!empty($tokeninfo)){

    	//转换成数组形式
        $tokeninfo = json_decode($tokeninfo,true);
        if($tokeninfo['endtime']-time()<300){
        	//预留5分钟的网络延迟时间,过期的话重新获取access_token

        	//清空文档里面的内容
        	file_put_contents($logfilename, '');
			$token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid.'&secret='.$appsecret;

			//获取文件内容或获取网络请求的内容
			$result = http_Msg($token_url,"GET");
			$fresult = $result;

			//access_token过期时间点
			$fresult["endtime"] = $result['expires_in']+time();
			$fresult = json_encode($fresult);

			//将access_token数据存在文件中
			file_put_contents($logfilename, $fresult);
        }else{
        	//没有过期直接返回存储在文件中的access_token
        	$result = $tokeninfo;
        }
    }else{

    	//第一次获取access_token
        $token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid.'&secret='.$appsecret;

        //获取文件内容或获取网络请求的内容
        $result = http_Msg($token_url,"GET");
        $fresult = $result;
        $fresult["endtime"] = $result['expires_in']+time();
        $fresult = json_encode($fresult);

        //写入文件
        file_put_contents($logfilename, $fresult);
    }
    return $result;
}


function http_Msg($url,$method="GET",$data=array())
{
	$ch = curl_init();
	$wx_data = json_encode($data);

	//打开
	$ch = curl_init();

	//请求方法为POST的时候
	if($method == "POST"){
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $wx_data);
	}
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
	$response  = curl_exec($ch);
	//关闭
	curl_close($ch);
	$result = json_decode($response,true);
	return $result;
}

  

posted @ 2018-04-21 14:43  瑛雄  阅读(706)  评论(0编辑  收藏  举报