阅读 104

H5 接入微信登录

提供一个可用的 APPID,可以通过微信登录测试网站获取一个测试用的。

export default {
  name: 'home',
  data() {
    return {
      APPID: 'wxbf8fccd8049a0c26',
      code: ''
    }
  },

  created() {
    this.code = this.getQueryStringByName('code')
    // if (!getLocalStorage('openId')) {
    //   this.login()
    // }
  },
  methods: {
    login() {
      return new Promise((resolve, reject) => {
        if (!this.code && !getLocalStorage('openId')) {
          let uri = encodeURIComponent(window.location.origin + window.location.pathname)
          let url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${this.APPID}&redirect_uri=${uri}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`
          window.location.href = url
        } else {
          openIdLogin(this.code).then(res => {
            if (res.code == 0) {
              setLocalStorage('userInfo', res.userInfo)
              resolve()
            } else {
              setLocalStorage('url', window.location.origin + window.location.pathname)
              this.$router.replace('/error')
            }
          })
        }
      })
    },
    //根据参数名获取参数值
    getQueryStringByName(name) {
      let result = location.search.match(new RegExp('[?&]' + name + '=([^&]+)', 'i'))
      if (result == null || result.length < 1) {
        return ''
      }
      return result[1]
    }
  }
}
</script>
复制代码
文章分类
前端
文章标签