5 第五步:拉取用户信息(需scope为 snsapi_userinfo)
好了,直接贴方法代码:前期准备:配置授权回调域名在微信公众号请求用户网页授权之前,开发者需要先到公众平台官网中的开发者中心页配置授权回调域名。请注意,这里填写的是域名(是一个字符串),而不是URL,因此请勿加 http:// 等协议头先构造好php的curl网络请求函数,方法见:PHP中的curl网络请求1.Scope为snsapi_base基本授权
public function _baseAuth($redirect_url){ //1.准备scope为snsapi_base网页授权页面 $baseurl = urlencode($redirect_url); $snsapi_base_url = 'https://open.weixin.QQ.com/connect/oauth2/authorize?appid='.$this->_appid.'&redirect_uri='.$baseurl.'&response_type=code&scope=snsapi_base&state=YQJ#wechat_redirect'; //2.静默授权,获取code //页面跳转至redirect_uri/?code=CODE&state=STATE $code = $_GET['code']; if( !isset($code) ){ header('Location:'.$snsapi_base_url); } //3.通过code换取网页授权access_token和openID $curl = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$this->_appid.'&secret='.$this->_appsecret.'&code='.$code.'&grant_type=authorization_code'; $content = $this->_request($curl); $result = json_decode($content); return $result;}2.Scope为snsapi_userinfo用户授权
public function _userInfoAuth($redirect_url){ //1.准备scope为snsapi_userInfo网页授权页面 $redirecturl = urlencode($redirect_url); $snsapi_userInfo_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$this->_appid.'&redirect_uri='.$redirecturl.'&response_type=code&scope=snsapi_userinfo&state=YQJ#wechat_redirect'; //2.用户手动同意授权,同意之后,获取code //页面跳转至redirect_uri/?code=CODE&state=STATE $code = $_GET['code']; if( !isset($code) ){ header('Location:'.$snsapi_userInfo_url); } //3.通过code换取网页授权access_token $curl = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$this->_appid.'&secret='.$this->_appsecret.'&code='.$code.'&grant_type=authorization_code'; $content = $this->_request($curl); $result = json_decode($content); //4.通过access_token和openid拉取用户信息 $webAccess_token = $result->access_token; $openid = $result->openid; $userInfourl = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$webAccess_token.'&openid='.$openid.'&lang=zh_CN '; $recontent = $this->_request($userInfourl); $userInfo = json_decode($recontent,true); return $userInfo;}亲测有效
新闻热点
疑难解答