One-click login and logout functions of WeChat applet based on uni-app

origin

I am currently using uni-app to develop a WeChat applet. When I developed the login module, I finally realized the login module of the WeChat applet by consulting the uni-app official tutorial, WeChat applet official documents, and online tutorials. Now I will summarize and share it with you ,study together.

general idea

  1. Create Vuex for state management (you can choose whether to use it according to actual needs)

  2. Create a login button and add trigger event

  3. Call the official uni.getUserProfile()interface to obtain user information

  4. Call the official uni.login()interface to obtain the temporary login credential code

  5. Call the login interface of the backend to pass the code to get the token value

  6. login successful! Render user information to the page

  7. Create a logout button and add a trigger event

  8. Clear userinfo and token in vuex

  9. exit successfully! Jump to other pages

Detailed process

  1. Create Vuex for state management, which is used to store token and user information globally for easy use. (You can choose whether to use it according to actual needs)

token can be used to determine whether the user is logged in, and as a subsequent access credential

const store = createStore({
    
    
	state: {
    
    
		"token": uni.getStorageSync('token') || '',
		"userinfo": JSON.parse(uni.getStorageSync('userinfo') || '{}')
	},
	mutations: {
    
    
		// 更新用户信息
		updateUserInfo(state, userinfo) {
    
    
			state.userinfo = userinfo
			this.commit('saveUserInfoToStorge')
		},
		// 将用户信息持久化存储到本地
		saveUserInfoToStorge(state) {
    
    
			uni.setStorageSync('userinfo', JSON.stringify(state.userinfo))
		},
		// 更新 token 字符串
		updateToken(state, token) {
    
    
			state.token = token
			// 调用saveTokenToStorage方法
			this.commit('saveTokenToStorage')
		},

		// 将 token 字符串持久化存储到本地
		saveTokenToStorage(state) {
    
    
			uni.setStorageSync('token', state.token)
		}
	}
})
  1. Create a button and add a trigger event
<button type="primary" @click="getUserInfo">一键登录</button>
  1. Call the official uni.getUserProfile()interface to get user information and store it in Vuex
getUserInfo() {
    
    
	uni.getUserProfile({
    
    
        //声明获取用户个人信息后的用途(必填)
		desc: "仅用作登录功能",
		success: (res) => {
    
    
            //调用Vuex中的updateUserInfo()方法,将用户信息存储到Vuex中
			this.updateUserInfo(res.userInfo)
		},
		fail: () => {
    
    
			uni.$showMsg('您取消了登录授权!')
		}
	})
},
  1. Call the official uni.login()interface to obtain the temporary login credential code
const res = await uni.login().catch(err => err)
//判断是否获取成功
if (res.errMsg !== 'login:ok') return uni.$showMsg('登录失败!')
  1. Call the login interface of the backend to pass the code , and the backend will return a token value, store the token value in Vuex and persist it locally
//换取token
const {
    
     data: loginResult } = await uni.$http.post(`/wx/login?code=${
      
      res.code}`)
//将token值存储到Vuex中
this.updateToken(loginResult.data.ticket)
  1. login successful! Render user information to the page

  2. Create a logout button and add a trigger event

<button @click="logout">退出登录</button>
  1. Define logoutevent handler function
// 退出登录
async logout() {
    
    
  // 询问用户是否退出登录
  const [err, succ] = await uni.showModal({
    
    
    title: '提示',
    content: '确认退出登录吗?'
  }).catch(err => err)

  if (succ && succ.confirm) {
    
    
     // 用户确认了退出登录的操作
     // 清空 vuex 中的 userinfo、token
     this.updateUserInfo({
    
    })
     this.updateToken('')
  }
}
  1. exit successfully! and jump to other pages
uni.switchTab({
    
    
    //跳转到主页
	url: '../../pages/home/home',
	success: () => {
    
    
        //跳转成功后提示退出成功
		uni.$showMsg('退出成功')
	},
})

Summarize

The overall process is not complicated. Login is to call two official interfaces and a background interface to obtain user information and token value, and logout is to clear the stored user information and token value.

This article is updated to my blog synchronously, welcome everyone to visit!
https://blog.zlpo.xyz/

Guess you like

Origin blog.csdn.net/weixin_57006241/article/details/126028974