浅谈小程序如何授权登录,获取信息和手机号

广告:宝塔服务器面板,一键全能部署及管理,送你10850元礼包,点我领取~~~

浅谈小程序如何授权登录,获取信息和手机号

本篇文章给大家分享一下微信小程序实现授权登录,并获取用户信息和手机号的方法。

相关学习推荐:小程序开发教程

总结,新增获取用户手机号功能,里面用到了关于获取用户信息和用户手机号的功能,一开始写的时候发现我把两个按钮写在一个登录页面上,获取手机号逻辑是当用户点击授权之后跳转到首页,当点击拒绝弹窗提示,最后发现可能是微信上的限制,模拟器调试拒绝有提示,真机点击拒绝也是能跳的,没办法又写了一套关于用户进入某个详情页判断手机号授权问题,这里记录一下,希望能帮到有需要的朋友,先看下效果!!!

1.全局判断

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登录页判断

(一)index.wxml

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

(四)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; */}
登录后复制

(三)index.js

const app = getApp();Page({  data: {    //判断小程序的API,回调,参数,组件等是否在当前版本可用。    canIUse: wx.canIUse('button.open-type.getUserInfo'),    isHide: false,    AuthorizedLogin: '授权登录',    UserPhone: '手机号授权',    lee: "",    flag: true  },  onLoad: function() {    var that = this;    // 查看是否授权    //获取用户本地是否是第一次进入新版本    var versions = wx.getStorageSync('versions');    if (versions == '1') {      wx.getSetting({        success: function(res) {          if (res.authSetting['scope.userInfo']) {            //调用共通的登录方法            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 == '') {        wx.showToast({            icon: "none",            title: '请继续点击获取手机号',          }),          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: '警告',        content: '您点击了拒绝授权,将无法进入小程序,请授权之后再进入!!!',        showCancel: false,        confirmText: '返回授权',        success: function(res) {          // 用户没有授权成功,不需要改变 isHide 的值          if (res.confirm) {            console.log('用户点击了“返回授权”');          }        }      });    }  },  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 == '') {      wx.showToast({        icon: "none",        title: '请先点击获取用户信息',      })      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 == 'getPhoneNumber:fail user deny') {            wx.showModal({                title: '警告',                content: '您点击了拒绝授权,部分功能无法使用!!!',                showCancel: false,                confirmText: '返回授权',                success: function(res) {                  // 用户没有授权成功,不需要改变 isHide 的值                  if (res.confirm) {                    wx.setStorageSync('enws', '1');                    wx.switchTab({                      url: "/wurui_house/pages/index/index"                    })                    console.log('用户点击了“返回授权”');                  };                }              }),              that.setData({                modalstatus: true,              });          } else {            that.setData({              lee: false,            });            wx.switchTab({              url: "/wurui_house/pages/index/index"            })            //同意授权            var userinfo = wx.getStorageSync('userInfo');            app.util.request({              'url': 'entry/wxapp/saveusermobile',              data: {                sessionid: userinfo.sessionid,                uid: userinfo.memberInfo.uid,                iv: iv,                encryptedData: ency              },              success: function(res) {                if (res.data.data.error == 0) {                  console.log('success' + res.data.data);                  //用户已经进入新的版本,可以更新本地数据                  wx.setStorageSync('versions', '1');                  wx.setStorageSync('enws', '2');                } else {                  //用户保存手机号失败,下次进入继续授权手机号                  wx.setStorageSync('enws', '1');                  console.log('fail' + res.data.data);                }              },              fail: function(res) {                console.log('fail' + res);              }            });          }        },        fail: function() {          console.log("session_key 已经失效,需要重新执行登录流程");          that.wxlogin(); //重新登录        }      });    }  }})
登录后复制

2.某个详情页手机号授权判断

使用的遮罩层写法

(一)index.html

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

(二)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;}
登录后复制

(三)index.js

data: {    viewShowed: true, //控制授权能否显示  },  cancle: function () {    wx.setStorageSync('enws', '2');    this.setData({      viewShowed: true    })  },   /**   * 生命周期函数--监听页面显示   */  onShow: function () {    var enws = wx.getStorageSync('enws');    console.log("enws:", +enws);    var that = this;    if (enws != '2') { //判断能否授权        that.setData({        viewShowed: false,      })      console.log('判断能否授权');    } 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('enws', '2');        if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {        } else {          //同意授权          var userinfo = wx.getStorageSync('userInfo');          app.util.request({            'url': 'entry/wxapp/saveusermobile',            data: {              sessionid: userinfo.sessionid,              uid: userinfo.memberInfo.uid,              iv: iv,              encryptedData: ency            },            success: function (res) {              console.log('success' + res);              if (res.data.data.error == 0) {                console.log('success' + res.data.data);                //用户已经进入新的版本,可以更新本地数据                wx.setStorageSync('versions', '1');              } else {                //用户保存手机号失败,下次进入继续授权手机号              }            },            fail: function (res) {              console.log('fail' + res);            }          });        }      }    });  },
登录后复制

链接:https://pan.baidu.com/s/1E7d33scSpk1tiq_Ndium2g

提取码:ll9i

复制这段内容后打开百度网盘,下载util.js

更多编程相关知识,请访问:编程入门!!

以上就是浅谈小程序如何授权登录,获取信息和手机号的详细内容,更多请关注9543建站博客其它相关文章!

9543建站博客
一个专注于网站开发、微信开发的技术类纯净博客。
作者头像
admin创始人

肥猫,知名SEO博客站长,14年SEO经验。

上一篇:yii2关闭错误提示
下一篇:微信聊天记录被删除了怎么恢复

发表评论

关闭广告
关闭广告