Home  >  Article  >  WeChat Applet  >  A brief discussion on how to authorize login to the mini program and obtain information and mobile phone number

A brief discussion on how to authorize login to the mini program and obtain information and mobile phone number

青灯夜游
青灯夜游forward
2021-07-23 10:53:175091browse

This article will share with you how to implement authorized login in WeChat applet and obtain user information and mobile phone number.

A brief discussion on how to authorize login to the mini program and obtain information and mobile phone number

Relevant learning recommendations: Mini Program Development Tutorial

Summary, the new function of obtaining the user’s mobile phone number is used, which uses the information about obtaining For the functions of user information and user mobile phone number, when I first wrote it, I found that I wrote two buttons on a login page. The logic of obtaining the mobile phone number is to jump to the homepage when the user clicks authorize, and when the user clicks to reject the pop-up prompt, finally I found that it may be a limitation on WeChat. There is a prompt when debugging on the simulator. If you click on the reject button on a real machine, it will still work. I couldn’t help but write another set about judging the authorization of mobile phone numbers when users enter a certain details page. I will record it here. I hope it can be solved. Help friends in need and see the effect first! ! !

A brief discussion on how to authorize login to the mini program and obtain information and mobile phone number

1. Global judgment

App({
  onLaunch: function () {
    //调用API从本地缓存中获取数据
    // 展示本地存储能力
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
    var that = this;
    //获取用户本地是否是第一次进入新版本
    var versions = wx.getStorageSync('versions');
    console.log('versions:' + versions);
    //判断是不是需要授权
    if (versions == '1'){
      // 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框
      wx.getUserInfo({
        success: function (res) {
          that.globalData.userInfo = res.userInfo
          console.log(that.globalData.userInfo)
        },
        fail: function () {
          wx.redirectTo({
            url: '../wurui_house/pages/login/index',
          })
        }
      })
    }else{
      //未授权, 跳转登录页面
      wx.redirectTo({
        url: '../wurui_house/pages/login/index',
      })
    }
  },
  onShow: function () {
    //		console.log(getCurrentPages())
  },
  onHide: function () {
    //	console.log(getCurrentPages())
  },
  onError: function (msg) {
    //console.log(msg)
  },

  util: require('we7/resource/js/util.js'),
  tabBar: {
    "color": "#123",
    "selectedColor": "#1ba9ba",
    "borderStyle": "#1ba9ba",
    "backgroundColor": "#fff",
    "list": [

    ]
  },
  getLocationInfo: function (cb) {
    var that = this;
    if (this.globalData.locationInfo) {
      cb(this.globalData.locationInfo)
    } else {
      wx.getLocation({
        type: 'gcj02', // 默认为 wgs84 返回 gps 坐标,gcj02 返回可用于 wx.openLocation 的坐标
        success: function (res) {
          that.globalData.locationInfo = res;
          cb(that.globalData.locationInfo)
        },
        fail: function () {
          // fail
        },
        complete: function () {
          // complete
        }
      })
    }
  },
  globalData: {
    userInfo: null,
    appid: "",
    appsecret: "",
  },
  siteInfo: require('siteinfo.js')

});

2.Login login page judgment

(1) index.wxml

<view wx:if="{{isHide}}">
    <view wx:if="{{canIUse}}">
        <view>
            <image src=&#39;../../../we7/resource/images/login.png&#39;></image>
        </view>
        <view>
            <text>请依次允许获得你的公开信息及手机号码</text>
        </view>
        <view class="" >
            <button class="{{flag?&#39;show&#39;:&#39;hide&#39;}}" type="primary" open-type="getUserInfo"  bindgetuserinfo="bindGetUserInfo">{{AuthorizedLogin}}</button>
        <button class="{{flag?&#39;hide&#39;:&#39;show&#39;}}" type="primary" open-type=&#39;getPhoneNumber&#39;  bindgetphonenumber="getPhoneNumber">{{UserPhone}}</button>
        </view>
    </view>
    <view wx:else>请升级微信版本</view>
</view>

(4) index.wxss

.header {
  margin: 90rpx 0 90rpx 50rpx;
  border-bottom: 1px solid #ccc;
  text-align: center;
  width: 650rpx;
  height: 300rpx;
  line-height: 450rpx;
}

.header image {
  width: 200rpx;
  height: 200rpx;
}

.content {
  margin-left: 50rpx;
  margin-bottom: 90rpx;
}

.content text {
  display: block;
  color: #9d9d9d;
  margin-top: 40rpx;
} 
/* .operBtn{
  border-radius: 80rpx;
  margin: 70rpx 50rpx;
  font-size: 35rpx;
}
.operBtns{
  background: #eef0ed !important;
  border-radius: 80rpx;
  margin: 70rpx 50rpx;
  font-size: 35rpx;
  color: #000300 !important;
} */
.hide{
  border-radius: 80rpx;
  margin: 70rpx 50rpx;
  font-size: 35rpx;
  display: none;
}
.show{
  display: block;
  /* background: #eef0ed !important; */
  border-radius: 80rpx;
  margin: 70rpx 50rpx;
  font-size: 35rpx;
  /* color: #000300 !important; */
}

(3) index.js

const app = getApp();
Page({
  data: {
    //判断小程序的API,回调,参数,组件等是否在当前版本可用。
    canIUse: wx.canIUse(&#39;button.open-type.getUserInfo&#39;),
    isHide: false,
    AuthorizedLogin: &#39;授权登录&#39;,
    UserPhone: &#39;手机号授权&#39;,
    lee: "",
    flag: true
  },
  onLoad: function() {
    var that = this;
    // 查看是否授权
    //获取用户本地是否是第一次进入新版本
    var versions = wx.getStorageSync(&#39;versions&#39;);
    if (versions == &#39;1&#39;) {
      wx.getSetting({
        success: function(res) {
          if (res.authSetting[&#39;scope.userInfo&#39;]) {
            //调用共通的登录方法
            app.util.getUserInfo(
              function(userinfo) {
                that.setData({
                  userinfo: userinfo
                })
              });
          } else {
            // 用户没有授权
            // 改变 isHide 的值,显示授权页面
            that.setData({
              isHide: true
            });
          }
        }
      });
    } else {
      // 用户没有授权
      // 改变 isHide 的值,显示授权页面
      that.setData({
        isHide: true
      });
    }

  },
  bindGetUserInfo: function(e) {
    if (e.detail.userInfo) {
      //用户按了允许授权按钮
      var that = this;
      let user = e.detail.userInfo;
      // 获取到用户的信息了,打印到控制台上看下
      console.log("用户的信息如下:");
      console.log(user);
      //授权成功后,通过改变 isHide 的值,让实现页面显示出来,把授权页面隐藏起来
      that.data.lee
      if (that.data.lee == &#39;&#39;) {
        wx.showToast({
            icon: "none",
            title: &#39;请继续点击获取手机号&#39;,
          }),
          that.setData({
            isHide: true,
            flag: (!that.data.flag),
            lee: true
          })
        that.wxlogin();
      } else if (!that.data.lee) {
        wx.switchTab({
          url: "/wurui_house/pages/index/index"
        })

      }
    } else {
      //用户按了拒绝按钮
      wx.showModal({
        title: &#39;警告&#39;,
        content: &#39;您点击了拒绝授权,将无法进入小程序,请授权之后再进入!!!&#39;,
        showCancel: false,
        confirmText: &#39;返回授权&#39;,
        success: function(res) {
          // 用户没有授权成功,不需要改变 isHide 的值
          if (res.confirm) {
            console.log(&#39;用户点击了“返回授权”&#39;);
          }
        }
      });
    }
  },

  wxlogin: function() { //获取用户的openID

    var that = this;
    //调用共通的登录方法
    app.util.getUserInfo(
      function(userinfo) {
        that.setData({
          userinfo: userinfo
        })
      });

  },

  getPhoneNumber: function(e) { //点击获取手机号码按钮
    var that = this;
    that.data.lee
    if (that.data.lee == &#39;&#39;) {
      wx.showToast({
        icon: "none",
        title: &#39;请先点击获取用户信息&#39;,
      })
      return
    } else {
      wx.checkSession({
        success: function(res) {
          console.log(e.detail.errMsg)
          console.log(e.detail.iv)
          console.log(e.detail.encryptedData)
          var ency = e.detail.encryptedData;
          var iv = e.detail.iv;

          var sessionk = that.data.sessionKey;


          if (e.detail.errMsg == &#39;getPhoneNumber:fail user deny&#39;) {
            wx.showModal({
                title: &#39;警告&#39;,
                content: &#39;您点击了拒绝授权,部分功能无法使用!!!&#39;,
                showCancel: false,
                confirmText: &#39;返回授权&#39;,
                success: function(res) {
                  // 用户没有授权成功,不需要改变 isHide 的值
                  if (res.confirm) {
                    wx.setStorageSync(&#39;enws&#39;, &#39;1&#39;);
                    wx.switchTab({
                      url: "/wurui_house/pages/index/index"
                    })
                    console.log(&#39;用户点击了“返回授权”&#39;);
                  };
                }
              }),

              that.setData({

                modalstatus: true,

              });
          } else {
            that.setData({

              lee: false,

            });
            wx.switchTab({
              url: "/wurui_house/pages/index/index"
            })
            //同意授权
            var userinfo = wx.getStorageSync(&#39;userInfo&#39;);
            app.util.request({
              &#39;url&#39;: &#39;entry/wxapp/saveusermobile&#39;,
              data: {
                sessionid: userinfo.sessionid,
                uid: userinfo.memberInfo.uid,
                iv: iv,
                encryptedData: ency
              },
              success: function(res) {
                if (res.data.data.error == 0) {
                  console.log(&#39;success&#39; + res.data.data);
                  //用户已经进入新的版本,可以更新本地数据
                  wx.setStorageSync(&#39;versions&#39;, &#39;1&#39;);
                  wx.setStorageSync(&#39;enws&#39;, &#39;2&#39;);
                } else {
                  //用户保存手机号失败,下次进入继续授权手机号
                  wx.setStorageSync(&#39;enws&#39;, &#39;1&#39;);
                  console.log(&#39;fail&#39; + res.data.data);
                }
              },
              fail: function(res) {
                console.log(&#39;fail&#39; + res);
              }
            });
          }
        },

        fail: function() {

          console.log("session_key 已经失效,需要重新执行登录流程");


          that.wxlogin(); //重新登录
        }

      });
    }

  }
})

2. The mask layer writing method used to determine the mobile phone number authorization of a certain details page

(1) index.html

<code>
  <!-- 受权弹框提醒 -->
  <view class="container">
    <view class="float" hidden=&#39;{{viewShowed}}&#39;>
      <view class=&#39;floatContent&#39;>
      <text>允许授权获取手机号</text>
        <view class=&#39;floatText&#39;>
          <button  bindtap=&#39;cancle&#39; class=&#39;btn-cancle&#39;>取消</button>
        <button  class=&#39;btn-cancle&#39; open-type=&#39;getPhoneNumber&#39; bindgetphonenumber="getPhoneNumber">确认</button>
        </view>
      </view>
    </view>
  </view>
 </code>

(2) index. wxss

/* 手机号授权 */
.float {  
  height: 100%;  
  width: 100%;  
  position: fixed; 
  background-color: rgba(0, 0, 0, 0.5);  
  z-index: 2;  
  top: 0;  
  left: 0;
}
.floatContent {  
  /* padding: 20rpx 0;   */
  width: 80%;  
  background: #fff;  
  margin: 40% auto;  
  border-radius: 20rpx;  
  display: flex;  
  flex-direction: column;  
  justify-content: space-around;  
  align-items: center;  
  position: relative;  
  height: 255rpx;
}
.floatContent text {  
  color: #000;  
  font-size: 40rpx;  
  display: block;  
  margin: 0 auto;
  position: absolute;
  top: 50rpx;
  /* text-align: center;   */
  /* line-height: 60rpx;   */
  border-radius: 30rpx;  
}
.floatText{
  width: 100%;
  height: 100rpx;
  display: flex;
  justify-content: flex-start;
  position: absolute;
  bottom: 0;
}
.btn-cancle{
  line-height: 100rpx;
  flex: 1;
  margin: 0;
  padding: 0;
  border-radius: none;
}

(3) index.js

data: {
    viewShowed: true, //控制授权能否显示
  },
  cancle: function () {
    wx.setStorageSync(&#39;enws&#39;, &#39;2&#39;);
    this.setData({
      viewShowed: true
    })
  },
   /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var enws = wx.getStorageSync(&#39;enws&#39;);
    console.log("enws:", +enws);
    var that = this;
    if (enws != &#39;2&#39;) { //判断能否授权  
      that.setData({
        viewShowed: false,
      })
      console.log(&#39;判断能否授权&#39;);
    } else {

    }
  },

  getPhoneNumber: function (e) { //点击获取手机号码按钮
    var that = this;
    wx.checkSession({
      success: function (res) {
        console.log(e.detail.errMsg)
        console.log(e.detail.iv)
        console.log(e.detail.encryptedData)
        var ency = e.detail.encryptedData;
        var iv = e.detail.iv;

        var sessionk = that.data.sessionKey;

        that.setData({
          viewShowed: true,
        })
        wx.setStorageSync(&#39;enws&#39;, &#39;2&#39;);
        if (e.detail.errMsg == &#39;getPhoneNumber:fail user deny&#39;) {

        } else {
          //同意授权
          var userinfo = wx.getStorageSync(&#39;userInfo&#39;);
          app.util.request({
            &#39;url&#39;: &#39;entry/wxapp/saveusermobile&#39;,
            data: {
              sessionid: userinfo.sessionid,
              uid: userinfo.memberInfo.uid,
              iv: iv,
              encryptedData: ency
            },
            success: function (res) {
              console.log(&#39;success&#39; + res);
              if (res.data.data.error == 0) {
                console.log(&#39;success&#39; + res.data.data);
                //用户已经进入新的版本,可以更新本地数据
                wx.setStorageSync(&#39;versions&#39;, &#39;1&#39;);
              } else {
                //用户保存手机号失败,下次进入继续授权手机号
              }
            },
            fail: function (res) {
              console.log(&#39;fail&#39; + res);
            }
          });
        }
      }
    });
  },

Link: https://pan.baidu.com/s/1E7d33scSpk1tiq_Ndium2g

Extraction code: ll9i

After copying this content, open Baidu network disk and download util.js

For more programming-related knowledge, please visit: Programming getting Started! !

The above is the detailed content of A brief discussion on how to authorize login to the mini program and obtain information and mobile phone number. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete