前端uniapp+后端springboot 详细教程《实现微信小程序授权登录》(附完整前后端项目demo)

微信小程序官方登录流程图:
在这里插入图片描述
参考微信小程序登录官网文档

1、前端技术栈

1.1、uniapp

使用uniapp构建一套代码多端使用的前端框架项目

1.2、前端封装工具
  • dateUtil.js:
    功能:
    1. 时间日期格式化
    2. 传入日期是否和当前日期的比较
    完整代码:

    // 判断传入日期是否和当前日期比较 
     const judgeDate=(toDate)=>{
         
    	return new Date().getTime()-new Date(toDate).getTime();
    }
    
    var timeFormat = function (msTime) {
         
        let time = new Date(msTime);
        let yy = time.getFullYear();
        let MM = time.getMonth() + 1;
        let dd = time.getDate();
        let hh = time.getHours() < 10 ? "0" + time.getHours() : time.getHours();
        let min =
            time.getMinutes() < 10 ? "0" + time.getMinutes() : time.getMinutes();
        let sec =
            time.getSeconds() < 10 ? "0" + time.getSeconds() : time.getSeconds();
        return yy + "-" + MM + "-" + dd + " " + hh + ":" + min + ":" + sec;
    }
    
    export {
         timeFormat,judgeDate}
    
  • requestUtil.js:
    功能:
    1. 定义公共的url
    2. 后端请求工具封装
    完整代码:

    // 同时发送异步代码的次数
    let ajaxTimes = 0;
    
    // 定义公共的url
    const baseUrl = "http://localhost:8866";
    
    /**
     * 返回baseUrl
     */
    export const getBaseUrl = () => {
         
      return baseUrl;
    }
    
    /**
     * 后端请求工具类
     * @param {*} params 请求参数
     */
    export const requestUtil = (params) => {
         
    
      let header = {
         
        ...params.header
      };
    
      // 拼接header 带上token
      header["token"] = uni.getStorageSync("token");
    
      ajaxTimes++;
    
      // 显示加载中 效果
      wx.showLoading({
         
        title: "加载中",
        mask: true
      });
    
      var start = new Date().getTime();
    
      // 模拟网络延迟加载
      while (true)
        if (new Date().getTime() - start > 1000 * 1) break;
    
      return new Promise((resolve, reject) => {
         
        wx.request({
         
          ...params,
          header: header,
          url: baseUrl + params.url,
          success: (result) => {
         
            resolve(result.data);
          },
          fail: (err) => {
         
            uni.showToast({
         
              icon: 'error',
              title: '连接服务器失败',
              duration: 3000
            })
            reject(err);
          },
          complete: () => {
         
            ajaxTimes--;
            if (ajaxTimes === 0) {
         
              //  关闭正在等待的图标
              wx.hideLoading();
            }
          }
        });
      })
    }
    
  • stringUtil.js:
    功能:
    1. 判断字符串是否为空
    完整代码:

    //判断字符串是否为空
    export const isEmpty = (str) => {
         
      if (str === '' || str.trim().length === 0) {
         
        return true
      } else {
         
        return false;
      }
    }
    
1.3、Hbuilderx构建uniapp项目

在这里插入图片描述
项目结构:
在这里插入图片描述

app.vue中,写两个方法:

  1. 在onLaunch生命周期函数中调用wx.login()获取code(前提是在微信开发者工具中登录微信账号,而且在uniapp中设置微信小程序AppId),code的作用是后端接受到code,通过code参数向微信后台发送请求,它是实现微信临时登录的url中的一个非常重要的参数。
  2. 三个重要参数
  • appid:应用ID
  • secret:应用密钥
  • js_code:前台传给我们的code
  1. wxlogin方法
    携带code参数发送请求给后端来获取token和openid
<script>
  import {
   
    requestUtil
  } from "./utils/requestUtil.js"
  export default {
   
    onLaunch: function() {
   
      console.log('App Launch')
      wx.login({
   
        timeout: 5000,
        success: (res) => {
   
          console.log(res)
          this.wxlogin(res.code);
        }
      });
    },
    onShow: function() {
   
      console.log('App Show')
    },
    onHide: function() {
   
      console.log('App Hide')
    },
    methods: {
   
      /**
       * 请求后端获取用户token
       * @param {} code 
       */
      async wxlogin(code) {
   
        console.log("code=" + code)
        // 发送请求 获取用户的token
        const result = await requestUtil({
   
          url: "/user/wxlogin",
          data: {
   
            code: code
          },
          method: "post"
        });
        console.log("token=" + result.token);
        console.log("openid=" + result.openid);
        if (result.code == 0) {
   
          console.log("登录成功")
          uni.setStorageSync("token", result.token);
          uni.setStorageSync("openid", result.openid);
        } else {
   
          console.log("登录失败,报错信息:" + result.msg);
          uni.showToast({
   
            icon: 'error',
            title: result.msg,
            duration: 3000
          })
        }
      }
    }
  }
</script>

<style>
  /*每个页面公共css */
</style>

2、后端技术栈

  • springboot后端技术框架
  • mybatis-plus数据持久层框架
2.1、创建springboot后端项目

利用idea工具,使用spring initializr初始化创建一个空的springboot项目

springboot版本选择2.3.2.RELEASE。

  1. 修改pom.xml
 <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>


        <!-- 连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.10</version>
        </dependency>
        <!-- mybatis-plus -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.3.2</version>
        </dependency>


        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.40</version>
        </dependency>

        <!-- JWT -->
        <dependency>
            <groupId>com.auth0</groupId>
            <artifactId>java-jwt</artifactId>
            <version>3.2.0</version>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.1</version>
        </dependency>

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.5</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <!-- spring boot redis 缓存引入 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <!-- lettuce pool 缓存连接池 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
        </dependency>

        <!-- hutool工具类-->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.3.3</version>
        </dependency>

        <!-- 验证码依赖-->
   
  • 9
    点赞
  • 91
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hhzz

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值