用户
 找回密码
 立即注册

QQ登录

只需一步,快速开始

扫一扫,登录网站

小程序社区 首页 教程 实战教程 查看内容

小程序获取用户手机号信息

Rolan 2021-2-23 17:24

小程序获取用户信息和手机号必须要用户主动授权,所以这里需要有个按钮提示用户触发

小程序获取用户信息和手机号必须要用户主动授权,所以这里需要有个按钮提示用户触发

页面样子:

 展示效果:

 

 点击拒绝:

 点击确定跳转到过来时的页面

wxml页面:

复制代码

<view class="no-login">
  
  <view class="page">
    <view class="hd">
      <image class="logo" src="../../../static/images/assets/logo.png">image>
    view>
    <view class="bd">
      <view class="top_line">view>
      
      <text class="s_name">为了保护你的隐私,请登录后查看text>
    view>
    <view class="btn spacing">
      
      <button open-type="getPhoneNumber" class="weui_btn weui_btn_primary"
        bindgetphonenumber="bindPhoneNumber">登录查看button>
      
    view>
  view>
view>
复制代码

wxss:

复制代码
.no-login .page{
  margin-top: 100rpx;
}

.no-login .hd {
  display: flex;
  width: 100%;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.no-login .hd .logo {
  width: 170rpx;
  height: 170rpx;
  margin-top: 40rpx;
  border-radius: 50%;
}

.no-login .hd .title {
  text-align: center;
  font-size: 36rpx;
  color: #000;
}

.no-login .bd {
  width: 100%;
  padding: 50rpx;
}

.no-login .bd .top_line {
  width: 100%;
  height: 2rpx;
  background: #ccc;
  margin-top: 20rpx;
  margin-bottom: 50rpx;
}

.no-login .bd .m_name {
  display: block;
  font-size: 36rpx;
  color: #000;
}

.no-login .bd .s_name {
  margin-top: 25rpx;
  display: block;
  font-size: 34rpx;
  color: #8a8a8a;
  text-align: center;
}

.no-login .btn {
  padding: 120rpx 50rpx 0;
}

.no-login .weui_btn_primary {
  background-color: #5986ED;
}

.no-login .weui_btn {
  position: relative;
  display: block;
  margin-left: auto;
  margin-right: auto;
  padding-left: 14px;
  padding-right: 14px;
  box-sizing: border-box;
  font-size: 18px;
  text-align: center;
  text-decoration: none;
  color: #fff;
  line-height: 2.33333333;
  border-radius: 5px;
  -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
  overflow: hidden;
}

.no-login .weui_btn:after {
  content: " ";
  width: 200%;
  height: 200%;
  position: absolute;
  top: 0;
  left: 0;
  border: 1px solid rgba(0, 0, 0, 0.2);
  -webkit-transform: scale(0.5);
  -ms-transform: scale(0.5);
  transform: scale(0.5);
  -webkit-transform-origin: 0 0;
  -ms-transform-origin: 0 0;
  transform-origin: 0 0;
  box-sizing: border-box;
  border-radius: 10px;
}
复制代码

js:

复制代码
const util = require('../../../utils/util.js');
const api = require('../../../config/api.js');
Component({
  /**
   * 组件的初始数据
   */
  globalData: {
    appid: 'wx5123af152604563', //appid需自己提供,此处的appid我随机编写
    secret: 'c42b59b15d7b7fc3d53c746f7369m4cf', //secret需自己提供,此处的secret我随机编写
  },
  data: {
    canIUse: wx.canIUse('button.open-type.getPhoneNumber'),
    navUrl: '',
    code: '',
    sessionkey: '',
    openid: '',
    appid: 'wx5123af152604563', //appid需自己提供,此处的appid我随机编写
    secret: 'c42b59b15d7b7fc3d53c746f7369m4cf', //secret需自己提供,此处的secret我随机编写

    isLogin: true, // 显示当前组件
  },
  /**
   * 组件的属性列表 
   */
  properties: {
    isLogin: { // 接收传递过来的是否显示
      type: Boolean,
      value: true,
    },
  },

  /**
   * 组件的方法列表
   */
  methods: {
    getToken: function(encryptedData,iv,sessionkey){
      let that = this;

      //let openid = that.data.openid
      console.log('sessionkey:' + sessionkey)
      wx.showLoading({
        title: '加载中',
      })

      util.request(api.AuthLoginByWeixin, {
        sEncryptedData: encryptedData,
        sIv: iv,
        sSessionkey: sessionkey,
        // openid:openid,
      }, 'POST', 'application/json').then(res => {
        console.log(res)
        if (res.code === "SUCCESS") {
          wx.hideLoading();
          //存储用户信息
          wx.setStorageSync('token', res.token)
          console.log(wx.getStorageSync('token'))

          if (that.data.navUrl && (that.data.navUrl == '/pages/index/index' || that.data.navUrl == '/pages/cart/cart' || that.data.navUrl == "/pages/ucenter/index/index")) {
            that.setData({
              isLogin: !that.properties.isLogin
            })

            // 将数据传递过去
            this.triggerEvent("onBindAuthorize", {
              "isLogin": this.data.isLogin,
            })

          } else if (that.data.navUrl) {
            wx.redirectTo({
              url: that.data.navUrl,
            })
          }
        }
      });
    },
    
    login(encryptedData,iv) {
      let that = this;
      wx.login({
        success: function (res) {
          console.log("登陆成功:")
          console.log(res)
          if (res.code) {
            util.request(api.Code2Session+'?code='+res.code).then(function (res) {
              if (res.code === "SUCCESS") {
                console.log('openid和sessionkey:' + res)
                wx.setStorageSync('openid', res.data.openid); //存储openid
                
                that.setData({
                  sessionkey: res.data.session_key,
                  openid: res.data.openid
                })

                that.getToken(encryptedData,iv,res.data.session_key)
              }
            })
          }
        }
      })
    },

    // 绑定手机号
    bindPhoneNumber: function (e) {
      let that = this;

      console.log('绑定手机号信息:')
      console.log(e.detail)

      //登录远程服务器
      if (e.detail.errMsg == 'getPhoneNumber:ok') {
        //用户按了允许授权按钮
        let encryptedData = e.detail.encryptedData // 包括敏感数据在内的完整用户信息的加密数据
        let iv = e.detail.iv // 加密算法的初始向量

        //登录验证
        wx.checkSession({
          success(){
            that.getToken(encryptedData,iv,that.data.sessionkey)
          },
          fail() {
            // session_key 已经失效,需要重新执行登录流程
            that.login(encryptedData,iv)
          }
        })
      } else {
        //用户按了拒绝按钮
        wx.showModal({
          title: '警告',
          content: '您点击了拒绝授权,将无法继续下一步操作,请授权之后再进入!!!',
          showCancel: false,
          confirmText: '返回授权',
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击了“返回授权”');
            }
          }
        });
      }
    },

  },

  created() {
    let that = this;
    console.log('登陆页navuRL:' + wx.getStorageSync('navUrl'))
    // that.login.bind(this)();

    wx.login({
      success: function (res) {
        console.log("登陆成功:")
        console.log(res)
        if (res.code) {
          util.request(api.Code2Session+'?code='+res.code).then(function (res) {
            if (res.code === "SUCCESS") {
              console.log('openid和sessionkey:' + res)
              wx.setStorageSync('openid', res.data.openid); //存储openid
              
              that.setData({
                sessionkey: res.data.session_key,
                openid: res.data.openid
              })
            }
          })
        }
      }
    })

    if (wx.getStorageSync("navUrl")) {
      that.setData({
        navUrl: '/' + wx.getStorageSync("navUrl")
      })
    } else {
      that.setData({
        navUrl: '/pages/index/index'
      })
    }
    if (wx.getStorageSync("token")) {
      if (that.data.navUrl && that.data.navUrl == '/pages/index/index' && that.data.navUrl == '/pages/cart/cart' && that.data.navUrl == '/pages/ucenter/index/index') {
        wx.navigateTo({
          url: that.data.navUrl,
        })
      } else if (that.data.navUrl) {
        wx.switchTab({
          url: that.data.navUrl,
        })
      }
    }


  },
})
鲜花
鲜花
鸡蛋
鸡蛋
分享至 : QQ空间
收藏