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


    一、讲解视频

    教学视频地址: 视频地址

    二、小程序前端代码

    // 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"
            }});
        },
      
     
      
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219

    三、后端Java代码

    
    
      org.apache.httpcomponents
      httpclient
      4.5.3
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    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 {
    
        @Resource
        private UserMapper userMapper;
    
        @Resource
        private 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
         */
        @Override
        public 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);// 创建一个get请求
            LoginDTO loginDTO = new LoginDTO(); // 存储下面http请求返回的结果
            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()); // 拿到openId,存入userDTO实体
                } 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位uuid
                user.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);
            }
            // 生成8位uuid作为登录的token,标识用户的登录信息
            userDTO.setToken(UuidUtil.getShortUuid());
            // 把用户登录信息存入redis中,定时1小时
            stringRedisTemplate.opsForValue().set("USER_" + userDTO.getToken(), JSON.toJSONString(userMapper.selectByPrimaryKey(userDTO.getId())), 3600, TimeUnit.SECONDS);
            return ResponseDTO.successByMsg(userDTO, "登录成功!");
        }
    
        
        /**
         * 获取当前登录用户
         * @param token
         * @return
         */
        @Override
        public 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
         */
        @Override
        public ResponseDTO<Boolean> logout(UserDTO userDTO) {
            if(!CommonUtil.isEmpty(userDTO.getToken())){
                // token不为空  清除redis中数据
                stringRedisTemplate.delete("USER_" + userDTO.getToken());
            }
            return ResponseDTO.successByMsg(true, "退出登录成功!");
        }
    
       
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151

    四、备注

    完整的配套代码资料获取请关注公众号:杨杨吖知识库,回复关键词:配套代码资料

  • 相关阅读:
    2023年数维杯国际大学生数学建模挑战赛
    DMSP/OLS夜间灯光数据
    Python编程从入门到实践 第九章:类 练习答案记录
    Linux安装Redis
    PRCV 2023 - Day2
    2024年腾讯云4核8G云服务器性能测评和优惠价格表
    变量名命名的艺术
    一、Flume使用
    hive shell中有许多日志信息的解决办法
    TYVJ P1023 奶牛的锻炼
  • 原文地址:https://blog.csdn.net/dgfdhgghd/article/details/133546587