第一步:引导用户打开如下链接 (详细介绍见OAuth2.0)
$url = urlencode('http://xxx.com/xxx');
$newurl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx9c807c944920c501&redirect_uri=$url&response_type=code&scope=snsapi_base&state=123#wechat_redirect";
注意这里需要去配置redirect_uri 回调URL的授权域名
如果用户同意授权,页面将跳转至 redirect_uri/?code=CODE&state=STATE。若用户禁止授权,则重定向后不会带上code参数,仅会带上state参数redirect_uri?state=STATE
点击修改
第二步:封装拉取用户信息类
public function Oauth($code='',$mode=0){
$appid = $this->AppId ; //公共账号 appid
$secret = $this->AppSecret ; //公众账号AppSecret
if($code=='') $code = $_REQUEST['code'] ; //接收参数
if(!$code) return false ;
$cul = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$secret.'&code='.$code.'&grant_type=authorization_code' ;
$cx = file_get_contents($cul) ;
$bx = json_decode($cx,true) ;
if($bx['errcode']){
//第一步 根据code获取refresh_token
$this->restat = 0 ;
$this->errmsg = $bx ; return ;
}
$rtoken = $bx['refresh_token'] ;
$rurl = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid='.$appid.'&grant_type=refresh_token&refresh_token='.$rtoken ;
$rr = file_get_contents($rurl) ;
$rr = json_decode($rr,true) ;
if($rr['errcode']){
//第二步 根据refresh_token获取的access_token和openid
$this->restat = 0 ;
$this->errmsg = $bx ; return ;
}
$acct = $rr['access_token'] ;
//file_put_contents('abc.txt', $acct);
$this->auth_access_token = $acct ; //存放认证的token
$openid = $rr['openid'] ;
if($mode == 0 ) return ;
//第三步拉取信息
$purl = "https://api.weixin.qq.com/sns/userinfo?access_token=$acct&openid=$openid&lang=zh_CN" ;
$xv = file_get_contents($purl) ;
//file_put_contents('xv.txt', $xv);
/*$xv返回数据格式
{"openid":"XXX","nickname":"Mini_Ren","sex":1,"language":"zh_CN","city":"郑州","province":"河南","country":"中国","headimgurl":"","privilege":[]}
*/
$xv = json_decode($xv,true) ;
if($xv['errcode']){
$this->restat = 0 ;
$this->errmsg = $bx ; return ;
}
$this->res = $xv ;
return $xv ; //带有用户信息数组
}
PS:微信Oauth认证类下载 Oauth认证下载