一文读懂 Uniapp 小程序登录流程

一、微信小程序登录原理

登录的标准流程如下:

步骤 动作 说明
1 小程序端调用 uni.login() 获取 code(临时登录凭证)
2 小程序端把 code 发给自己的服务器 通常是 /api/login
3 服务器请求微信接口 https://api.weixin.qq.com/sns/jscode2session appid + secret + code 换取 openidsession_key
4 服务器生成自己的 token 返回前端 对应平台用户身份
5 小程序保存 token 并登录成功 下次启动可直接使用

二、前端开发(UniApp + Vue3)

登录页面代码

/pages/login/login.vue

ts 复制代码
<template>
  <view class="container">
    <view class="title">欢迎使用小程序</view>
    <button @click="handleLogin" class="login-btn">微信一键登录</button>
  </view>
</template>

<script setup>
import { ref } from 'vue'

const token = ref('')
const user = ref({})

// 微信登录
const handleLogin = async () => {
  try {
    // 1. 获取 code
    const { code } = await new Promise((resolve, reject) => {
      uni.login({
        provider: 'weixin',
        success: res => resolve(res),
        fail: err => reject(err)
      })
    })
    console.log('小程序登录凭证 code:', code)

    // 2. 发送到后端
    const [err, res] = await uni.request({
      url: 'http://localhost:3000/api/login', // 后端接口地址
      method: 'POST',
      data: { code }
    })
    if (err) throw new Error('请求失败')

    // 3. 处理后端返回数据
    token.value = res.data.token
    user.value = res.data.user

    uni.setStorageSync('token', token.value)
    uni.setStorageSync('userInfo', user.value)

    uni.showToast({ title: '登录成功', icon: 'success' })
    console.log('登录结果:', res.data)
  } catch (e) {
    console.error(e)
    uni.showToast({ title: '登录失败', icon: 'none' })
  }
}
</script>

<style>
.container {
  margin-top: 200rpx;
  text-align: center;
}
.title {
  font-size: 40rpx;
  margin-bottom: 80rpx;
}
.login-btn {
  background-color: #07c160;
  color: #fff;
  width: 80%;
  border-radius: 12rpx;
}
</style>

✅ 点击按钮会自动执行微信登录流程。


三、后端实现(Node.js)

1️⃣ 环境搭建

创建一个 server 文件夹,执行命令:

复制代码
npm init -y
npm install express axios jsonwebtoken cors

2️⃣ 创建 server.js

ts 复制代码
const express = require('express')
const axios = require('axios')
const jwt = require('jsonwebtoken')
const cors = require('cors')

const app = express()
app.use(cors())
app.use(express.json())

// 你的微信小程序信息
const APPID = '你的小程序AppID'
const SECRET = '你的小程序AppSecret'

// token密钥
const JWT_SECRET = 'my_secret_key'

// 模拟数据库
const users = {}

// 登录接口
app.post('/api/login', async (req, res) => {
  const { code } = req.body
  if (!code) return res.status(400).json({ message: '缺少code' })

  try {
    // 请求微信API换取openid和session_key
    const response = await axios.get(
      `https://api.weixin.qq.com/sns/jscode2session`, {
        params: {
          appid: APPID,
          secret: SECRET,
          js_code: code,
          grant_type: 'authorization_code'
        }
      }
    )

    const { openid, session_key, errcode, errmsg } = response.data
    if (errcode) {
      return res.status(400).json({ message: '微信登录失败: ' + errmsg })
    }

    console.log('用户openid:', openid)

    // 模拟创建/更新用户
    if (!users[openid]) {
      users[openid] = { openid, createTime: new Date() }
    }

    // 生成自定义 token
    const token = jwt.sign({ openid }, JWT_SECRET, { expiresIn: '7d' })

    return res.json({
      token,
      user: users[openid]
    })
  } catch (err) {
    console.error(err)
    res.status(500).json({ message: '服务器错误' })
  }
})

// 验证 token 接口(示例)
app.get('/api/profile', (req, res) => {
  const auth = req.headers.authorization
  if (!auth) return res.status(401).json({ message: '请先登录' })

  try {
    const decoded = jwt.verify(auth.replace('Bearer ', ''), JWT_SECRET)
    res.json({ user: users[decoded.openid] })
  } catch {
    res.status(401).json({ message: 'token无效' })
  }
})

// 启动服务器
app.listen(3000, () => {
  console.log('✅ Server running on http://localhost:3000')
})

✅ 启动命令:

复制代码
node server.js

四、运行测试

  1. 启动后端:

    复制代码
    node server.js
  2. 打开 HBuilderX → 运行 → 运行到微信开发者工具

  3. 点击 "一键登录",查看控制台输出

    • 小程序端日志会打印 code
    • 后端会打印 openid
  4. Toast 提示 "登录成功" ✅


五、持久化登录

登录成功后:

  • 将 token 存到 uni.setStorageSync('token', token)
  • 下次启动时判断本地是否有 token,有则不再重复登录。
ts 复制代码
// 在 App.vue 的 onLaunch 中
onLaunch() {
  const token = uni.getStorageSync('token')
  if (token) {
    console.log('用户已登录:', token)
  } else {
    uni.reLaunch({ url: '/pages/login/login' })
  }
}

六、重点总结

模块 工具 功能
前端 uni.login() 获取 code
前端 uni.request() 调后端登录接口
后端 axios 请求微信接口 用 code 换 openid
后端 jsonwebtoken 生成自定义 token
前端 uni.setStorageSync 保存 token

最终效果:

  • 点击登录按钮 → 自动通过微信授权登录
  • 后端生成 token 并返回
  • 前端保存登录状态
  • 可扩展为用户注册、绑定手机号等功能。
相关推荐
子兮曰6 小时前
async/await高级模式:async迭代器、错误边界与并发控制
前端·javascript·github
恋猫de小郭6 小时前
2026 Flutter VS React Native ,同时在 AI 时代 VS Native 开发,你没见过的版本
android·前端·flutter
GIS之路9 小时前
ArcGIS Pro 中的 Notebooks 入门
前端
IT_陈寒10 小时前
React状态管理终极对决:Redux vs Context API谁更胜一筹?
前端·人工智能·后端
Kagol11 小时前
TinyVue 支持 Skills 啦!现在你可以让 AI 使用 TinyVue 组件搭建项目
前端·agent·ai编程
柳杉11 小时前
从零打造 AI 全球趋势监测大屏
前端·javascript·aigc
simple_lau11 小时前
Cursor配置MasterGo MCP:一键读取设计稿生成高还原度前端代码
前端·javascript·vue.js
睡不着先生11 小时前
如何设计一个真正可扩展的表单生成器?
前端·javascript·vue.js
天蓝色的鱼鱼11 小时前
模块化与组件化:90%的前端开发者都没搞懂的本质区别
前端·架构·代码规范
明君8799711 小时前
Flutter 如何给图片添加多行文字水印
前端·flutter