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

 5639

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


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


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


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


1、全局判断

  1. App({
  2.   onLaunch: function () {
  3.     //调用API从本地缓存中获取数据
  4.     // 展示本地存储能力
  5.     var logs = wx.getStorageSync('logs') || []
  6.     logs.unshift(Date.now())
  7.     wx.setStorageSync('logs', logs)
  8.     var that = this;
  9.     //获取用户本地是否是第一次进入新版本
  10.     var versions = wx.getStorageSync('versions');
  11.     console.log('versions:' + versions);
  12.     //判断是不是需要授权
  13.     if (versions == '1'){
  14.       // 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框
  15.       wx.getUserInfo({
  16.         success: function (res) {
  17.           that.globalData.userInfo = res.userInfo
  18.           console.log(that.globalData.userInfo)
  19.         },
  20.         fail: function () {
  21.           wx.redirectTo({
  22.             url: '../wurui_house/pages/login/index',
  23.           })
  24.         }
  25.       })
  26.     }else{
  27.       //未授权, 跳转登录页面
  28.       wx.redirectTo({
  29.         url: '../wurui_house/pages/login/index',
  30.       })
  31.     }
  32.   },
  33.   onShow: function () {
  34.     //      console.log(getCurrentPages())
  35.   },
  36.   onHide: function () {
  37.     //  console.log(getCurrentPages())
  38.   },
  39.   onError: function (msg) {
  40.     //console.log(msg)
  41.   },
  42.  
  43.   util: require('we7/resource/js/util.js'),
  44.   tabBar: {
  45.     "color": "#123",
  46.     "selectedColor": "#1ba9ba",
  47.     "borderStyle": "#1ba9ba",
  48.     "backgroundColor": "#fff",
  49.     "list": [
  50.  
  51.     ]
  52.   },
  53.   getLocationInfo: function (cb) {
  54.     var that = this;
  55.     if (this.globalData.locationInfo) {
  56.       cb(this.globalData.locationInfo)
  57.     } else {
  58.       wx.getLocation({
  59.         type: 'gcj02', // 默认为 wgs84 返回 gps 坐标,gcj02 返回可用于 wx.openLocation 的坐标
  60.         success: function (res) {
  61.           that.globalData.locationInfo = res;
  62.           cb(that.globalData.locationInfo)
  63.         },
  64.         fail: function () {
  65.           // fail
  66.         },
  67.         complete: function () {
  68.           // complete
  69.         }
  70.       })
  71.     }
  72.   },
  73.   globalData: {
  74.     userInfo: null,
  75.     appid: "",
  76.     appsecret: "",
  77.   },
  78.   siteInfo: require('siteinfo.js')
  79.  
  80. });


2、login登录页判断

一、index.wxml

  1. <view wx:if="{{isHide}}">
  2.     <view wx:if="{{canIUse}}">
  3.         <view>
  4.             <image src='../../../we7/resource/images/login.png'></image>
  5.         </view>
  6.         <view>
  7.             <text>请依次允许获得你的公开信息及手机号码</text>
  8.         </view>
  9.         <view class="" >
  10.             <button class="{{flag?'show':'hide'}}" type="primary" open-type="getUserInfo"  bindgetuserinfo="bindGetUserInfo">{{AuthorizedLogin}}</button>
  11.         <button class="{{flag?'hide':'show'}}" type="primary" open-type='getPhoneNumber'  bindgetphonenumber="getPhoneNumber">{{UserPhone}}</button>
  12.         </view>
  13.     </view>
  14.     <view wx:else>请升级微信版本</view>
  15. </view>

二、index.wxss


  1. .header {
  2.   margin: 90rpx 0 90rpx 50rpx;
  3.   border-bottom: 1px solid #ccc;
  4.   text-align: center;
  5.   width: 650rpx;
  6.   height: 300rpx;
  7.   line-height: 450rpx;
  8. }
  9.  
  10. .header image {
  11.   width: 200rpx;
  12.   height: 200rpx;
  13. }
  14.  
  15. .content {
  16.   margin-left: 50rpx;
  17.   margin-bottom: 90rpx;
  18. }
  19.  
  20. .content text {
  21.   display: block;
  22.   color: #9d9d9d;
  23.   margin-top: 40rpx;
  24. } 
  25. /* .operBtn{
  26.   border-radius: 80rpx;
  27.   margin: 70rpx 50rpx;
  28.   font-size: 35rpx;
  29. }
  30. .operBtns{
  31.   background: #eef0ed !important;
  32.   border-radius: 80rpx;
  33.   margin: 70rpx 50rpx;
  34.   font-size: 35rpx;
  35.   color: #000300 !important;
  36. } */
  37. .hide{
  38.   border-radius: 80rpx;
  39.   margin: 70rpx 50rpx;
  40.   font-size: 35rpx;
  41.   display: none;
  42. }
  43. .show{
  44.   display: block;
  45.   /* background: #eef0ed !important; */
  46.   border-radius: 80rpx;
  47.   margin: 70rpx 50rpx;
  48.   font-size: 35rpx;
  49.   /* color: #000300 !important; */
  50. }

三、index.js

  1. const app = getApp();
  2. Page({
  3.   data: {
  4.     //判断小程序的API,回调,参数,组件等是否在当前版本可用。
  5.     canIUse: wx.canIUse('button.open-type.getUserInfo'),
  6.     isHide: false,
  7.     AuthorizedLogin: '授权登录',
  8.     UserPhone: '手机号授权',
  9.     lee: "",
  10.     flag: true
  11.   },
  12.   onLoad: function() {
  13.     var that = this;
  14.     // 查看是否授权
  15.     //获取用户本地是否是第一次进入新版本
  16.     var versions = wx.getStorageSync('versions');
  17.     if (versions == '1') {
  18.       wx.getSetting({
  19.         success: function(res) {
  20.           if (res.authSetting['scope.userInfo']) {
  21.             //调用共通的登录方法
  22.             app.util.getUserInfo(
  23.               function(userinfo) {
  24.                 that.setData({
  25.                   userinfo: userinfo
  26.                 })
  27.               });
  28.           } else {
  29.             // 用户没有授权
  30.             // 改变 isHide 的值,显示授权页面
  31.             that.setData({
  32.               isHide: true
  33.             });
  34.           }
  35.         }
  36.       });
  37.     } else {
  38.       // 用户没有授权
  39.       // 改变 isHide 的值,显示授权页面
  40.       that.setData({
  41.         isHide: true
  42.       });
  43.     }
  44.  
  45.   },
  46.   bindGetUserInfo: function(e) {
  47.     if (e.detail.userInfo) {
  48.       //用户按了允许授权按钮
  49.       var that = this;
  50.       let user = e.detail.userInfo;
  51.       // 获取到用户的信息了,打印到控制台上看下
  52.       console.log("用户的信息如下:");
  53.       console.log(user);
  54.       //授权成功后,通过改变 isHide 的值,让实现页面显示出来,把授权页面隐藏起来
  55.       that.data.lee
  56.       if (that.data.lee == '') {
  57.         wx.showToast({
  58.             icon: "none",
  59.             title: '请继续点击获取手机号',
  60.           }),
  61.           that.setData({
  62.             isHide: true,
  63.             flag: (!that.data.flag),
  64.             lee: true
  65.           })
  66.         that.wxlogin();
  67.       } else if (!that.data.lee) {
  68.         wx.switchTab({
  69.           url: "/wurui_house/pages/index/index"
  70.         })
  71.  
  72.       }
  73.     } else {
  74.       //用户按了拒绝按钮
  75.       wx.showModal({
  76.         title: '警告',
  77.         content: '您点击了拒绝授权,将无法进入小程序,请授权之后再进入!!!',
  78.         showCancel: false,
  79.         confirmText: '返回授权',
  80.         success: function(res) {
  81.           // 用户没有授权成功,不需要改变 isHide 的值
  82.           if (res.confirm) {
  83.             console.log('用户点击了“返回授权”');
  84.           }
  85.         }
  86.       });
  87.     }
  88.   },
  89.  
  90.   wxlogin: function() { //获取用户的openID
  91.  
  92.     var that = this;
  93.     //调用共通的登录方法
  94.     app.util.getUserInfo(
  95.       function(userinfo) {
  96.         that.setData({
  97.           userinfo: userinfo
  98.         })
  99.       });
  100.  
  101.   },
  102.  
  103.   getPhoneNumber: function(e) { //点击获取手机号码按钮
  104.     var that = this;
  105.     that.data.lee
  106.     if (that.data.lee == '') {
  107.       wx.showToast({
  108.         icon: "none",
  109.         title: '请先点击获取用户信息',
  110.       })
  111.       return
  112.     } else {
  113.       wx.checkSession({
  114.         success: function(res) {
  115.           console.log(e.detail.errMsg)
  116.           console.log(e.detail.iv)
  117.           console.log(e.detail.encryptedData)
  118.           var ency = e.detail.encryptedData;
  119.           var iv = e.detail.iv;
  120.  
  121.           var sessionk = that.data.sessionKey;
  122.  
  123.  
  124.           if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
  125.             wx.showModal({
  126.                 title: '警告',
  127.                 content: '您点击了拒绝授权,部分功能无法使用!!!',
  128.                 showCancel: false,
  129.                 confirmText: '返回授权',
  130.                 success: function(res) {
  131.                   // 用户没有授权成功,不需要改变 isHide 的值
  132.                   if (res.confirm) {
  133.                     wx.setStorageSync('enws', '1');
  134.                     wx.switchTab({
  135.                       url: "/wurui_house/pages/index/index"
  136.                     })
  137.                     console.log('用户点击了“返回授权”');
  138.                   };
  139.                 }
  140.               }),
  141.  
  142.               that.setData({
  143.  
  144.                 modalstatus: true,
  145.  
  146.               });
  147.           } else {
  148.             that.setData({
  149.  
  150.               lee: false,
  151.  
  152.             });
  153.             wx.switchTab({
  154.               url: "/wurui_house/pages/index/index"
  155.             })
  156.             //同意授权
  157.             var userinfo = wx.getStorageSync('userInfo');
  158.             app.util.request({
  159.               'url': 'entry/wxapp/saveusermobile',
  160.               data: {
  161.                 sessionid: userinfo.sessionid,
  162.                 uid: userinfo.memberInfo.uid,
  163.                 iv: iv,
  164.                 encryptedData: ency
  165.               },
  166.               success: function(res) {
  167.                 if (res.data.data.error == 0) {
  168.                   console.log('success' + res.data.data);
  169.                   //用户已经进入新的版本,可以更新本地数据
  170.                   wx.setStorageSync('versions', '1');
  171.                   wx.setStorageSync('enws', '2');
  172.                 } else {
  173.                   //用户保存手机号失败,下次进入继续授权手机号
  174.                   wx.setStorageSync('enws', '1');
  175.                   console.log('fail' + res.data.data);
  176.                 }
  177.               },
  178.               fail: function(res) {
  179.                 console.log('fail' + res);
  180.               }
  181.             });
  182.           }
  183.         },
  184.  
  185.         fail: function() {
  186.  
  187.           console.log("session_key 已经失效,需要重新执行登录流程");
  188.  
  189.  
  190.           that.wxlogin(); //重新登录
  191.         }
  192.  
  193.       });
  194.     }
  195.  
  196.   }
  197. })


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

使用的遮罩层写法

一、index.html

  1. <code>
  2.   <!-- 受权弹框提醒 -->
  3.   <view class="container">
  4.     <view class="float" hidden='{{viewShowed}}'>
  5.       <view class='floatContent'>
  6.       <text>允许授权获取手机号</text>
  7.         <view class='floatText'>
  8.           <button  bindtap='cancle' class='btn-cancle'>取消</button>
  9.         <button  class='btn-cancle' open-type='getPhoneNumber' bindgetphonenumber="getPhoneNumber">确认</button>
  10.         </view>
  11.       </view>
  12.     </view>
  13.   </view>
  14.  </code>

二、index.wxss

  1. /* 手机号授权 */
  2. .float {  
  3.   height: 100%;  
  4.   width: 100%;  
  5.   position: fixed; 
  6.   background-color: rgba(0, 0, 0, 0.5);  
  7.   z-index: 2;  
  8.   top: 0;  
  9.   left: 0;
  10. }
  11. .floatContent {  
  12.   /* padding: 20rpx 0;   */
  13.   width: 80%;  
  14.   background: #fff;  
  15.   margin: 40% auto;  
  16.   border-radius: 20rpx;  
  17.   display: flex;  
  18.   flex-direction: column;  
  19.   justify-content: space-around;  
  20.   align-items: center;  
  21.   position: relative;  
  22.   height: 255rpx;
  23. }
  24. .floatContent text {  
  25.   color: #000;  
  26.   font-size: 40rpx;  
  27.   display: block;  
  28.   margin: 0 auto;
  29.   position: absolute;
  30.   top: 50rpx;
  31.   /* text-align: center;   */
  32.   /* line-height: 60rpx;   */
  33.   border-radius: 30rpx;  
  34. }
  35. .floatText{
  36.   width: 100%;
  37.   height: 100rpx;
  38.   display: flex;
  39.   justify-content: flex-start;
  40.   position: absolute;
  41.   bottom: 0;
  42. }
  43. .btn-cancle{
  44.   line-height: 100rpx;
  45.   flex: 1;
  46.   margin: 0;
  47.   padding: 0;
  48.   border-radius: none;
  49. }

三、index.js

  1. data: {
  2.     viewShowed: true, //控制授权能否显示
  3.   },
  4.   cancle: function () {
  5.     wx.setStorageSync('enws', '2');
  6.     this.setData({
  7.       viewShowed: true
  8.     })
  9.   },
  10.    /**
  11.    * 生命周期函数--监听页面显示
  12.    */
  13.   onShow: function () {
  14.     var enws = wx.getStorageSync('enws');
  15.     console.log("enws:", +enws);
  16.     var that = this;
  17.     if (enws != '2') { //判断能否授权  
  18.       that.setData({
  19.         viewShowed: false,
  20.       })
  21.       console.log('判断能否授权');
  22.     } else {
  23.  
  24.     }
  25.   },
  26.  
  27.   getPhoneNumber: function (e) { //点击获取手机号码按钮
  28.     var that = this;
  29.     wx.checkSession({
  30.       success: function (res) {
  31.         console.log(e.detail.errMsg)
  32.         console.log(e.detail.iv)
  33.         console.log(e.detail.encryptedData)
  34.         var ency = e.detail.encryptedData;
  35.         var iv = e.detail.iv;
  36.  
  37.         var sessionk = that.data.sessionKey;
  38.  
  39.         that.setData({
  40.           viewShowed: true,
  41.         })
  42.         wx.setStorageSync('enws', '2');
  43.         if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
  44.  
  45.         } else {
  46.           //同意授权
  47.           var userinfo = wx.getStorageSync('userInfo');
  48.           app.util.request({
  49.             'url': 'entry/wxapp/saveusermobile',
  50.             data: {
  51.               sessionid: userinfo.sessionid,
  52.               uid: userinfo.memberInfo.uid,
  53.               iv: iv,
  54.               encryptedData: ency
  55.             },
  56.             success: function (res) {
  57.               console.log('success' + res);
  58.               if (res.data.data.error == 0) {
  59.                 console.log('success' + res.data.data);
  60.                 //用户已经进入新的版本,可以更新本地数据
  61.                 wx.setStorageSync('versions', '1');
  62.               } else {
  63.                 //用户保存手机号失败,下次进入继续授权手机号
  64.               }
  65.             },
  66.             fail: function (res) {
  67.               console.log('fail' + res);
  68.             }
  69.           });
  70.         }
  71.       }
  72.     });
  73.   },


附件:浅谈小程序如何授权登录,获取信息和手机号util.js.zip


本文网址:https://www.zztuku.com/detail-9030.html
站长图库 - 浅谈小程序如何授权登录,获取信息和手机号
申明:如有侵犯,请 联系我们 删除。

评论(0)条

您还没有登录,请 登录 后发表评论!

提示:请勿发布广告垃圾评论,否则封号处理!!

    编辑推荐