wlzboy
6 天以前 3bbd80a63ac7728ac01b641a48a26befcb171a0f
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
package com.ruoyi.web.controller.system;
 
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.framework.web.service.QyWechatLoginService;
import com.ruoyi.system.service.IQyWechatAccessTokenService;
import com.ruoyi.system.service.IQyWechatService;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
 
import java.util.HashMap;
import java.util.Map;
 
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
 
/**
 * 企业微信免登控制器
 * 
 * @author ruoyi
 * @date 2025-12-14
 */
@RestController
@RequestMapping("/system/qywechat")
public class QyWechatLoginController extends BaseController {
    
    private static final Logger log = LoggerFactory.getLogger(QyWechatLoginController.class);
    
    @Autowired
    private IQyWechatAccessTokenService qyWechatAccessTokenService;
    
    @Autowired
    private IQyWechatService qyWechatService;
    
    @Autowired
    private ISysConfigService configService;
    
    @Autowired
    private ISysUserService userService;
    
    @Autowired
    private QyWechatLoginService qyWechatLoginService;
    
    /**
     * 企业微信免登接口
     * 
     * @param params 企业微信授权code
     * @return 登录结果
     */
    @Anonymous
    @PostMapping("/autoLogin")
    public AjaxResult autoLogin(@RequestBody Map<String, String> params) {
        try {
            String code = params.get("code");
            
            if (code == null || code.isEmpty()) {
                return AjaxResult.error("缺少授权code参数");
            }
            
            // 获取企业微信配置
            String corpId = configService.selectConfigByKey("qy_wechat.corp_id");
            // 获取企业微信小程序的secret(用于获取AccessToken)
            String miniProgramSecret = configService.selectConfigByKey("qy_wechat.miniprogram_secret");
            
            if (corpId == null || miniProgramSecret == null) {
                return AjaxResult.error("企业微信配置不完整,请检查corp_id和miniprogram_secret配置");
            }
            
            // 获取AccessToken(使用小程序的secret)
            String accessToken = qyWechatAccessTokenService.getQyMiniAccessToken(corpId, miniProgramSecret);
            if (accessToken == null) {
                return AjaxResult.error("获取企业微信AccessToken失败");
            }
            
            // 通过code获取用户信息
            Map<String, Object> userInfo = getUserInfoByCode(accessToken, code);
            if (!((Boolean) userInfo.get("success"))) {
                return AjaxResult.error((String) userInfo.get("message"));
            }
            
            // 获取用户ID
            String userId = (String) userInfo.get("userid");
            
            // 根据企业微信用户ID查找系统用户
            SysUser sysUser = userService.selectUserByQyWechatUserId(userId);
            if (sysUser == null) {
                return AjaxResult.error("该企业微信账号未绑定系统用户");
            }
            
            // 检查用户状态
            if ("1".equals(sysUser.getStatus())) {
                return AjaxResult.error("用户已被停用,请联系管理员");
            }
            
            if ("1".equals(sysUser.getDelFlag())) {
                return AjaxResult.error("用户已被删除,请联系管理员");
            }
            
            // 使用QyWechatLoginService生成token
            String token = qyWechatLoginService.loginByQyUserId(userId, corpId);
            
            // 构造返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("token", token);
            result.put("user", sysUser);
            
            return AjaxResult.success("登录成功", result);
        } catch (Exception e) {
            log.error("企业微信免登异常", e);
            return AjaxResult.error("登录异常:" + e.getMessage());
        }
    }
    
    /**
     * 根据code获取用户信息
     * 
     * @param accessToken AccessToken
     * @param code 授权code
     * @return 用户信息
     */
    private Map<String, Object> getUserInfoByCode(String accessToken, String code) {
        try {
            Map<String, Object> result = new HashMap<>();
            
            // 构造请求URL - 使用企业微信小程序专用接口
            String url = "https://qyapi.weixin.qq.com/cgi-bin/miniprogram/jscode2session?access_token=" + accessToken + "&js_code=" + code + "&grant_type=authorization_code";
            
            // 发送HTTP GET请求
            String response = sendHttpGetRequest(url);
            if (response == null || response.isEmpty()) {
                result.put("success", false);
                result.put("message", "获取用户信息失败,响应为空");
                return result;
            }
            
            // 使用FastJSON解析响应
            JSONObject jsonResponse = JSON.parseObject(response);
            
            // 检查是否有错误
            Integer errcode = jsonResponse.getInteger("errcode");
            if (errcode != null && errcode != 0) {
                String errmsg = jsonResponse.getString("errmsg");
                result.put("success", false);
                result.put("message", "获取用户信息失败,错误码:" + errcode + ",错误信息:" + errmsg);
                return result;
            }
            
            // 检查是否包含userid字段
            String userId = jsonResponse.getString("userid");
            if (userId == null || userId.isEmpty()) {
                result.put("success", false);
                result.put("message", "获取用户信息失败,未找到用户ID");
                return result;
            }
            
            result.put("success", true);
            result.put("userid", userId);
            result.put("corpid", jsonResponse.getString("corpid"));
            result.put("session_key", jsonResponse.getString("session_key"));
            
            return result;
        } catch (Exception e) {
            log.error("获取用户信息异常", e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "获取用户信息异常:" + e.getMessage());
            return result;
        }
    }
    
    /**
     * 发送HTTP GET请求
     * 
     * @param url 请求URL
     * @return 响应内容
     */
    private String sendHttpGetRequest(String url) {
        try {
            java.net.HttpURLConnection conn = (java.net.HttpURLConnection) new java.net.URL(url).openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(5000);
            
            int responseCode = conn.getResponseCode();
            if (responseCode == 200) {
                java.io.BufferedReader reader = new java.io.BufferedReader(
                    new java.io.InputStreamReader(conn.getInputStream(), "UTF-8"));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();
                return response.toString();
            } else {
                log.error("HTTP请求失败,响应码: {}", responseCode);
                return null;
            }
        } catch (Exception e) {
            log.error("发送HTTP请求失败", e);
            return null;
        }
    }
}