微信開發(fā)之網(wǎng)頁授權(quán)獲取用戶信息(二)
在公眾號的配置過程中,許多開發(fā)者會在菜單中加入HTML5頁面,有時在頁面內(nèi)需要訪問頁面的用戶信息,此時就需要網(wǎng)頁授權(quán)獲取用戶基本信息
腳本之家提醒大家:本文介紹講述的內(nèi)容是基于yii2.0框架
1、設(shè)置授權(quán)回調(diào)域名:開發(fā) ---> 接口權(quán)限
找到“網(wǎng)頁授權(quán)獲取用戶基本信息”,點擊后面對應(yīng)的“修改”,在彈框響應(yīng)位置填寫授權(quán)回調(diào)域名即可,此處的域名不需要加http:// (關(guān)于網(wǎng)頁授權(quán)回調(diào)域名的說明詳情可參考公眾平臺開發(fā)者文檔)
2、獲取授權(quán)
關(guān)于OAuth2.0博主參考的是方倍工作室的博文http://www.cnblogs.com/txw1958/p/weixin71-oauth20.html(PS:方倍是一個微信開發(fā)大神,其中的微信開發(fā)內(nèi)容還是比較詳細(xì)的,推薦參考),其中詳細(xì)剖析了微信官方文檔的相關(guān)內(nèi)容,也提供了獲取授權(quán)的更詳細(xì)思路和方案。
實際上,獲取用戶信息的關(guān)鍵在于獲取用戶的openid。博主想要實現(xiàn)用戶點擊公眾號菜單打開頁面即可自動授權(quán),從而針對該用戶進行數(shù)據(jù)庫操作,于是有下面兩種方式:
(1)利用自定義菜單請求授權(quán)頁面
自定義菜單后面會單獨寫一篇博文,在這里先簡述一下通過自定義菜單進行授權(quán),該方法需要高級接口權(quán)限,且局限于關(guān)注公眾號的用戶直接從菜單進入頁面。
$menu = '{ "button":[ { "type": "view", "name": "商城", "url": "https://open.weixin.qq.com/connect/oauth/authorize?appid=xxx&redirect_uri=http://tx.heivr.com/index.php&response_type=code&scope=snsapi_base&state=#wechat_redirect" }, { "name":"快遞服務(wù)", "sub_button":[ { "type":"click", "name":"發(fā)快遞", "key":"express" }, { "type":"click", "name":"快遞查詢", "key":"ww" } ] }, ] }';
需要授權(quán)的view直接在url處填寫微信提供的授權(quán)請求地址,其中:
•appid:填寫微信公眾平臺基本配置中的AppID;
•redirect_uri:填寫授權(quán)完成后跳轉(zhuǎn)的頁面地址,即自己的html5頁面;
•state:跳轉(zhuǎn)至回調(diào)頁面所帶參數(shù);
•response_type:網(wǎng)頁授權(quán)的兩種scope,微信官方文檔中說明如下:
1、以snsapi_base為scope發(fā)起的網(wǎng)頁授權(quán),是用來獲取進入頁面的用戶的openid的,并且是靜默授權(quán)并自動跳轉(zhuǎn)到回調(diào)頁的。用戶感知的就是直接進入了回調(diào)頁(往往是業(yè)務(wù)頁面)
2、以snsapi_userinfo為scope發(fā)起的網(wǎng)頁授權(quán),是用來獲取用戶的基本信息的。但這種授權(quán)需要用戶手動同意,并且由于用戶同意過,所以無須關(guān)注,就可在授權(quán)后獲取該用戶的基本信息。
按照此方法點擊“商城”即可接收到返回的openid,繼而進行下一步用戶信息的獲取?!?/p>
(2)利用JS自動請求授權(quán)頁面
這個方法相對而言比較笨拙,步驟略復(fù)雜,但目前能解決需求還沒有研究簡化方法,且由于頁面的跳轉(zhuǎn)多數(shù)情況下訪問頁面的時間會增加,但相比于前一個方法,該方法可以獲取到非關(guān)注用戶的基本信息。有些程序可能涉及到頁面分享,程序沒有強制關(guān)注但其他用戶通過分享直接進入頁面也需要記錄用戶信息,此時可以考慮該方法。(微信開發(fā)相關(guān)的代碼博主封裝成工具類調(diào)用,這里先貼用到的部分,以后整理完成會全部貼出來并附下載鏈接)
該方法的思路為:js請求鏈接獲取code ---> 利用code換取openid ---> 得到用戶基本信息
a. 編輯配置
為了方便把用到的一些微信參數(shù)單獨寫入一個類,方便修改添加及調(diào)用
<?php namespace common\tools\wechat; /** * 微信請求相關(guān)配置類庫 */ class ConfigTool { /** * 微信配置參數(shù) * @return array 配置參數(shù) */ public function setConfig() { // 用于驗證微信接口配置信息的Token,可以任意填寫 $config['token'] = '自己的token'; // appID $config['appid'] = '自己的appid'; // appSecret $config['secret'] = '自己的secret'; // 回調(diào)鏈接地址 $config['redirect_uri'] = 'http://tx.heivr.com/index.php?'; // 是否以 HTTPS 安全協(xié)議訪問接口 $config['https_request'] = false; // 授權(quán)作用域,snsapi_base (不彈出授權(quán)頁面,直接跳轉(zhuǎn),只能獲取用戶openid), // snsapi_userinfo (彈出授權(quán)頁面,可通過openid拿到昵稱、性別、所在地。并且, // 即使在未關(guān)注的情況下,只要用戶授權(quán),也能獲取其信息) $config['scope'] = 'snsapi_userinfo'; // 語言 $config['lang'] = 'zh_CN'; // zh_CN 簡體,zh_TW 繁體,en 英語 // 微信公眾賬戶授權(quán)地址 $config['mp_authorize_url'] = 'https://api.weixin.qq.com/cgi-bin/token'; // 微信公眾賬戶js臨時票據(jù)地址 $config['jsapi_ticket_url'] = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket'; // 授權(quán)地址 $config['authorize_url'] = 'https://open.weixin.qq.com/connect/oauth/authorize'; // 獲取access token 的地址 $config['access_token_url'] = 'https://api.weixin.qq.com/sns/oauth/access_token'; // 刷新 token 的地址 $config['refresh_token_url'] = 'https://api.weixin.qq.com/sns/oauth/refresh_token'; // 獲取用戶信息地址 $config['userinfo_url'] = 'https://api.weixin.qq.com/sns/userinfo'; // 驗證access token $config['valid_token_url'] = 'https://api.weixin.qq.com/sns/auth'; // 上傳臨時素材地址 $config['media_temp_upload_url'] = 'https://api.weixin.qq.com/cgi-bin/media/upload?'; // 上傳永久素材地址 $config['media_forever_upload_url'] = 'https://api.weixin.qq.com/cgi-bin/material/add_material?'; return $config; } }
b. https請求工具
<?php namespace common\tools; /** * https請求相關(guān)類庫 */ class HttpsTool { const TIMEOUT = ; // 設(shè)置超時時間 private $ch; // curl對象 /** * 發(fā)送curl請求,并獲取請求結(jié)果 * @param string 請求地址 * @param array 如果是post請求則需要傳入請求參數(shù) * @param string 請求方法,get 或者 post, 默認(rèn)為get * @param bool 是否以https協(xié)議請求 */ public function send_request($requests, $params = null, $method = 'get', $https = true) { // 以get方式提交 if ($method == 'get') { if($params){ $request = $requests . $this->create_url($params); }else{ $request = $requests; } }else{ $request = $requests; } $this->ch = curl_init($request); curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, );// 設(shè)置不顯示結(jié)果,儲存入變量 curl_setopt($this->ch, CURLOPT_TIMEOUT, self::TIMEOUT); // 設(shè)置超時限制防止死循環(huán) // 判斷是否以https方式訪問 if ($https) { curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, ); // 對認(rèn)證證書來源的檢查 curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, ); // 從證書中檢查SSL加密算法是否存在 } if ($method == 'post') { // 以post方式提交 //curl_setopt($this->ch, CURLOPT_SAFE_UPLOAD, false); //php .文件上傳必加內(nèi)容,.不需要 curl_setopt($this->ch, CURLOPT_POST, ); // 發(fā)送一個常規(guī)的Post請求 curl_setopt($this->ch, CURLOPT_POSTFIELDS, $params); // Post提交的數(shù)據(jù)包 curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, ); } $tmpInfo = curl_exec($this->ch); // 執(zhí)行操作 if (curl_errno($this->ch)) { echo 'Errno:'.curl_error($this->ch);//捕抓異常 } curl_close($this->ch); // 關(guān)閉CURL會話 //var_dump($tmpInfo);exit; return $tmpInfo; // 返回數(shù)據(jù) } /** * 生成url */ public function create_url($data) { $temp = '?'; foreach ($data as $key => $item) { $temp = $temp . $key . '=' . $item . '&'; } return substr($temp, , -); } }
關(guān)于curl_setopt($this->ch, CURLOPT_SAFE_UPLOAD, false)會在微信圖片資源上傳博文中詳細(xì)講述它出現(xiàn)的心酸史,這里暫時用不到,不做解釋
c. 授權(quán)基類
<?php namespace common\tools\wechat; use common\tools\wechat\ConfigTool; use common\tools\HttpsTool; /** * Weixin_oauth 類庫 */ class OauthTool { public $conf; public function __construct(){ $re = new ConfigTool; $this->conf = $re->setConfig(); } /** * 生成用戶授權(quán)的地址 * @param string 自定義需要保持的信息 * @param sting 請求的路由 * @param bool 是否是通過公眾平臺方式認(rèn)真 */ public function authorize_addr($route, $state='', $mp=false) { if ($mp) { $data = [ 'appid' => $this->conf['appid'], 'secret' => $this->conf['token'], 'grant_type' => 'client_credential' ]; $url = $this->conf['mp_authorize_url']; } else { $data = [ 'appid' => $this->conf['appid'], //公眾號唯一標(biāo)識 'redirect_uri' => urlencode($this->conf['redirect_uri'] . $route), //授權(quán)后重定向的回調(diào)鏈接地址 'response_type' => 'code', //返回類型,此處填寫code 'scope'=>$this->conf['scope'], //應(yīng)用授權(quán)作用域 'state'=>$state, //重定向后帶上state參數(shù),開發(fā)者可以填寫任意參數(shù) '#wechat_redirect'=>'' //直接在微信打開鏈接,可不填,做頁面重定向時必須帶此參數(shù) ]; $url = $this->conf['authorize_url']; } $send = new HttpsTool; //var_dump($url . $send->create_url($data));exit; return $url . $send->create_url($data); } /** * 獲取 access token * @param string 用于換取access token的code,微信提供 */ public function access_token($code) { $data = [ 'appid' => $this->conf['appid'], 'secret' => $this->conf['secret'], 'code' => $code, 'grant_type' => 'authorization_code' ]; // 生成授權(quán)url $url = $this->conf['access_token_url']; $send = new HttpsTool; return $send->send_request($url, $data); } /** * 獲取用戶信息 * @param string access token * @param string 用戶的open id */ public function userinfo($token, $openid) { $data = [ 'access_token' => $token, 'openid' => $openid, 'lang' => $this->conf['lang'] ]; // 生成授權(quán)url $url = $this->conf['userinfo_url']; $send = new HttpsTool; return $send->send_request($url, $data); } }
d. 授權(quán)基類調(diào)用及用戶數(shù)據(jù)處理(在控制器調(diào)用前,先對用戶數(shù)據(jù)存入或更新)
<?php namespace wechat\controllers\classes; use common\tools\wechat\OauthTool; use common\models\User; use common\tools\EmojiTool; /** * 微信用戶基本信息獲取 */ class UserinfoClass { /** * 用戶授權(quán)并獲取code * @return string 用戶code */ public function getCode($route, $state){ $re = new OauthTool; $request = $re->authorize_addr($route, $state); $code = isset($_GET['code']) ? $_GET['code'] : ''; return [$request,$code]; } /** * 獲取用戶信息并寫入數(shù)據(jù)庫(之后加參數(shù)傳給code) */ public function info($code) { $re = new OauthTool; //獲取access token $access = $re->access_token($code); $token = json_decode($access,true); //header("Content-type: text/html; charset=gbk"); //獲取用戶信息 if(count($token) != ) { $response = $re->userinfo($token['access_token'], $token['openid']); $user = json_decode($response,true); //用戶昵稱轉(zhuǎn)換 //$user['nickname'] = EmojiTool::emoji_trans($user['nickname']); if($model = User::findOne(['openid' => $user['openid'] ])) { //用戶已存在更新數(shù)據(jù) $model->attributes = $user; $model->modify_time = time(); $model->save(false); }else{ //用戶不存在寫入 $model = new User; $model->attributes = $user; $model->create_time = time(); $model->save(false); } } return isset($model->id) ? $model->id : ''; } }
e. 控制器調(diào)用(這里只貼其中一個方法)
/** * 產(chǎn)品列表 * @return object 所有可用產(chǎn)品信息 */ public function actionIndex(){ //判斷頁面是否自動刷新 if(isset($_GET['state'])) { $refresh = ; }else{ $refresh = ; } //獲取用戶code $user = new UserinfoClass; $request = $user->getCode('r=store/index', ); //該用戶userid $userid = $user->info($request[]); $model = new Product; $list = $model->find()->where(['status' => ])->all(); return $this->render('index',['list' => $list, 'refresh' => $refresh, 'userid' => $userid, 'request' => $request]); }
程序要求用戶打開產(chǎn)品列表即獲取用戶信息并存入數(shù)據(jù)庫,其中設(shè)計了幾個變量作用如下:
$refresh:判斷頁面是否刷新,由于首次打開頁面未進行oauth驗證時才自動請求驗證,避免反復(fù)刷新,這里用回調(diào)的state參數(shù)作為判斷依據(jù)且設(shè)state=1(若有特定參數(shù)需要可將state賦值為所需值);
$request:即為驗證請求地址
f. 視圖自動刷新
只需要在視圖中添加以下js代碼即可
<script type="text/javascript"> //自動請求獲取code $(function(){ var refresh = <?= $refresh; ?>; var request = '<?= $request[]; ?>'; if(refresh == ){ console.log(); location = request; } }); </script>
以上內(nèi)容給大家介紹了微信開發(fā)之網(wǎng)頁授權(quán)獲取用戶信息(二)的全部敘述,希望本文分享能夠給大家?guī)韼椭?/p>
相關(guān)文章
詳解php中serialize()和unserialize()函數(shù)
這篇文章主要介紹了php的serialize()函數(shù)和unserialize()函數(shù)的相關(guān)資料,需要的朋友可以參考下2017-07-07關(guān)于laravel5.5的定時任務(wù)詳解(demo)
今天小編就為大家分享一篇關(guān)于laravel5.5的定時任務(wù)詳解(demo),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-10-10php json轉(zhuǎn)換相關(guān)知識(小結(jié))
這篇文章主要介紹了php json轉(zhuǎn)換相關(guān)知識(小結(jié)),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-12-12