15158846557 在线咨询 在线咨询
15158846557 在线咨询
所在位置: 首页 > 营销资讯 > 网站运营 > 微信网页登录授权流程都不清楚,还说自己是3年前端?

微信网页登录授权流程都不清楚,还说自己是3年前端?

时间:2022-08-06 21:21:01 | 来源:网站运营

时间:2022-08-06 21:21:01 来源:网站运营

前段时间,面试官问到微信网页登录的授权流程分为几步,一面懵逼的我不知所措...
下面是来自微信开发文档

步骤如图:

第一步:用户同意授权,获取code

第二步:通过code换取网页授权access_token

第三步:刷新access_token

第四步:拉取用户信息

接下来我将实际项目的代码粘出来, 前端nuxt.js

前端部分

在插件plugins 下app.js中封装方法

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); }


步骤如下:

1、根据前端传入的code, 公众号appid,secret获取access_token

2、再根据access_token拉取用户信息




总结:

在微信开发中遇到问题时,一定要结合微信官方文档,先了解其原理再开发。

更多面试题:点击这里



关键词:清楚,流程,授权

74
73
25
news

版权所有© 亿企邦 1997-2025 保留一切法律许可权利。

为了最佳展示效果,本站不支持IE9及以下版本的浏览器,建议您使用谷歌Chrome浏览器。 点击下载Chrome浏览器
关闭