The latest authorized login interface for WeChat applet - October 2021

The latest authorized login interface for WeChat applet - October 2021

Rendering:

Mini program authorized login renderings
Note: First we need to use the cloud function in app.js to get the openid, and then when the user clicks to log in, use the obtained openid to check whether the user exists in the user table. If not, write the user information into the database. User table, then log in; if there is one, log in directly;

Go directly to the code!
mypage.wxml code:
<!--pages/mypage/mypage.wxml-->
<!-- 背景图 -->
<view class="bg-box">
	<image src="../image/mypagebg.png"></image>
</view>

<!-- 未登录 -->
<view wx:if="{
     
     {!UserLogin}}" class="login_box" bindtap="getUserProfile">
	<view class="userlogin">
		<view>点击登录</view>
		<view style="font-size: 12px; color:grey;margin-top: 5px;">需要先完成授权登录才能使用服务哟(*v*)</view>
	</view>
</view>

<!-- 已登录 -->
<view wx:else class="login_box">
	<view class="userAvatar_box" bindtap="secretEntrance">
		<image src="{
     
     {userInfo.avatarUrl}}"></image>
	</view>
	<view class="userlogin">
		<view style="font-weight:bold;">欢迎:{
   
   {userInfo.nickName}}</view>
		<view><text style="font-size: 10px; color: gray;">微信用户</text></view>
		<view><text style="font-size: 10px; color: red;">Lv:</text><text style="font-size: 10px; color: orange;">{
   
   {Lv}}</text></view>
	</view>
</view>

<!-- 服务 -->
<view class="service_box">
	<view class="service_title">服务</view>
	<view class="service_row" bindtap="goMycollection">
		<view class="service_icon">
			<image src="../image/mycollection.png"></image>
		</view>
		<view class="service_text">我的收藏</view>
	</view>

	<view class="service_row">
		<view class="service_icon ">
			<image src="../image/kefu.png"></image>
		</view>
		<view class="service_text">
			<button open-type='contact' style="color:black;height:35px;line-height:35px;font-weight: lighter;padding:0;width:100%;border:none;background:#fff;font-size:14px;text-align:left;">在线客服</button>
		</view>
	</view>

	<view  class="service_row" bindtap="exit">
        <view class="service_icon">
            <image src="../image/exit.png"></image>
        </view>
        <view class="service_text">退出登录</view>
    </view>
</view>

mypage.js code:
// pages/mypage/mypage.js
var app = getApp();
const db = wx.cloud.database()
const {
    
    
    formatTime
} = require("../../utils/util.js")
Page({
    
    

    /**
     * 页面的初始数据
     */
    data: {
    
    
        UserLogin: false,
        userInfo: null,
        Lv: '1'
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
    
    
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
    
    
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
    
    
        app.isLogin() // 全局变量
        this.setData({
    
    
            UserLogin: app.globalData.UserLogin,
            userInfo: app.globalData.userInfo
        })
    },
    
    //获取用户信息
    getUserProfile() {
    
    
        let openId = app.globalData.openid
        //console.log('全局的openid', openId)
        wx.getUserProfile({
    
    
            desc: '用于完善会员资料', //声明获取用户信息的用途
            success: (res) => {
    
    
                //console.log('点击获取用户信息成功', res.userInfo)
                let userInfo = res.userInfo
                db.collection('UserList').where({
    
    
                    '_openid': openId
                }).get({
    
    
                    success: res => {
    
    
                        console.log('根据全局openid查询用户表成功', res.data)
                        if (res.errMsg == "collection.get:ok" && res.data.length == 0) {
    
     //length等于0,证明没有该用户,走写入数据库
                            //console.log('走if-1,开始写入数据库')
                            db.collection('UserList') // 把用户信息写入数据库的用户表
                                .add({
    
    
                                    data: {
    
    
                                        avatarUrl: userInfo.avatarUrl,
                                        nickName: userInfo.nickName,
                                        mamager: false,
                                        vip: false,
                                        Lv: 1,
                                        registerTime: formatTime(new Date())
                                    },
                                    success: res => {
    
    
                                        //console.log('写入成功', res.errMsg)
                                        if (res.errMsg == "collection.add:ok") {
    
    
                                            wx.setStorageSync('UserInfo', userInfo) //保存用户信息保存到本地缓存
                                            this.setData({
    
    
                                                userInfo: userInfo,
                                                UserLogin: true,
                                                Lv: "1"
                                            })
                                            wx.showToast({
    
    
                                                title: '恭喜,登录成功',
                                                icon: "success",
                                                duration: 1000,
                                            })
                                        } else {
    
    
                                            // 提示网络错误
                                            wx.showToast({
    
    
                                                title: '登录失败,请检查网络后重试!',
                                                icon: 'none',
                                                duration: 1000,
                                            })
                                        }
                                    },
                                    fail: err => {
    
    
                                        console.log('用户信息写入失败', err)
                                        // 提示网络错误
                                        wx.showToast({
    
    
                                            title: '登录失败,请检查网络后重试!',
                                            icon: 'none',
                                            duration: 1000,
                                        })
                                    }
                                })
                        } else {
    
    
                            //console.log('走else-1,数据库里已存有用户信息,直接登录,不用写入数据库')
                            wx.setStorageSync('UserInfo', userInfo) //保存用户信息保存到本地缓存
                            this.setData({
    
    
                                userInfo: userInfo,
                                UserLogin: true,
                                Lv: res.data[0].Lv
                            })
                            //更新全局状态
                            app.globalData({
    
    
                                userInfo: userInfo,
                                UserLogin: true,
                            })
                        }
                    },
                    fail: err => {
    
    
                        console.log('根据全局openid查询用户表失败', err)
                        // 提示网络错误
                        wx.showToast({
    
    
                            title: '网络错误!获取授权信息失败',
                            icon: 'none',
                            duration: 1000,
                        })
                    }
                })
            },
            fail: err => {
    
    
                console.log('用户信息获取失败', err)
                // 提示网络错误
                wx.showToast({
    
    
                    title: '网络错误!获取授权信息失败',
                    icon: 'none',
                    duration: 1000,
                })
            }
        })
    },
    // 跳转到我的收藏
    goMycollection() {
    
    
        let UserLogin = this.data.UserLogin
        if (UserLogin) {
    
    
            wx.navigateTo({
    
    
              url: '../collection/collection',
            })
        } else {
    
    
            // 提示登录
            wx.showToast({
    
    
                title: '你还未登录,请先登录!',
                icon: 'none',
                duration: 1000,
            })
        }
    },

    // 清除数据退出
    exit() {
    
    
        let UserLogin = this.data.UserLogin
        if (UserLogin) {
    
    
            wx.showToast({
    
    
                title: '退出成功',
                icon:'success',
                duration: 1000,
            })
            this.setData({
    
    
                UserLogin: false,
            })
            wx.removeStorageSync('UserInfo')
        } else {
    
    
            // 提示登录
            wx.showToast({
    
    
                title: '你还未登录,请先登录!',
                icon: 'none',
                duration: 1000,
            })
        }
    },
})
util.js
const formatTime = date => {
    
    
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
const formatNumber = n => {
    
    
  n = n.toString()
  return n[1] ? n : '0' + n
}

module.exports = {
    
    
  formatTime: formatTime
}

app.js code:
//app.js
App({
    
    
  onLaunch: function () {
    
    
    // 初始化云开发环境
    if (!wx.cloud) {
    
    
      //console.error('请使用 2.2.3 或以上的基础库以使用云能力')
    } else {
    
    
      wx.cloud.init({
    
    
        env: 'cloud1-3gklfre2aef67472',//云环境ID
        traceUser: true,
      })
    }
    this.getOpenid();
  },
  globalData: {
    
    
    userInfo: null,
    UserLogin: false,
    openid:null,
  },

  // 获取用户openid
  getOpenid: function () {
    
    
    var app = this;
    var openId = wx.getStorageSync('openId');
    if (openId) {
    
    
      //console.log('本地获取openid:', openId);
      app.globalData.openid = openId;
      app.isLogin();
    } else {
    
    
      wx.cloud.callFunction({
    
    
        name: 'getOpenid',
        success(res) {
    
    
          //console.log('云函数获取openid成功', res.result.openid)
          var openId = res.result.openid;
          wx.setStorageSync('openId', openId)
          app.globalData.openid = openId;
          app.isLogin();
        },
        fail(res) {
    
    
          console.log('云函数获取openid失败', res)
        }
      })
    }
  },

  //检测是否登录函数,未登录则提示登录
  isLogin() {
    
    
    //console.log('app.isLogin方法被执行了')
    var userInfo = wx.getStorageSync('UserInfo') // 获取缓存的用户信息
    if (userInfo.nickName && userInfo.avatarUrl) {
    
    
      this.globalData.UserLogin = true
      this.globalData.userInfo = userInfo
    } else {
    
    
      this.globalData.UserLogin = false
    }
  },

})
mypage.wxss code:
/* pages/mypage/mypage.wxss */

/* 背景图 */
.bg-box {
    
    
	width: 100%;
	height: 300rpx;
	z-index: 1;
}

.bg-box image {
    
    
	z-index: 1;
	width: 100%;
	height: 100%;
}

/* 登录 */
.login_box {
    
    
	height: 200rpx;
	margin: 10rpx 18rpx;
	border-radius: 16rpx;
	background-color: #fff;
	box-shadow: 20rpx 20rpx 10rpx rgba(39, 48, 57, 0.05);
}

.userlogin {
    
    
	height: 100%;
	margin-left: 40rpx;
	float: left;
	display: flex;
	flex-direction: column;
	justify-content: center;
}

.userAvatar_box {
    
    
	width: 150rpx;
	height: 150rpx;
	margin-top: 40rpx;
	margin-left: 20rpx;
	border-radius: 10rpx;
	overflow: hidden;
	float: left;
}

.userAvatar_box image {
    
    
	width: 100%;
	height: 100%;
}

/* 服务 */
.service_box {
    
    
	position: relative;
	margin: 10rpx 18rpx;
	border-radius: 16rpx;
	background-color: #fff;
	box-shadow: 20rpx 20rpx 10rpx rgba(39, 48, 57, 0.05);
}

.service_title {
    
    
	height: 60rpx;
	line-height: 60rpx;
	padding-left: 10rpx;
	font-size: 16px;
	font-weight: bold;
}

.service_row {
    
    
	height: 70rpx;
	margin-top: 16rpx;
	border-bottom: 2rpx #f0f0f0 solid;
}

.service_icon {
    
    
	width: 50rpx;
	height: 50rpx;
	margin-left: 20rpx;
	margin-top: 10rpx;
	float: left;
}

.service_icon image {
    
    
	width: 50rpx;
	height: 50rpx;
}

.service_text {
    
    
	font-size: 14px;
	height: 70rpx;
	line-height: 70rpx;
	margin-left: 100rpx;
}

WeChat applet authorized login video tutorial
If it is useful to you, don’t forget to click three times

Guess you like

Origin blog.csdn.net/IT2047668268/article/details/120673403