5 第五步:拉取用戶信息(需scope為 snsapi_userinfo)
好了,直接貼方法代碼:前期準備:配置授權回調域名在微信公眾號請求用戶網頁授權之前,開發者需要先到公眾平臺官網中的開發者中心頁配置授權回調域名。請注意,這里填寫的是域名(是一個字符串),而不是URL,因此請勿加 http:// 等協議頭 先構造好php的curl網絡請求函數,方法見:PHP中的curl網絡請求1.Scope為snsapi_base基本授權
先構造好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;}親測有效

新聞熱點
疑難解答