微信網頁授權獲取使用者基本資訊
阿新 • • 發佈:2019-01-05
如果使用者在微信客戶端中訪問第三方網頁,公眾號可以通過微信網頁授權機制,來獲取使用者基本資訊,但這種授權需要使用者手動同意,並且由於使用者同意過,所以無須關注,就可在授權後獲取該使用者的基本資訊。
網頁授權分為兩種,這兩種以scope來區別:
1、以snsapi_base為scope發起的網頁授權,是用來獲取進入頁面的使用者的openid的,並且是靜默授權並自動跳轉到回撥頁的。使用者感知的就是直接進入了回撥頁(往往是業務頁面)
2、以snsapi_userinfo為scope發起的網頁授權,是用來獲取使用者的基本資訊的。但這種授權需要使用者手動同意,並且由於使用者同意過,所以無須關注,就可在授權後獲取該使用者的基本資訊。
基本步驟如下:
1 第一步:準備發起的網頁授權的回撥頁URL
2 第二步:使用者同意授權,獲取code
3 第三步:通過code換取網頁授權access_token
4 第四步:重新整理access_token(如果需要)
2.Scope為snsapi_userinfo使用者授權
親測有效
網頁授權分為兩種,這兩種以scope來區別:
1、以snsapi_base為scope發起的網頁授權,是用來獲取進入頁面的使用者的openid的,並且是靜默授權並自動跳轉到回撥頁的。使用者感知的就是直接進入了回撥頁(往往是業務頁面)
2、以snsapi_userinfo為scope發起的網頁授權,是用來獲取使用者的基本資訊的。但這種授權需要使用者手動同意,並且由於使用者同意過,所以無須關注,就可在授權後獲取該使用者的基本資訊。
基本步驟如下:
1 第一步:準備發起的網頁授權的回撥頁URL
2 第二步:使用者同意授權,獲取code
3 第三步:通過code換取網頁授權access_token
4 第四步:重新整理access_token(如果需要)
5 第五步:拉取使用者資訊(需scope為 snsapi_userinfo)
好了,直接貼方法程式碼:
前期準備:
配置授權回撥域名
在微信公眾號請求使用者網頁授權之前,開發者需要先到公眾平臺官網中的開發者中心頁配置授權回撥域名。請注意,這裡填寫的是域名(是一個字串),而不是URL,因此請勿加 http:// 等協議頭
先構造好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; }
親測有效