时间:2022-08-06 21:21:01 | 来源:网站运营
时间:2022-08-06 21:21:01 来源:网站运营
前段时间,面试官问到微信网页登录的授权流程分为几步,一面懵逼的我不知所措...下面是来自微信开发文档
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); }
关键词:清楚,流程,授权