$openid = session('userinfo');
$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.C('WECHAT_APPID').'&secret='.C('WECHAT_APPSECRET').'';
$token = json_decode(request($url));
//对象转为数组
$token = object_to_array($token);
//写入文件
$TxtFileName = "access_token.txt";
//以读写方式打写指定文件,如果文件不存则创建
if( ($TxtRes=fopen ($TxtFileName,"w+")) === FALSE){
echo("创建可写文件:".$TxtFileName."失败");
exit();
}
echo ("创建可写文件".$TxtFileName."成功!</br>");
$StrConents = $token['access_token'];//要 写进文件的内容
if(!fwrite ($TxtRes,$StrConents)){ //将信息写入文件
echo ("尝试向文件".$TxtFileName."写入".$StrConents."失败!");
fclose($TxtRes);
exit();
}
echo ("尝试向文件".$TxtFileName."写入".$StrConents."成功!");
fclose ($TxtRes); //关闭指针
这是定时执行的php文件,通过appid和secret获得token并定时写入文件
这是curl的请求函数
function request($url,$https=true,$method='get',$data=null){
//1.初始化curl
$ch = curl_init($url);
//2.设置相关的参数
//字符串不直接输出,进行一个变量的存储
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// curl_setopt($ch, CURLOPT_HEADER, 1);
//判断是否为https请求
if($https === true){
//为了确保https请求能够请求成功
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
}
//判断是否为post请求
if($method == 'post'){
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
}
//3.发送请求
$str = curl_exec($ch);
// $hd = curl_getinfo($ch);
//4.关闭连接
curl_close($ch);
//返回请求到的结果
// return array('str'=>$str,'hd'=>$hd);
return $str;
}
这是对象转数组的函数
//对象转数组
function object_to_array($obj){
$_arr = is_object($obj) ? get_object_vars($obj) :$obj;
foreach ($_arr as $key=>$val){
$val = (is_array($val) || is_object($val)) ? $this->object_to_array($val):$val;
$arr[$key] = $val;
}
return $arr;
}