時間:2022-08-06 21:21:01 | 來源:網站運營
時間:2022-08-06 21:21:01 來源:網站運營
前段時間,面試官問到微信網頁登錄的授權流程分為幾步,一面懵逼的我不知所措...下面是來自微信開發(fā)文檔
export default ({ app }, inject) => { inject('wxLogin', (pageURI) => { let url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + process.env.WXPAGEAPPID + "&scope=snsapi_userinfo&state=STATE&redirect_uri=" + encodeURIComponent(pageURI); return url })}
methods:{ login() { let url = location.href.split("#")[0]; location.href = this.$wxLogin(url); }}
通過此微信登錄授權重定向當前頁面,會拿到code,將其傳入后端<?phpnamespace thago/util;use fast/Http;use think/Session;class Wechat{ private $app_id = ''; private $app_secret = ''; private $scope = 'snsapi_userinfo'; public function __construct($app_id, $app_secret) { $this->app_id = $app_id; $this->app_secret = $app_secret; } /** * 獲取授權token網頁授權 * * @param string $code * @return mixed|string */ public function getAccessToken($code = '') { $params = [ 'appid' => $this->app_id, 'secret' => $this->app_secret, 'code' => $code, 'grant_type' => 'authorization_code' ]; $ret = Http::sendRequest('https://api.weixin.qq.com/sns/oauth2/access_token', $params, 'GET'); if ($ret['ret']) { $ar = json_decode($ret['msg'], true); return $ar; } return []; } /** * 獲取用戶信息 * * @param string $code * @return mixed|string */ public function getUserinfo($access_token,$openid) { $params = [ 'access_token' => $access_token, 'openid' => $openid, 'lang' => 'zh_CN' ]; $ret = Http::sendRequest('https://api.weixin.qq.com/sns/userinfo', $params, 'GET'); if ($ret['ret']) { $ar = json_decode($ret['msg'], true); return $ar; } return []; }}
$wxchat = new /thago/util/Wechat($wxconfig['app_id'],$wxconfig['secret']); $token = $wxchat->getAccessToken($code); $openid = isset($token['openid']) ? $token['openid'] : ''; $access_token = isset($token['access_token']) ? $token['access_token'] : ''; if(!empty($openid)){ $wxUserinfo = $wxchat->getUserinfo($access_token,$openid); }
關鍵詞:清楚,流程,授權