微信開發文檔:https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html
一、公眾號配置
在微信公眾號請求用戶網頁授權之前,開發者需要先到公眾平台官網中的“開發 - 接口權限 - 網頁服務 - 網頁帳號 - 網頁授權獲取用戶基本信息”的配置選項中,修改授權回調域名。請注意,這里填寫的是域名(是一個字符串),而不是URL,因此請勿加 http:// 等協議頭;
授權登陸有兩種:一種是 snsapi_base 靜默登陸,登陸的時候不會彈出授權彈窗,但是這種方式只能獲取 openid;另一種是 snsapi_userinfo,這種方式會彈出授權框,需要用戶手動同意,可以獲取到用戶的詳細信息
access_token:網頁授權用的access_token和基礎支持中的“獲取access_token”的接口獲取的普通access_token不同;
二、授權流程
1、用戶同意授權,獲取code
在需要授權的地方引導用戶進入授權頁面
用戶同意授權后,頁面會跳轉到之前填寫的回調頁面,在回調地址url后面會攜帶code參數,截取url就可以得到code了
注意:每次授權攜帶的code都不一樣,也有過期時間
2、通過code換取網頁授權access_token
如果之前選擇的授權作用域是snsapi_base,那么在本步驟獲取access_token的同時,openid也會獲取到,那么snsapi_base方式的網頁授權也就到此結束了;如果用的是snsapi_userinfo,那還要繼續往下。
需要注意的是access_token有過期時間,所以注意這個時間,避免access_token過期。
3、獲取用戶信息
通過前幾步獲取到的access_token和openid,去請求接口,就額可以獲取用戶的詳細信息了
三、示例代碼
<?php namespace app\index\controller; use think\Controller; /** * 微信功能開發 */ class Wxopera extends Wechat { protected $APPID = 'xxxxxxxxxxxxxxx'; protected $APPSECRET = 'xxxxxxxxxxxxxxx'; /** * curl請求 */ public function http_curl($url, $type = 'get', $res = 'json', $arr = ''){ $cl = curl_init(); curl_setopt($cl, CURLOPT_URL, $url); curl_setopt($cl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($cl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($cl, CURLOPT_SSL_VERIFYHOST, false); if($type == 'post'){ curl_setopt($cl, CURLOPT_POST, 1); curl_setopt($cl, CURLOPT_POSTFIELDS, $arr); } $output = curl_exec($cl); curl_close($cl); return json_decode($output, true); if($res == 'json'){ if( curl_error($cl)){ return curl_error($cl); }else{ return json_decode($output, true); } } } /** * 網頁授權 */ public function shouquan(){ $APPID = $this->APPID; // 編碼 $redirect = urlencode("http://test.zizhuyou.site/index/Wxopera/callback"); // 調起微信授權提示 $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$APPID."&redirect_uri=".$redirect."&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"; // 跳轉授權頁面 $this->redirect($url); } /** * 網頁授權的回調 */ public function callback(){ $APPID = $this->APPID; $APPSECRET = $this->APPSECRET; // 一、獲取用戶授權回調里的code code只有五分鍾有效 echo "<pre>"; // 獲取當前url的參數部分 $params = $_SERVER["QUERY_STRING"]; // s=/index/Wxopera/callback&code=code&state=STATE // 拆分成數組 得到code $arr = explode('&',$params); $code = explode('=',$arr[1]); $code = $code[1]; // 二、通過code獲取網頁授權access_token 有效期7200s,過期需要重新獲取,這里暫不處理過期的問題 $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$APPID&secret=$APPSECRET&code=$code&grant_type=authorization_code"; $res = $this->http_curl($url); // 三、獲取用戶信息 $url2 = "https://api.weixin.qq.com/sns/userinfo?access_token=".$res['access_token']."&openid=".$res['openid']."&lang=zh_CN"; $userinfo = $this->http_curl($url2); print_r($userinfo); } }
思路說明:
1.公眾號配置:填寫回調地址,域名即可
2.調起微信授權提示頁面(snsapi_base 靜默登陸,snsapi_userinfo 手動授權)
3.在回調函數里接收返回的參數 code(有效期五分鍾)
4.拿 code 換取 openid 和 token(默認7200s),此時已經可以獲取到 openid,但還獲取不到詳細信息
5.獲取用戶詳細信息,拿 token 和 openid 獲取用戶詳細信息