欢迎光临,了解微信小程序开发,就上易用通!

微信小程序登录方式的修改解决方案

发布:2018-06-04 12:12浏览: 来源:网络 作者:cola

微信小程序官方登录方式修改,要求通过button点击登录,和大家分享一下我的解决方案。

原先的登录逻辑是注册一个全局login方法, login方法中首先调用wx.login静默登录,获取临时登录凭证code,在开发者服务器后台调用 api,使用 code 换取 openid 和 session_key 。然后调用wx.getUserInfo获取用户信息。

现在的实现逻辑是写一个button中转页,进入小程序wx.getUserInfo获取失败后跳转到button中转页,点击button调用bindgetuserinfo方法,该方法返回的detail数据与wx.getUserInfo方法返回的信息一致,此时也可以获取到用户信息。回调成功后wx.navigateBack({})回原页面。

下面贴上部分代码片段:

async bindGetUserInfo(event) {
    const { detail } = event;

    const isSuccess = detail.errMsg === 'getUserInfo:ok';

    if (isSuccess) {
      this.authSuccess(detail);
      return;
    }
    // 用户拒绝授权
    // wx.navigateBack({});
  }
  
  
  
  async authSuccess(detail) {
    await this.getToken(detail);
    wx.navigateBack({});

    // this.nextHander();
  }
  
  
  
保存用户信息
 async getToken(detail) {
    console.log('getToken', detail);

    const session_key = wx.getStorageSync('session_key');

    const { encryptedData: encrypted_data, iv } = detail;
    const that = this;

    // 保存用户信息到服务器
    const { data: { user, up_token, token, is_created } } = await this.fetch({
      url: '/api/artisan/wechat/login',
      data: {
        session_key,
        encrypted_data,
        iv,
      },
      method: 'POST',
    });
    wx.setStorageSync('user', user);
    this.$root.$parent.store.set('up_token', up_token, 30);
    // 存储用户标识符到本地
    this.$root.$parent.store.set('token', token, 30);
    this.$root.$parent.store.set('is_created', is_created, 30);
    //  redux
    // store.dispatch({
    //   type: 'SET_IS_CREATED',
    //   payload: is_created,
    // });
  }




免责声明:本站所有文章和图片均来自用户分享和网络收集,文章和图片版权归原作者及原出处所有,仅供学习与参考,请勿用于商业用途,如果损害了您的权利,请联系网站客服处理。