NPLUSWEB / nplusweb.github.io

NPLUS前端技术博客
https://nplusweb.github.io
1 stars 1 forks source link

vue-cli(六) 微信授权登录和微信分享 #24

Open sanghb opened 6 years ago

sanghb commented 6 years ago

了解微信网页授权和js-sdk 微信网页授权:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842 微信js-sdk:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115

提前了解路由拦截 https://github.com/NPLUSWEB/nplusweb.github.io/issues/22

微信授权登录

1、获取授权链接,链接带code

2

2、根据code获取用户信息返回登录凭证

3

遇到的问题: 微信授权链接包括分享出去的链接会附带很多乱七八糟的我们不需要的一些信息,导致链接很长很乱,当再次授权时会出错,也会影响原本链接参数的获取,甚至路由错乱,导致页面打不开。

处理方法: 单独开个空的授权页面,所有授权都走授权页面,授权完成跳回原链接。 用router.beforeEach 来记录目标路由地址存储在本地,授权完成从本地获取地址并跳转。

// 存储目标路由在本地
let authToken = localStorage.getItem('authToken')
router.beforeEach((to, from, next) => {
  if (util.isEmpty(authToken) && to.path !== '/Author') {
    localStorage.setItem('toUrl', to.fullPath) // 保存用户进入的url
    next('/Author')
    return false
  }
}
// 授权页
<script>
export default {
  created () {
    let _this = this
    let code = _this.util.getParameter('code')
    if (_this.util.isEmpty(code)) {
      _this.$wxsdk.getWeChatAuthUrl()
    } else {
      _this.$wxsdk.getWechatAuthTokenByCode(code, function () {
        _this.toUrl()
      })
    }
  },
  methods: {
    toUrl () {
      let _this = this
      let url = localStorage.getItem('toUrl')
      if (!_this.util.isEmpty(url)) {
 localStorage.setItem('toUrl', '' )
        _this.$router.push(url)
      }
    }
  }
}
</script>

微信分享

微信分享授权链接到链接的.html即可,其他信息不用放到授权链接。

授权和分享的案例可以参考SKF项目,svn地址:https://121.40.103.89:4443/svn/core2018/SKF/trunk/WebRoot/resource/system/phone/SKF