小程序授权流程

微信小程序开发用户授权登录

在这里插入图片描述
微信官方的开放文档:https://developers.weixin.qq.com/miniprogram/dev/api/open-api/login/wx.login.html

说明:
小程序调用wx.login() 获取 临时登录凭证code ,并回传到开发者服务器
开发者服务器以code换取 用户唯一标识openid 和 会话密钥session_key。
临时登录凭证code只能使用一次

OpenID:
在关注者与公众号产生消息交互后,公众号可获得关注者的OpenID
1.1 普通用户的标识,对当前公众号唯一
1.2 不同的公众号,同一个用户,openid不同
unionid
同一用户,对同一个微信开放平台下的不同应用,unionid是相同的。
也就是说:
如果开发者拥有多个移动应用、网站应用、和公众帐号(包括小程序),可通过unionid来区分用户的唯一性,因为只要是同一个微信开放平台帐号下的移动应用、网站应用和公众帐号(包括小程序),用户的unionid是唯一的。
实践方法
1、调用 wx.login 获取 code。
2、使用 wx.getSetting 获取用户的授权情况
2.1 如果用户已经授权,直接调用 API wx.getUserInfo 获取用户最新的信息;
2.2 用户未授权,在界面中显示一个按钮提示用户登入,当用户点击并授权后就获取到用户的最新信息。
3、将获取到的用户数据连同wx.login返回的code一同传给后端


import {
  me,
  xmini,
} from '../config/xmini';
import api from '../api/index';
import {
  clone
} from '../utils/index';
const app = getApp();
module.exports = {
  authCode: 0,
  // 登录的逻辑
  updatedAuthCode(callback) {
    const that = this
    wx.login({
      success(auth) {
        if (auth.code) {
          console.log('auth code :', auth);
          that.authCode = auth.code;
          callback && callback.call(that, auth.code)
        }
      }
    })
  },
  // 获取用户信息
  getUserInfo(res) {
    // 登录前,先清除下之前登录相关的缓存数据
    app.clearUserInfo();
    //这里是清除登录相关信息
    xmini.store.dispatch('setUserInfo', {})
    xmini.store.dispatch('setAddresses', []);
    console.log(res)

    const detail = res.detail;
    console.log(detail)
    if (detail.errMsg == 'getUserInfo:ok') {
      console.log('xxxx')
        wx.showLoading({
          title: '登录中...',
        })
        this.postLogin({
          data: {
            code: this.authCode,
            // userInfo: res.userInfo,
            encryptedData: encodeURIComponent(detail.encryptedData),
            iv: encodeURIComponent(detail.iv),
          },
          success: loginRes => {
            //更新code
            this.updatedAuthCode();

            wx.hideLoading();
          },
          fail: loginErr => {
            //
            wx.showToast(loginErr.errmsg)
          }
        });
      // })
    } else {
      // 失败!
      if (detail.errMsg === 'getUserInfo:fail auth deny' || detail.errMsg === 'getUserInfo:fail:auth deny') {
        // 获取用户信息授权失败,展示引导
        wx.showModal({
          title: '提示',
          content: '需要你到授权,才能使用完整版的好食期',
          confirmText: '知道了',
          showCancel: false,
          success(res) {
            console.log(res)
          }
        });

      }
    }
  },

  getPhoneNumber(e) {
    console.log('getPhoneNumber:', e)
    if (e.detail.errMsg == 'getPhoneNumber:ok') {
      // 更新code 解析手机号
        wx.showLoading();
        api.userAuthPrepose({
          type: 2,
          code: this.authCode,
          encryptedData: encodeURIComponent(e.detail.encryptedData),
          iv: encodeURIComponent(e.detail.iv),
        }, (res) => {
          //更新code
          this.updatedAuthCode();

          let userInfo = clone(xmini.store.state.user.userInfo)
          userInfo.authPhone = true;
          //这里更新存储的用户信息和地址
          xmini.store.dispatch('setUserInfo', userInfo) 
          xmini.store.dispatch('setAddresses');
        }, (err) => {
          //更新code
          this.updatedAuthCode();
          console.log(err);
        })
      // })
    }
  },

  postLogin({ data = {}, success, fail }){
    const that = this;
    api.login({
      isLoading: false,
      type: 2,
      ...data,
    }, (res) => {
      const { data } = res;
      const userId = data.user_id;

      // 更新code
      that.updatedAuthCode()
      // data.userId = userId;
      if (userId) {
        console.log('登录成功');
        xmini.piwikUpdate({
          isTrackWorking: true,
          userId: data.user_id || '',
          openId: data.wechat_open_id || '',
        });

        // data.authPhone=false; //!!test
        // 更新store
        xmini.store.dispatch('setUserInfo', data)
        success && success.call(that, res);
      } else {
        wx.showToast('用户登录信息有误,请重新登录');
        fail && fail.call(that, res);
      }
      //更新收货地址
      xmini.store.dispatch('setAddresses');
    }, (err) => {
      // 更新code
      that.updatedAuthCode()
      //更新收货地址
      xmini.store.dispatch('setAddresses');
      fail && fail.call(that, err);
      return true;
    });
  },
  // 更新登录
  updatedLogin({ success, fail}) {
    const that = this;
    // 获取 用户是否授过权
    wx.getSetting({
      success(res) {
        console.log(res.authSetting)
        // 判断权限
        if (res.authSetting['scope.userInfo']) {
          // 获取login code
          that.updatedAuthCode((code) => {
            console.log(code);
            // 获取用户信息
            wx.getUserInfo({
              success(res) {
                // console.log(res);
                // 登录
                that.postLogin({
                  data: {
                    code,
                    encryptedData: encodeURIComponent(res.encryptedData),
                    iv: encodeURIComponent(res.iv),
                  },
                  success: res => {
                    console.log(res);
                    success && success(res);
                  },
                  fail: err => {
                    // console.log(err);
                    fail && fail(err);
                  }
                })
              },
              fail(err) {
                fail && fail(err);
              }
            })
            // end
          })
          // end
        }
      }
    })
  },
};

小结:在真实的业务场景中,我们希望,用户进入小程序时,未登录情况下可以正常浏览商品,对小程序有个基本的认知,不要直接弹出框要求用户授权,否则会干扰用户,导致新用户的流失,当用户需要使用一些高级功能和场景,这个时候再去要求用户授权,这样用户授权的几率会大大提高。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值