关于微信网页授权的用法

登录授权流程逻辑:
页面场景:在进入页面时,有的页面需要授权才能进入访问
实现逻辑:

  • 对当前路由meta属性定义变量布尔值requireOauth为true表示当前页需要授权,为false表示不需要授权
  • 通过路由前置取到meta属性判断当前用户是否需要授权登录,若未登录且要跳转的页面需要微信授权登录,就把当前要跳转的页面先进行保存,然后location跳转到授权页面,location的地中携带几个参数appid、要跳转的url、esponse_type、scope
  • location地址是先跳到微信,由微信跳到授权页面,当微信跳到oauth授权页面时url地址栏中会携带code参数,在授权页面中拿着这个code参数去请求授权接口,在授权页面的业务逻辑中,登录成功就跳转到原来开始保存的业务页面,就完成了登录授权的流程了。

实现业务:实现业务就是我要想访问首页index页面,这个页面需要授权权限后才可以访问,所以需要先微信授权,最后在跳回这个页面


token是授权登录成功以后,登录成功后的接口会返回token进行存储在其它业务进行使用

{
    path: '/index',
    name: 'index',
    meta: {
      requireOauth: true,
      requireCardAuth: false
    },
    component: () => import('@/views/index.vue')
  },
  {
    path: '/oauth',
    name: 'oauth',
    meta: {
      requireOauth: false,
      requireCardAuth: false
    },
    component: oauth
  },


router.beforeEach((to, from, next) => {
  redirect(to, from, next)
})

const redirect = (to, from, next) => {
  console.log(config.weixin.defaultRedirectUri);
  const token = getToken();
  const bindStatus = store.state.user.realAuthStatus;
  if (!token && to.meta.requireOauth) {
    // 未登录且要跳转的页面需要微信用户授权登录
    setReferUrl(to.fullPath)
    window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + config.weixin.appid + '&redirect_uri=' + encodeURI(config.weixin.defaultRedirectUri) + '&response_type=code&scope=snsapi_base&state=123#wechat_redirect';
  } else if (token && to.meta.requireCardAuth && bindStatus == '0') {
    // 已登录要去社保卡授权的页面
    setReferUrl(to.fullPath)
    window.location.href = config.wecity.defaultRedirectUrl
  } else {
    // 其他情况 直接跳转
    next()
  }
}

 config.js 配置location地址的id和跳转的地址,这是固定值

config.js
配置location地址的id和跳转的地址,这是固定值

let weixinDefaultRedirectUri = 'http://.com' + '/h5-travel/' + 'oauth';
let weixinDefaultRedirectUrl = 'http://.com' + '/h5-travel/' + 'card-oauth';

  weixin: {
    appid: '',
    defaultRedirectUri: weixinDefaultRedirectUri
  },

 vuex定义公共微信授权登录方法,进行数据的存储

mutations:{
 setUserId (state, id) {
    state.userId = id
    setStore({ name: 'userId', content: state.userId, type: 'session' })
 },
 setToken (state, token) {
    state.token = token
    setToken(token)
 }, 
}


actions: {
    /**
     * @description: 微信授权登录方法
     * @param {*} commit:上下文桥梁
     * @param {*} code:微信调回auth授权页面时携带的参数
     * @param {*} state:重定向后会带上state参数,开发者可以填写a-zA-Z0-9的参数值,最多128字节,可要可不要
     */    
    handleLogin ({ commit }, { code, state }) {
        return new Promise((resolve, reject) => {
          oauthcallback(
            code,
            state
          ).then(res => {
            console.log(res);
            const wrapper = res.data
            if (wrapper.code != '200') {
              throw new Error(wrapper.msg)
            }
            const data = wrapper.data
            commit('setToken', data.sessionToken)
            commit('setUserId', data.userId)
            resolve()
          }).catch(err => {
            reject(err)
          })
        })
      },
    }

微信授权回跳页:微信端:允许授权获取个人信息后,跳转前端微信授权页,前端拿到微信提供的code传给后端,后端通过code值换取网页授权access_token和openid,开发者可以通过access_token和openid拉取用户信息。

<!--
 * @Description: 微信授权登录页
-->
<template>
    <!-- 空页面 负责微信授权登录接口调用和重定向业务页面 -->
    <div style="margin:0 auto;text-align:center;margin-top: 50%;">
        <van-loading size="48px"></van-loading>
    </div>
</template>

<script>
import { mapActions } from 'vuex'
import { getReferUrl } from '@/libs/util'
import router from '@/router/index'
import { json } from 'body-parser';
export default {
    name: 'TravelCardOauth',

    data() {
        return {

        };
    },
    computed: {

    },

    mounted() {
        var _this = this;
        const code = _this.$route.query.code;
        // 调用授权登录方法
        _this['user/handleLogin']({ code }).then(
            res => {
                // 登录成功之后 重新跳转至原页面 或者再次执行统一的跳转方法
                router.replace(getReferUrl())
                //router.go(-1);
            },
            function (err) {
                console.log('微信授权错误', JSON.stringify(err))
                _this.$dialog.alert({
                    title: '提示',
                    message: err.message
                }).then(() => {
                    _this.$router.push('/home')
                });
            }
        );
    },

    methods: {
        ...mapActions(['user/handleLogin'])
    },

};
</script>

<style lang="less" scoped></style>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值