首页 >微信小程序 >小程序开发 >浅谈小程序如何授权登录,获取信息和手机号

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

青灯夜游
青灯夜游转载
2021-07-23 10:53:175210浏览

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

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

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

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

在这里插入图片描述

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=&#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>

(四)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(&#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.某个详情页手机号授权判断

使用的遮罩层写法

(一)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>

(二)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(&#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);
            }
          });
        }
      }
    });
  },

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

提取码:ll9i

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

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

以上是浅谈小程序如何授权登录,获取信息和手机号的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:csdn.net。如有侵权,请联系admin@php.cn删除