开头要说明一下,微信公众号获取授权有俩种方式,一种是使用AppID和AppSecret获取的access_token,一种是OAuth2.0授权中产生的access_token,
第一种是用户关注以及回复消息的时候,均可以获得用户的OpenID,然后通过AppSecret即可获取access_token,另外一种就是本文中要说到的。
–>通过OAuth2.0方式弹出授权页面获得用户基本信息:
1.在公众号后台设置回调域名
2.拼接请求构造代码,跳转至微信的用户授权页:看代码注释
protected function checkValid(){ //检测用户是否已经授权登录 if(empty(session('user'))){ //没有的话跳转授权登录方法 return $this->wx_login(); } $this->UserId=session('user')['userid']; $this->UserOpenid=session('user')['useropenid']; $this->UserName=session('user')['username']; $this->UserHeadimg=session('user')['userheadpic']; } //微信用户授权登录 public function wx_login(){ $appid = "xxxxxxxxxx"; $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri=http://xxx.com/user/index/wx_callback.html&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect'; header("Location:".$url); }
代码中的xxx.com就是第一步中设置的回调域名
在微信的用户授权页,如果用户选择了“同意授权”,则微信重新回跳的到用户设置的回跳地址时,会附带上code参数。
3.在回跳url中,首先从请求中取得code,然后根据code进一步换取openid和access_token,然后就可以根据openid和access_token调用微信的相关接口查询用户信息了。
//微信回调地址 public function wx_callback(){ $appid = "xxxxxx"; $secret = "xxxxxxx"; $code = $_GET["code"]; $get_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$secret.'&code='.$code.'&grant_type=authorization_code'; //换取spenid和access_token $ch = curl_init(); curl_setopt($ch,CURLOPT_URL,$get_token_url); curl_setopt($ch,CURLOPT_HEADER,0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 ); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); $res = curl_exec($ch); curl_close($ch); $json_obj = json_decode($res,true); //这里做token缓存 //根据openid和access_token查询用户信息 $access_token = $json_obj['access_token']; $openid = $json_obj['openid']; //获取用户信息接口 $get_user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN'; $ch = curl_init(); curl_setopt($ch,CURLOPT_URL,$get_user_info_url); curl_setopt($ch,CURLOPT_HEADER,0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 ); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); $res = curl_exec($ch); curl_close($ch); //解析json $user_obj = json_decode($res,true); //获得用户信息后 判断是否记录过 $data['useropenid']=$user_obj['openid']; $data['username']=$user_obj['nickname']; $data['userheadpic']=$user_obj['headimgurl']; $user_data=db('user')->where('useropenid',$user_obj['openid'])->field('userid,useropenid,username,userheadpic')->find(); if($user_data){ //说明登录过 修改信息 存储session db('user')->where('userid',$user_data['userid'])->update($data); session('user',$user_data); }else{ //未登录 先登记信息 $data['usercreatetime']=time(); $id=db('user')->insertGetId($data); $data['userid']=$id; session('user',$data); } //跳转回首页 return $this->redirect('/user/index');
以上代码只是个基本例子,具体还待优化,仅供参考。