小程序模板网

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

发布时间:2018-06-04 12:12 所属栏目:小程序开发教程

微信小程序官方登录方式修改,要求通过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,
    // });
  }


易优小程序(企业版)+灵活api+前后代码开源 码云仓库:starfork
本文地址:https://www.eyoucms.com/wxmini/doc/course/24496.html 复制链接 如需定制请联系易优客服咨询:800182392 点击咨询
QQ在线咨询