【2023最新】微信小程序中微信授权登录功能和退出登录功能实现讲解

文章目录

  • 一、讲解视频
  • 二、小程序前端代码
  • 三、后端Java代码
  • 四、备注

一、讲解视频

教学视频地址: 视频地址

二、小程序前端代码

// pages/profile/profile.js
import api from "../../utils/api";
import { myRequest } from "../../utils/request";
import Notify from "@vant/weapp/notify/notify";
import Cache from "../../utils/cache";
import Tool from "../../utils/tool";Page({/*** 页面的初始数据*/data: {isLogin: false,userInfo: {username: "还未登录,请先登录!",headPic: api.BASE_URL + "/photo/view?filename=common/mine_normal.jpg"},basePhotoUrl: api.BASE_URL + "/photo/view?filename=",editUser: {},profileDialogVisible: false},/*** 生命周期函数--监听页面加载*/onLoad: function (options) {this.validateLoginState();},/*** 生命周期函数--监听页面初次渲染完成*/onReady: function () {},/*** 生命周期函数--监听页面显示*/onShow: function () {},/*** 生命周期函数--监听页面隐藏*/onHide: function () {},/*** 生命周期函数--监听页面卸载*/onUnload: function () {},/*** 页面相关事件处理函数--监听用户下拉动作*/onPullDownRefresh: function () {this.validateLoginState();},/*** 页面上拉触底事件的处理函数*/onReachBottom: function () {},/*** 用户点击右上角分享*/onShareAppMessage: function () {},// 预览图片previewHead: function () {let userInfo = this.data.userInfo;let basePhotoUrl = this.data.basePhotoUrl;wx.previewImage({current: userInfo.headPic === userInfo.wxHeadPic ? userInfo.wxHeadPic : basePhotoUrl + userInfo.headPic,urls: [userInfo.headPic === userInfo.wxHeadPic ? userInfo.wxHeadPic : basePhotoUrl + userInfo.headPic]})},// 验证登录状态validateLoginState: async function() {wx.showLoading({title: "获取登录信息...",mask: true})const loginUser = Cache.getCache(getApp().globalData.SESSION_KEY_LOGIN_USER);if(Tool.isEmpty(loginUser)) {wx.hideLoading();return;}const res = await myRequest({url: api.BASE_URL + "/app/user/get_login_user",method: "POST",data: {token: loginUser}});if(res.data.code === 0) {this.setData({userInfo: res.data.data,isLogin: true,editUser: res.data.data})}wx.hideLoading();wx.stopPullDownRefresh();},// 登录操作getLoginUser: function() {wx.showLoading({title: "正在登录...",mask: true})wx.getUserProfile({desc: "获取用户相关信息",success: res => {if(res.errMsg === "getUserProfile:ok") {let username = res.userInfo.nickName;let headPic = res.userInfo.avatarUrl;wx.login({success: async res => {if (res.errMsg === "login:ok") {// 调用后端接口,验证用户数据const response = await myRequest({url: api.BASE_URL + "/app/user/wx_login",method: "POST",data: {wxHeadPic: headPic,wxUsername: username,code: res.code}});if(response.data.code === 0) {Notify({ type: "success", message: response.data.msg, duration: 1000 });Cache.setCache(getApp().globalData.SESSION_KEY_LOGIN_USER, response.data.data.token, 3600);this.setData({userInfo: response.data.data,editUser: response.data.data,isLogin: true});} else {Notify({ type: "danger", message: response.data.msg, duration: 2000 });}} else {wx.showToast({icon: "error",title: "登录失败"});}wx.hideLoading();},fail: res => {wx.showToast({icon: "error",title: "登录失败"});wx.hideLoading();}})} else {wx.showToast({icon: "error",title: "获取用户失败"});wx.hideLoading();}},fail: res => {wx.showToast({icon: "error",title: "获取用户失败"});wx.hideLoading();}})},    // 登录验证authUser: function() {const loginUser = Cache.getCache(getApp().globalData.SESSION_KEY_LOGIN_USER);if(Tool.isEmpty(loginUser)) {Notify({ type: "danger", message: "请先登录!", duration: 2000 });return true;} else {return false;}},// 退出登录logout: async function() {const loginUser = Cache.getCache(getApp().globalData.SESSION_KEY_LOGIN_USER);const res = await myRequest({url: api.BASE_URL + "/app/user/logout",method: "POST",data: {token: loginUser}});if(res.data.code === 0) {Notify({ type: "success", message: res.data.msg, duration: 1000 });}Cache.removeCache(getApp().globalData.SESSION_KEY_LOGIN_USER);    this.setData({isLogin: false, userInfo: {username: "还未登录,请先登录!",headPic: api.BASE_URL + "/photo/view?filename=common/mine_normal.jpg"}});},})

三、后端Java代码

<!--引入http连接依赖-->
<dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.3</version>
</dependency>
package com.yjq.programmer.service.impl;import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yjq.programmer.bean.CodeMsg;
import com.yjq.programmer.dao.UserMapper;
import com.yjq.programmer.domain.User;
import com.yjq.programmer.domain.UserExample;
import com.yjq.programmer.dto.LoginDTO;
import com.yjq.programmer.dto.PageDTO;
import com.yjq.programmer.dto.ResponseDTO;
import com.yjq.programmer.dto.UserDTO;
import com.yjq.programmer.enums.RoleEnum;
import com.yjq.programmer.service.IUserService;
import com.yjq.programmer.utils.CommonUtil;
import com.yjq.programmer.utils.CopyUtil;
import com.yjq.programmer.utils.UuidUtil;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;/*** @author 杨杨吖* @QQ 823208782* @WX yjqi12345678* @create 2023-09-25 17:08*/
@Service
@Transactional
public class UserServiceImpl implements IUserService {@Resourceprivate UserMapper userMapper;@Resourceprivate StringRedisTemplate stringRedisTemplate;private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);// 填写上你的AppID,如何获取AppID自行百度,这步骤很简单private final static String APP_ID = "wxc41c88e07f3f1bd7";// 填写上你的AppSecret,如何获取AppSecret自行百度,这步骤很简单private final static String APP_SECRET = "99a06dc0d1e21d797a9915baca08c872";// 微信小程序登录校验请求地址private final static String LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";/*** 小程序授权登录验证* @param userDTO* @return*/@Overridepublic ResponseDTO<UserDTO> appWxLogin(UserDTO userDTO) {String url = LOGIN_URL + "?appid=" + APP_ID + "&secret="+ APP_SECRET + "&grant_type=authorization_code&js_code=" + userDTO.getCode();HttpClient client = HttpClients.createDefault(); // 创建默认http连接HttpGet getRequest = new HttpGet(url);// 创建一个post请求LoginDTO loginDTO = new LoginDTO();try {// 用http连接去执行get请求并且获得http响应HttpResponse response = client.execute(getRequest);// 从response中取到响实体HttpEntity entity = response.getEntity();// 把响应实体转成文本String html = EntityUtils.toString(entity);loginDTO = JSON.parseObject(html, LoginDTO.class);if(null == loginDTO.getErrcode()) {userDTO.setWxId(loginDTO.getOpenid());} else {return ResponseDTO.errorByMsg(CodeMsg.USER_WX_LOGIN_ERROR);}} catch (Exception e) {e.printStackTrace();return ResponseDTO.errorByMsg(CodeMsg.USER_WX_LOGIN_ERROR);}// 使用微信openId查询是否有此用户UserExample userExample = new UserExample();userExample.createCriteria().andWxIdEqualTo(userDTO.getWxId());List<User> userList = userMapper.selectByExample(userExample);if(null != userList && userList.size() > 0) {// 已经存在用户信息,读取数据库中用户信息User user = userList.get(0);userDTO = CopyUtil.copy(user, UserDTO.class);} else {// 数据库中不存在,注册用户信息User user = CopyUtil.copy(userDTO, User.class);// 自定义工具类,生成8位uuiduser.setId(UuidUtil.getShortUuid());user.setUsername(user.getWxUsername());user.setHeadPic(user.getWxHeadPic());user.setRoleId(RoleEnum.USER.getCode());if(userMapper.insertSelective(user) == 0) {return ResponseDTO.errorByMsg(CodeMsg.USER_REGISTER_ERROR);}// domain转dto 这步不是必须的,我项目中需要这步userDTO = CopyUtil.copy(user, UserDTO.class);}userDTO.setToken(UuidUtil.getShortUuid());stringRedisTemplate.opsForValue().set("USER_" + userDTO.getToken(), JSON.toJSONString(userMapper.selectByPrimaryKey(userDTO.getId())), 3600, TimeUnit.SECONDS);return ResponseDTO.successByMsg(userDTO, "登录成功!");}/*** 获取当前登录用户* @param token* @return*/@Overridepublic ResponseDTO<UserDTO> getLoginUser(String token) {if(CommonUtil.isEmpty(token)){return ResponseDTO.errorByMsg(CodeMsg.USER_SESSION_EXPIRED);}String value = stringRedisTemplate.opsForValue().get("USER_" + token);if(CommonUtil.isEmpty(value)){return ResponseDTO.errorByMsg(CodeMsg.USER_SESSION_EXPIRED);}UserDTO selectedUserDTO = JSON.parseObject(value, UserDTO.class);return ResponseDTO.success(CopyUtil.copy(userMapper.selectByPrimaryKey(selectedUserDTO.getId()), UserDTO.class));}/*** 退出登录操作* @param userDTO* @return*/@Overridepublic ResponseDTO<Boolean> logout(UserDTO userDTO) {if(!CommonUtil.isEmpty(userDTO.getToken())){// token不为空  清除redis中数据stringRedisTemplate.delete("USER_" + userDTO.getToken());}return ResponseDTO.successByMsg(true, "退出登录成功!");}}

四、备注

大家要跟着我的教学视频去配套着看代码,了解整个登录流程的实现思路最重要! 以上是我列出的主要实现代码,页面实现那些根据自己需求去实现,我这就不贴了,如有其他遗漏代码,博客评论区可以提出,我会及时补充!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.xdnf.cn/news/150192.html

如若内容造成侵权/违法违规/事实不符,请联系一条长河网进行投诉反馈,一经查实,立即删除!

相关文章

NLP的不同研究领域和最新发展的概述

一、介绍 作为理解、生成和处理自然语言文本的有效方法&#xff0c;自然语言处理 &#xff08;NLP&#xff09; 的研究近年来迅速普及并被广泛采用。鉴于NLP的快速发展&#xff0c;获得该领域的概述和维护它是困难的。这篇博文旨在提供NLP不同研究领域的结构化概述&#xff0c;…

基于SSM的家庭财务管理系统设计与实现

末尾获取源码 开发语言&#xff1a;Java Java开发工具&#xff1a;JDK1.8 后端框架&#xff1a;SSM 前端&#xff1a;采用JSP技术开发 数据库&#xff1a;MySQL5.7和Navicat管理工具结合 服务器&#xff1a;Tomcat8.5 开发软件&#xff1a;IDEA / Eclipse 是否Maven项目&#x…

总结二:linux面经

文章目录 1、 Linux中查看进程运行状态的指令、查看内存使用情况的指令、tar解压文件的参数。2、文件权限怎么修改&#xff1f;3、说说常用的Linux命令&#xff1f;4、说说如何以root权限运行某个程序&#xff1f;5、 说说软链接和硬链接的区别&#xff1f;6、说说静态库和动态…

Tensorflow、Pytorch和Ray(张量,计算图)

1.深度学习框架&#xff08;Tensorflow、Pytorch&#xff09; 1.1由来 可以追溯到2016年&#xff0c;当年最著名的事件是alphago战胜人类围棋巅峰柯洁&#xff0c;在那之后&#xff0c;学界普遍认为人工智能已经可以在一些领域超过人类&#xff0c;未来也必将可以在更多领域超过…

【伪彩色图像处理】将灰度图像转换为彩色图像研究(Matlab代码实现)

&#x1f4a5;&#x1f4a5;&#x1f49e;&#x1f49e;欢迎来到本博客❤️❤️&#x1f4a5;&#x1f4a5; &#x1f3c6;博主优势&#xff1a;&#x1f31e;&#x1f31e;&#x1f31e;博客内容尽量做到思维缜密&#xff0c;逻辑清晰&#xff0c;为了方便读者。 ⛳️座右铭&a…

【visual studio 小技巧】项目属性->生成->事件

需求 我们有时会用到一些dll&#xff0c;需要把这些dll和我们生成的exe放到一起&#xff0c;一般我们是手动自己copy&#xff0c; 这样发布的时候&#xff0c;有时会忘记拷贝这个dll&#xff0c;导致程序运行出错。学会这个小技巧&#xff0c;就能实现自动copy&#xff0c;非…

node版本问题:Error: error:0308010C:digital envelope routines::unsupported

前言 出现这个错误是因为 node.js V17及以后版本中最近发布的OpenSSL3.0, 而OpenSSL3.0对允许算法和密钥大小增加了严格的限制&#xff0c;可能会对生态系统造成一些影响. 在node.js V17以前一些可以正常运行的的应用程序,但是在 V17 及以后版本可能会抛出以下异常: 我重装系…

《Secure Analytics-Federated Learning and Secure Aggregation》论文阅读

背景 机器学习模型对数据的分析具有很大的优势&#xff0c;很多敏感数据分布在用户各自的终端。若大规模收集用户的敏感数据具有泄露的风险。 对于安全分析的一般背景就是认为有n方有敏感数据&#xff0c;并且不愿意分享他们的数据&#xff0c;但可以分享聚合计算后的结果。 联…

PyTorch入门之【AlexNet】

参考文献&#xff1a;https://www.bilibili.com/video/BV1DP411C7Bw/?spm_id_from333.999.0.0&vd_source98d31d5c9db8c0021988f2c2c25a9620 AlexNet 是一个经典的卷积神经网络模型&#xff0c;用于图像分类任务。 目录 大纲dataloadermodeltraintest 大纲 各个文件的作用&…

[每日算法 - 阿里机试] leetcode19. 删除链表的倒数第 N 个结点

入口 力扣&#xff08;LeetCode&#xff09;官网 - 全球极客挚爱的技术成长平台备战技术面试&#xff1f;力扣提供海量技术面试资源&#xff0c;帮助你高效提升编程技能&#xff0c;轻松拿下世界 IT 名企 Dream Offer。https://leetcode.cn/problems/remove-nth-node-from-end…

【AI视野·今日Robot 机器人论文速览 第四十七期】Wed, 4 Oct 2023

AI视野今日CS.Robotics 机器人学论文速览 Wed, 4 Oct 2023 Totally 40 papers &#x1f449;上期速览✈更多精彩请移步主页 Interesting: &#x1f4da;基于神经网络的多模态触觉感知, classification, position, posture, and force of the grasped object多模态形象的解耦(f…

多普勒频率相关内容介绍

图1 多普勒效应 1、径向速度 径向速度是作用于雷达或远离雷达的速度的一部分。 图2 不同的速度 2、喷气发动机调制 JEM是涡轮机的压缩机叶片的旋转的多普勒频率。 3、多普勒困境 最大无模糊范围需要尽可能低的PRF&#xff1b; 最大无模糊速度需要尽可能高的PRF&#xff1b…

【目标检测】——PE-YOLO精读

yolo&#xff0c;暗光目标检测 论文&#xff1a;PE-YOLO 1. 简介 卷积神经网络&#xff08;CNNs&#xff09;在近年来如何推动了物体检测的发展。许多检测器已经被提出&#xff0c;而且在许多基准数据集上的性能正在不断提高。然而&#xff0c;大多数现有的检测器都是在正常条…

项目环境搭建

注册中心网关配置 spring:cloud:gateway:globalcors:add-to-simple-url-handler-mapping: truecorsConfigurations:[/**]:allowedHeaders: "*"allowedOrigins: "*"allowedMethods:- GET- POST- DELETE- PUT- OPTIONroutes:# 平台管理- id: useruri: lb://…

基于SSM的大学生就业信息管理系统设计与实现

末尾获取源码 开发语言&#xff1a;Java Java开发工具&#xff1a;JDK1.8 后端框架&#xff1a;SSM 前端&#xff1a;采用JSP技术开发 数据库&#xff1a;MySQL5.7和Navicat管理工具结合 服务器&#xff1a;Tomcat8.5 开发软件&#xff1a;IDEA / Eclipse 是否Maven项目&#x…

【论文阅读】An Evaluation of Concurrency Control with One Thousand Cores

An Evaluation of Concurrency Control with One Thousand Cores Staring into the Abyss: An Evaluation of Concurrency Control with One Thousand Cores ABSTRACT 随着多核处理器的发展&#xff0c;一个芯片可能有几十乃至上百个core。在数百个线程并行运行的情况下&…

频次直方图、KDE和密度图

Seaborn的主要思想是用高级命令为统计数据探索和统计模型拟合创建各种图形&#xff0c;下面将介绍一些Seaborn中的数据集和图形类型。 虽然所有这些图形都可以用Matplotlib命令实现&#xff08;其实Matplotlib就是Seaborn的底层&#xff09;&#xff0c;但是用 Seaborn API会更…

黑马点评-02使用Redis代替session,Redis + token机制实现

Redis代替session session共享问题 每个Tomcat中都有一份属于自己的session,所以多台Tomcat并不共享session存储空间,当请求切换到不同tomcat服务时可能会导致数据丢失 用户第一次访问1号tomcat并把自己的信息存放session域中, 如果第二次访问到了2号tomcat就无法获取到在1号…

2023年CSP-J真题详解+分析数据(选择题篇)

目录 前言 2023CSP-J江苏卷详解 小结 前言 下面由我来给大家讲解一下CSP-J的选择题部分。 2023CSP-J江苏卷详解 1.答案 A 解析&#xff1a;const在C中是常量的意思&#xff0c;其作用是声明一个变量&#xff0c;值从头至尾不能被修改 2.答案 D 解析&#xff1a;八进制…

解决WPF+Avalonia在openKylin系统下默认字体问题

一、openKylin简介 openKylin&#xff08;开放麒麟&#xff09; 社区是在开源、自愿、平等和协作的基础上&#xff0c;由基础软硬件企业、非营利性组织、社团组织、高等院校、科研机构和个人开发者共同创立的一个开源社区&#xff0c;致力于通过开源、开放的社区合作&#xff…