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;
|
}
|
}
|
}
|