微信小程序--登录授权,一键获取用户微信手机号并登录

作者: cheng 发布时间: 2019-10-14 浏览: 1581 次 编辑

一、前言

由于微信官方修改了 getUserInfo 接口,所以现在无法实现一进入微信小程序就弹出授权窗口,只能通过 button 去触发。官方连接:https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/login.html

微信小程序登录流程时序


说明:

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

二、实现思路

自己写一个微信授权登录页面让用户实现点击的功能,也就是实现了通过 button 组件去触发 getUserInfo接口。在用户进入微信小程序的时候,判断用户是否授权了,如果没有授权的话就显示授权页面,让用户去执行授权的操作。如果已经授权了,则直接跳过这个页面,进入首页。

<button class='dialog-btn' open-type="getUserInfo" bindgetuserinfo="getUserInfo">获取用户信息</button>

获取手机号也类似:调用getPhoneNumber方法

<button open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber">获取手机号</button>

三、直接看效果图

https://www.niwoxuexi.com/blog/cheng/article/1110 ---


---

四、看源码

1, index.wxml

<!--pages/login/index.wxml-->
<button class='phone-text'   open-type="getUserInfo"  lang="zh_CN" bindgetuserinfo="onGotUserInfo">请登录</button>
<!--登录弹窗-->
<view class="modal-mask" catchtouchmove="preventTouchMove" wx:if="{{showModal}}"></view>
  <view class="modal-dialog" wx:if="{{showModal}}">
  <view class="modal-content">
    <view><image src='../images/show.png' class='show'></image></view>
    <view>绑定手机号</view>
    <view>请先绑定手机号在进行此操作</view>  
    <button open-type='getPhoneNumber' bindgetphonenumber="getPhoneNumber">
      <image src='../images/showWx.png' class='iconWx'></image>微信用户一键绑定
    </button>
  </view>
</view>

2, index.js

Page({
  /**
   * 页面的初始数据
   */
  data: {
     openid: "",
    loginstate: "0",
    openid: "",
    userEntity: null,
    terminal: "",
    osVersion: "",
     phoneNumber: "",
    showModal: false,//定义登录弹窗
  },
  //在页面加载的时候,判断缓存中是否有内容,如果有,存入到对应的字段里
  onLoad: function () {
    var that = this;
    wx.getStorage({
      key: 'openid',
      success: function (res) {
        that.setData({ openid: res.data });
      },
      fail: function (res) {
        that.getcode();
      }
    });
    wx.getStorage({
      key: 'userEntity',
      success: function (res) {
        that.setData({ userEntity: res.data });
      },
      fail: function (res) {
        console.log("fail1");
      }
    });
    wx.getStorage({
      key: 'loginstate',
      success: function (res) {
        that.setData({ loginstate: res.data });
      }, fail: function (res) {
        console.log("fail2");
      }
    });
  },
  onGotUserInfo: function (e) {
    var that = this;
    if (e.detail.errMsg == "getUserInfo:ok") {
      wx.setStorage({
        key: "userinfo",
        data: e.detail.userInfo
      })
      this.setData({ userInfo: e.detail.userInfo });
      that.showDialogBtn();//调用一键获取手机号弹窗(自己写的)
    }
  },
  // 显示一键获取手机号弹窗
  showDialogBtn: function () {
    this.setData({
      showModal: true//修改弹窗状态为true,即显示
    })
  },
  // 隐藏一键获取手机号弹窗
  hideModal: function () {
    this.setData({
      showModal: false//修改弹窗状态为false,即隐藏
    });
  },
  onshow: function (openid, userInfo, phoneNumber) {
    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        that.setData({ terminal: res.model });
        that.setData({ osVersion: res.system });
      }
    })
    wx.request({
      url: '登录接口',
      method: 'POST',
      header: {
        'content-type': 'application/json' // 默认值
      },
      data: {
        username: phoneNumber,
        parentuser: 'xudeihai',
        wximg: userInfo.avatarUrl,
        nickname: userInfo.nickName,
        identity: "",
        terminal: that.data.terminal,
        osVersion: that.data.system,
        logintype: "10",//微信登录
        openid: that.data.openid,
      },
      success(res) {
        if (res.data.r == "T") {
          that.setData({ userEntity: res.data.d });
          wx.setStorage({
            key: "userEntity",
            data: res.data.d
          })
          that.setData({ loginstate: "1" });
          wx.setStorage({
            key: "loginstate",
            data: "1"
          })
          wx.setStorage({
            key: 'userinfo',
            data: "1"
          })
        }
        else {
          return;
        }
      },
      fail(res) {
        console.log(res);
      }
    })
  },
  //绑定手机
  getPhoneNumber: function (e) {
    var that = this;
    that.hideModal();
    wx.checkSession({
      success: function () {
        wx.login({
          success: res => {
            wx.request({
              url: '自己的登录接口', //仅为示例,并非真实的接口地址
              data: {
                account: '1514382701',
                jscode: res.code
              },
              method: "POST",
              header: {
                'content-type': 'application/json' // 默认值
              },
              success(res) {
                if (res.data.r == "T") {
                  wx.setStorage({
                    key: "openid",
                    data: res.data.openid
                  })
                  wx.setStorage({
                    key: "sessionkey",
                    data: res.data.sessionkey
                  })
                  wx.setStorageSync("sessionkey", res.data.sessionkey);
                  wx.request({
                    url: '自己的解密接口',//自己的解密地址
                    data: {
                      encryptedData: e.detail.encryptedData,
                      iv: e.detail.iv,
                      code: wx.getStorageSync("sessionkey")
                    },
                    method: "post",
                    header: {
                      'content-type': 'application/json'
                    },
                    success: function (res) {
                      if (res.data.r == "T") {
                        that.onshow(that.data.openid, that.data.userInfo, res.data.d.phoneNumber);//调用onshow方法,并传递三个参数
                        console.log("登录成功")
                        console.log(res.data.d.phoneNumber)//成功后打印微信手机号
                      }
                      else {
                        console.log(res);
                      }
                    }
                  })
                }
              }
            })
          }
        })
      },
      fail: function () {
        wx.login({
          success: res => {
            wx.request({
              url: '自己的登录接口', //仅为示例,并非真实的接口地址
              data: {
                account: '1514382701',
                jscode: res.code
              },
              method: "POST",
              header: {
                'content-type': 'application/json' // 默认值
              },
              success(res) {
                if (res.data.r == "T") {
                  wx.setStorage({
                    key: "openid",
                    data: res.data.openid
                  })
                  wx.setStorage({
                    key: "sessionkey",
                    data: res.data.sessionkey
                  })
                  wx.request({
                    url: '自己的解密接口',//自己的解密地址
                    data: {
                      encryptedData: e.detail.encryptedData,
                      iv: e.detail.iv,
                      code: res.data.sessionkey
                    },
                    method: "post",
                    header: {
                      'content-type': 'application/json'
                    },
                    success: function (res) {
                      that.onshow(that.data.openid, that.data.userInfo, res.data.d.phoneNumber);//调用onshow方法,并传递三个参数
                    }
                  })
                }
              }
            })
          }
        })
      }
    })
  },
})

3, index.wxss

/* ---弹窗css--- */
  .modal-mask {
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  background: #000;
  opacity: 0.5;
  overflow: hidden;
  color: #fff;
}
.modal-dialog {
  width: 72%;
  position: absolute;
  top: 30%;
  left: 14%;
  background: #fff;
  border-radius: 12rpx;
}
.modal-content{
  text-align: center;
}
.modal-content .show{
  width: 450rpx;
  height: 323rpx;
  display: block;
  margin: 0 auto;
  margin-top: -118rpx;
  z-index: 10000;
}
.iconWx{
  width:52rpx;
  height: 41rpx;
  padding-right: 20rpx;
}
.iconPhone{
  width:56rpx;
  height: 56rpx;
  padding-right: 15rpx;
}
.modal-content view:nth-of-type(2){
  font-size: 38rpx;
  color: #333333;
  line-height: 1;
}
.modal-content view:nth-of-type(3){
  font-size: 26rpx;
  color: #9c9c9c;
  margin: 18rpx 0 29rpx;
  line-height: 1;
}
.modal-content button:nth-of-type(1){
  width: 80%;
  height: 80rpx;
  border-radius: 60rpx;
  margin: 0 auto 80rpx;
  font-size: 30rpx;
  color: #fff;
  background: #31cc32;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  padding: 0;
  box-sizing: border-box;
}
.modal-content button:nth-of-type(1)::after{
  border: none;
}
.modal-content  .wxLogin{
  font-size: 26rpx;
  color: #424242;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  margin: 38rpx 0 80rpx;
}
button::after{
  border: none;
}

注解:

1,点击登录按钮,弹出微信自带的是否允许授权弹出框,

2,如果点击的是允许,从缓存中读取用户信息,并把用户信息存储起来,

3,同时调用弹出获取手机号的弹窗(这个弹窗时自己写的),在wxml里用wx:if="{{showModal}}"判断获取手机号的隐藏状态,当为true的时候显示,

4,注意在两层view里写了两遍wx:if="{{showModal}}",为什么写两遍呢,因为第一层时弹出框的灰色蒙版背景,第二层是弹出框的内容,两层控制了整个弹窗框是否显示。

五、点击源码下载