javascript技巧

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript技巧 > 微信小程序手机号一键登录

微信小程序手机号授权一键登录功能实现代码

作者:csstmg

在微信小程序中实现手机号一键登录功能,首先需要通过uni.login调用获取微信的登录凭证(code),然后将此code发送到服务端,本文给大家介绍微信小程序手机号授权一键登录功能,感兴趣的朋友跟随小编一起看看吧

<template>
  <view class="container">
    <!-- <image class="img" 
      src="https://jetour-self-prod.oss-cn-hangzhou.aliyuncs.com/public/jetour-mini/images/car.png"
      mode="widthFix"></image> -->
			<image class="img" :src="backgroundLogo" mode="widthFix"></image>
			<image class="img2" :src="logo" mode="widthFix"></image>
			<image class="img3" :src="carLogo" mode="widthFix"></image>
    <view class="btn-mask">
			<view class="btns" @click="clicklogin" v-show="!isAgreed">
        <button class="openBtn" >一键登录</button>
      </view>
      <view class="btns" v-show="isAgreed">
        <button class="openBtn" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber" >一键登录</button>
      </view>
      <view class="checkbox-container">
        <checkbox-group @change="handleCheckboxChange">
          <label>
            <checkbox value="agree" :checked="isAgreed" class="myCheckbox" />
            我已阅读并同意
            <text class="link" @click.stop="navigateToPrivacyPolicy(1)">《用户服务协议》</text>
            <text class="link" @click.stop="navigateToPrivacyPolicy(2)">《隐私协议》</text>
          </label>
        </checkbox-group>
      </view>
    </view>
  </view>
</template>
<script>
  import dayJs from 'dayjs'
  import {
    getWxCode,
    getWxUserTel,
    getWxUserInfo,
    createWxUserClue
  } from '../../../api/clue.js'
  export default {
    onLoad(option) {
      this.qrCodeId = option.scene
      console.log(this.qrCodeId)
      this.getLoginCode()
    },
    data() {
      return {
				webviewStyles: {
					progress: {
						color: '#FF3333'
					}
				},
				backgroundLogo: require('../../static/img/liveStoreCode/backgroundLogo.png'),
				carLogo: require('../../static/img/liveStoreCode/carLogo.png'),
				logo: require('../../static/img/liveStoreCode/logo.png'),
        isAgreed: false,
        login_code: null,
        sessionKey: null,
        openId: null,
        rawData: null,
        userInfo: {},
        signature: null,
        userTel: null,
        qrCodeId: null,
        showWx: false
      };
    },
    methods: {
      close() {
        this.showWx = false
      },
			handleCheckboxChange(){
				this.isAgreed = !this.isAgreed
			},
      // 跳转到隐私协议页面
      navigateToPrivacyPolicy(type) {
        let goUrl = ''
        if(type == 1){
          goUrl='/pages/protocol/useProtocol'
        }
        if(type == 2){
					goUrl='/pages/protocol/concealProtocol'
				}
				uni.navigateTo({
					url: goUrl
				});
      },
      getLoginCode() {
        const that = this
        uni.login({
          success: function(res) {
						console.log(res, 'login')
            // 获取code    
            that.login_code = res.code;
            uni.getUserInfo({
              withCredentials: true,
              success(data) {
								console.log(data,'data');
                console.log(JSON.stringify(data));
                that.rawData = data.rawData
                that.userInfo = data.userInfo
                that.signature = data.signature
                that.getCurUserWxCode()
              }
            })
          }
        });
      },
			clicklogin(){
				console.log(this.isAgreed,'this.isAgreed');
				if(!this.isAgreed){
					wx.showToast({
						title: '请先同意捷途用户服务协议',
						icon: 'none'
					});
          return false
				}
			},
			// 获取用户手机号
      getPhoneNumber(e) {
        console.log(e.detail,'e.detail') // 判断用户是否允许获取手机号
        const params = {
          encryptedData: e.detail.encryptedData,
          iv: e.detail.iv,
          sessionKey: this.sessionKey,
          openId: this.openid,
          signature: this.signature,
          rawData: this.rawData
        }
        if (e.detail.errMsg == "getPhoneNumber:ok") { // 用户允许或去手机号
          getWxUserTel(params).then(res => {
            this.userTel = res.data.data.phoneNumber
						// 判断从外面过来的type 然后判断是进 活码页面还是领取优惠卷页面
						uni.navigateTo({
							url: `/pages/webView/webView?url=` + encodeURIComponent('https://blog.csdn.net/qq_48701993/article/details/134713613')
						})
            // this.submitClue()
          })
          // this.getCurUserInfo(params)
        }
      },
      getCurUserInfo(params) {
        getWxUserInfo(params)
      },
      getCurUserWxCode() {
        const that = this
        const params = {
          code: this.login_code
        }
        getWxCode(params).then((res) => {
          const data = res.data.data
          that.sessionKey = data.sessionKey
        })
      },
      submitClue() {
        const {
          nickName,
          gender
        } = this.userInfo
				// 跳h5页面 并且携带参数
        // const params = {
        //   qrCodeId: this.qrCodeId,
        //   name: nickName,
        //   phone: this.userTel,
        //   sex: gender,
        //   weChat: '',
        //   authorizationTime: dayJs().format('YYYY-MM-DD HH:mm:ss')
        // }
        // console.log('提交表单' + JSON.stringify(params))
        // createWxUserClue(params).then(res => {
        //   this.showWx = true
        // })
      }
    }
  }
</script>
<style lang="scss">
  .img {
    width: 100vw;
    height: 100vh;
    display: block;
  }
	.img2{
		position: absolute;
		width: 80px;
		height: 80px;
		top: 60px;
		margin-left: calc(50vw - 40px);
	}
	.title{
		font-size: 18px;
		display: flex;
		justify-content: center;
		position: absolute;
		width: 100%;
		top: 150px;
	}
	.img3{
		position: absolute;
		width: 350px;
		height: 222px;
		top: 200px;
		margin-left: calc(50vw - 175px);
	}
  .btn-mask {
    // background-color: rgba(0, 0, 0, 0.2);
    // background-image: url('https://jetour-self-prod.oss-cn-hangzhou.aliyuncs.com/public/jetour-mini/images/car.png');
    // background-size: contain;
    // background-repeat: no-repeat;
    // background-position: bottom;
    position: absolute;
    width: 100%;
    height: 100%;
    z-index: 20;
    top: 0;
    left: 0;
    // .checkbox-container{
    //  position: absolute;
    //  bottom: 80rpx;
    // }
  }
  .myCheckbox{
    ::v-deep .uni-checkbox-input{
      width: 16px;
      height: 16px;
      margin-right: 8px;
    }
  }
   .checkbox-container{
      display: flex;
      width: 94%;
      align-items: center;
      justify-content: center;
      line-height: 25px;
      font-size: 14px;
      color: #666;
      position: absolute;
      left: 5%;
      bottom: 5%;
      font-size: 12px;
    }
    .link {
      color: #007aff;
      // margin: 0 5px;
    }
  .container {
    width: 100vw;
    height: 100vh;
  }
  .btns {
    width: 80%;
    position: absolute;
    left: 10%;
    top: 70%;
    // margin-left: -15%;
    border-radius: 80px;
    display: flex;
    justify-content: flex-start;
    button {
      width: 100%;
      height: 80rpx;
      line-height: 80rpx;
      &:after {
        display: none;
      }
      &.openBtn {
        // background: #00A198;
        background-color: #165DFF;
        color: #fff;
        // border: 1px solid #fff;
      }
    }
  }
  .txt-content {
    text-align: center;
    width: 100%;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    width: 90%;
    margin: 70px auto;
    text {
      color: #3D3D3D;
      font-size: 30rpx;
    }
    image {
      width: 80rpx;
      height: 80rpx;
      border-radius: 20rpx;
      margin-right: 20rpx;
    }
  }
  .jetour-wx {
    background-color: rgba(0, 0, 0, 0.4);
    position: absolute;
    width: 100%;
    height: 100%;
    z-index: 30;
    top: 0;
    left: 0;
    .jetour-wx-content {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      text-align: center;
      width: 400rpx;
      height: auto;
      background: #fff;
      color: #000;
      border-radius: 10px;
      padding: 20px 0;
      display: flex;
      flex-direction: column;
      image {
        width: 360rpx;
        height: 360rpx;
        margin: 0 auto;
      }
      .colse {
        position: absolute;
        right: 10px;
        top: 0px;
        background: none;
        outline: none;
        border: none;
        font-size: 12px;
        padding: 0;
        &:after {
          border: none;
        }
      }
    }
  }
</style>

要点getLoginCode uni.login 以后获取微信code 拿到code 然后走后端接口换信息 具体看代码

https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-login/code2Session.html

小程序自己的组件
https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/getPhoneNumber.html#%E8%BF%94%E5%9B%9E%E5%8F%82%E6%95%B0%E8%AF%B4%E6%98%8E
<view class="btns" v-show="isAgreed">
        <button class="openBtn" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber" >一键登录</button>
      </view>

到此这篇关于微信小程序手机号授权一键登录功能的文章就介绍到这了,更多相关微信小程序手机号一键登录内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文