微信获取access_token并且做时间缓存限制

                      
                            <

微信获取access_token并且写到缓存,两个小时之后重新获取,避免接口重复刷新,浪费接口资源

/***************************

    方法名称:获取access_token

    编写者:July

    编写日期:2016-9-21

    参数说明:

    $appID

    $appsecret

    返回值:返回有效access_token

    方法说明:判断access_token是否已经到了两个小时,如果到了,那么就跟新token

    ***************************/

    public function get_access_token($appID="",$appsecret=""){

        $url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appID."&secret=".$appsecret;

        

        if(!is_readable("./wechattoken")){  

            is_file("./wechattoken") or mkdir("./wechattoken",0777,true);  

        } 

        if(!is_file("./wechattoken/access_token.php")){

            file_put_contents("./wechattoken/access_token.php","");

        }


        $tokeninfo=json_decode(file_get_contents("./wechattoken/access_token.php"));

        if(!$tokeninfo->access_token || !$tokeninfo->expires_in || ($tokeninfo->expires_in-time())<1){

            $curl = curl_init();

            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

            curl_setopt($curl, CURLOPT_TIMEOUT, 500);//超时

            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);

            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true);

            curl_setopt($curl, CURLOPT_URL, $url);

            curl_setopt($curl, CURLOPT_HEADER, false);//协议头

            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);//这个是重点。

            $data = curl_exec($curl);

            curl_close($curl);

            $tokeninfo=json_decode($data);

            $putdata=array(

                'access_token'=>$tokeninfo->access_token,

                'expires_in'=>time()+$tokeninfo->expires_in

            );


            file_put_contents("./wechattoken/access_token.php",json_encode($putdata));            

            return $tokeninfo->access_token;

        }else{

            return $tokeninfo->access_token;

        }

    }


>