微信开发,access_token定时获取

		$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;
 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值