基于Vue的单页应用的微信网页授权登录解决思路

微信公众号的微信授权登录,为我们快速导入用户流量提供了极大的便利,我们会选择在发布在微信端的页面中,优先使用微信授权登录,在这次的项目过程中,我们是这样解决微信的网页授权的——

解决思路

代码

  • main.js 配置路由前置操作
router.beforeEach((to, from, next) => {
  if (to.path === '/author' && store.state.userInfo.userId) {
    next('/near');
    return false
  }
  if (!(store.state.userInfo.userId) && to.path !== '/author') {
    store.state.toUrl = to.fullPath;
    next('/author');
  }
  if (store.state.userInfo.userId) {
    next();
    return false
  }
  next();
});
  • author.vue 授权中间件
mounted(){
 if (this.$store.state.toUrl){
          cooike.set('toUrl',this.$store.state.toUrl)
        }
        if (cooike.get('openid') === null){
            if (this.$route.query.openid){
              this.openid = this.$route.query.openid;
              cooike.set('openid',this.openid,5);
              console.log(this.openid);
            }else{
             window.location.href = '********************';//去后端授权页面
            }
        } else{
          this.openid = cooike.get('openid');
        }
this.$ajax({
          method:'POST',
          url:getToken,
          data:qs.stringify({
            openid:this.openid
          }),
        }).then((resp)=>{
          if (resp.data.errcode==='200'){
              console.log(resp.data.data);
            this.$vux.toast.show({
              text:'授权成功',
              time:1000,
            });
            console.log(resp.data.data.token);
            this.$store.state.token=resp.data.data.token;
            console.log(this.$store.state.token);
            this.$store.state.userInfo.userId=resp.data.data.userInfo.userId;
            this.$store.state.userInfo.nickName=resp.data.data.userInfo.nickName;
            this.$store.state.userInfo.headImg=resp.data.data.userInfo.headImg;
            this.$store.state.userInfo.growthValue=resp.data.data.userInfo.growthValue;
            this.$router.replace(cooike.get('toUrl'));
          }else{
            cooike.delete('openid');
            this.$vux.toast.show({
              text:'已经重置,请重新进入',
              time:2000,
              type:"text",
              position:"bottom"
            })

          }
        });
}
  • 后端授权方法
public function auth(){
        $url = $this->_getUrl();
        //echo $url;
        if(!$_GET['code']){
            \LaneWeChat\Core\WeChatOAuth::getCode($url,1,'snsapi_userinfo');
        }
        if($_GET['code']){
            $code = $_GET['code'];
            $arr = \LaneWeChat\Core\WeChatOAuth::getAccessTokenAndOpenId($code);
            $openid = $arr['openid'];
            $access_token = $arr['access_token'];
            $UserModel = M('User');
            $where['openId']=$openid;
            $has = $UserModel ->where($where) ->find();
            $oUtil = new \Base\Controller\UtilController();
            if ($has){
                $token = $oUtil->createToken($has['userid']);
            }else{
                $userInfo = \LaneWeChat\Core\WeChatOAuth::getUserInfo($access_token,$openid);
                $userId = $oUtil->newUserFromWechat($userInfo);
                if ($userId!= null){
                    $token = $oUtil->createToken($userId);
                }else{
                    echo "UnknowError";
                }
            }
            $url = "http://*********/#/author?openid=".$openid;
            header('Location: '.$url, true, 301);
        }
    }
    private function _getUrl() {
        $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
        $php_self = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
        $path_info = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
        $relate_url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $php_self.(isset($_SERVER['QUERY_STRING']) ? '?'.$_SERVER['QUERY_STRING'] : $path_info);
        return $sys_protocal.(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '').$relate_url;
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,338评论 19 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 177,578评论 25 709
  • 今天是我跟心理咨询师的第五次交流,一个多小时的谈话后,我忍不住想要把所学所思记录下来。在自我探寻的路上跌跌撞撞走了...
    清晰无言阅读 647评论 1 0
  • 如果不用面对,或许就不用伤心。 我换了微信页面,改了签名。 换了指甲的颜色,脚后跟纹了一根羽毛。 我告诉自己,一切...
    会飞的千鸟阅读 183评论 0 0
  • 射线:3D世界中一个点向一个方向发射的一天无终点的线,在发射轨迹中鱼其他物体发生碰撞时,他将停止发射。注意:这条线...
    IT白鸽阅读 500评论 0 0

友情链接更多精彩内容