public function getaccss_token(){ $table = 'Access_token'; $useraccess_token = Db::table('Access_token')->select(); $appid = "你的appid"; $appsecret = "你的appsecret"; $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret"; //判断是不是第一次获取access_token if(!count($useraccess_token)){ $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $output = curl_exec($ch); curl_close($ch); $jsoninfo = json_decode($output, true); $access_token = $jsoninfo["access_token"]; $data=['access_token'=>$access_token,'expires_time'=>($jsoninfo['expires_in']+time()-200)]; Db::table($table)->insert($data); return $access_token; }else if($useraccess_token[0]['expires_time']$access_token,'expires_time'=>($jsoninfo['expires_in']+time()-200)]; Db::table($table)->where('expires_time',$useraccess_token[0]['expires_time'])->update($data);//更新数据库; return $access_token; }else{ $access_token = $useraccess_token[0]['access_token']; return $access_token; } }
通过curl函数来截获微信发送过来的消息,由于获取到的access_token的有效时间只有7200s也就是两个小时,所以要每次用户对公众号进项操作就要检测一下是不是过期了,如果过期了就要重新获取,如上图的几个if判断就是来判断的,我是将access_token和时间都存到数据库了,这样每次就可以拿出来检测,当然你也可以从缓存调用或者放到文件里从文件里调用;
获取到access_token后,再通过access_token和openid来获取用户个人信息如下图函数:
public function userinfo($openid){ $access_token = $this->getaccss_token(); //获取用户信息地址 $urlid = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN'; $curl = curl_init(); // 启动一个CURL会话 curl_setopt($curl, CURLOPT_URL, $urlid); 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加密算法是否存在 $tmpInfo = curl_exec($curl); //返回api的json对象 //关闭URL请求 curl_close($curl); $userinfo = json_decode($tmpInfo,true); return $userinfo; }
也是一样的通过curl函数相关操作来截获信息,转换格式就可以了,这个最后的userinfo就是用户的个人信息数组了,你只需要调用就可以了;
以上就是通过access_token来获取用户个人信息的操作~!