以下是实现的pc端企微扫码登陆,话不多时,直接上代码。。。
整体流程:
1.企业发起授权登录请求,企业微信用户允许授权后,企业微信会重定向到企业网站,并且带上授权临时票据code参数;
2.然后企业应用通过 corpid 和 corpsecret 获取access_token ;
3.企业应用通过 access_token 和 code 获取用户身份,进入相应的系统。
相关的代码 如下:
1.通过后端获取到信息,前端加载二维码
/**
* 加载二维码
*
* @return
*/
@GetMapping("getWecom")
@ApiOperation("企微登陆获取二维码信息")
@ResponseBody
public AjaxResult getErWeiMa() throws UnsupportedEncodingException {
AjaxResult res = new AjaxResult();
res.setData(qwWeiXinUtil.loginGetErWeiMa());
return res;
}
2.根据返回的code与accessToken获取用户信息
@GetMapping("loginQwOrGetInfo")
@ApiOperation("回调并获取用户信息")
public AjaxResult getCode(HttpServletRequest request, String code) {
if(StringUtils.isEmpty(code)){
AjaxResult.error("请重新扫码登陆");
}
try {
AjaxResult ajax = AjaxResult.success();
//todo 此处是前端传入code
String userId = qwWeiXinUtil.getUserID(code);
WeiXinUserInfoDTO weiXinUserInfoDTO = qwWeiXinUtil.getUserInfo(userId);
//获取到手机号并与库中关联并生成令牌
String token = loginService.loginByWecom(weiXinUserInfoDTO.getMobile());
log.info(token);
ajax.setData(token);
return ajax;
} catch (Exception e) {
return AjaxResult.error(e.getMessage());
}
}
以下是用到的相关的工具类
package com.cogo.framework.util;
import com.alibaba.fastjson.JSONObject;
import com.cogo.common.core.redis.RedisCache;
import com.cogo.common.utils.StringUtils;
import com.cogo.core.domain.vo.WeiXinLoginDTO;
import com.cogo.core.domain.vo.WeiXinUserInfoDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;
@Component
@Slf4j
public class QwWeiXinUtil {
@Autowired
private RedisCache redisCache;
@Autowired
private WecomUtil wecomUtil;
/**
* 获取用户ID
*
* @param accessToken
* @param code
* @return
*/
public String getUserIDByToken(String accessToken, String code) {
//1.获取请求的url
String url = wecomUtil.getUserIDUrl.replace("ACCESS_TOKEN", accessToken)
.replace("CODE", code);
//2.调用接口,发送请求,获取成员
JSONObject jsonObject = SendRequest.sendGet(url);
//3.错误消息处理
if (null != jsonObject && 0 != jsonObject.getIntValue("errcode")) {
log.error("获取成员失败 errcode:{} errmsg:{}", jsonObject.getIntValue("errcode"), jsonObject.getString("errmsg"));
} else {
log.info("用户ID:" + jsonObject.getString("UserId"));
log.info("OpenID:" + jsonObject.getString("OpenId"));
if (!StringUtils.isEmpty(jsonObject.getString("UserId"))) {
return jsonObject.getString("UserId");
} else if (jsonObject.getString("OpenId") != null) {
log.info("该用户不是本企业人员,OpenID为:" + jsonObject.getString("OpenId"));
return null;
}
}
return null;
}
/**
* 初始加载二维码
*
* @return
* @throws UnsupportedEncodingException
*/
public WeiXinLoginDTO loginGetErWeiMa() throws UnsupportedEncodingException {
String redirect_uri = URLEncoder.encode(wecomUtil.redirectUri, "utf-8");
WeiXinLoginDTO weiXinLoginDTO = new WeiXinLoginDTO();
weiXinLoginDTO.setAppid(wecomUtil.appId);
weiXinLoginDTO.setAgentid(wecomUtil.agentId);
weiXinLoginDTO.setRedirectUri(redirect_uri);
return weiXinLoginDTO;
}
/**
* 获取token
*
* @return
*/
public String getToken() {
String token = getFirstAccessToken(wecomUtil.appId, wecomUtil.secret);
redisCache.setCacheObject("qwChatToken", token, 100, TimeUnit.SECONDS);
return token;
}
/**
* 获取token
*
* @param appid
* @param appsecret
* @return
*/
public String getFirstAccessToken(String appid, String appsecret) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String saveDate = sdf.format(new Date());
log.info("获取微信TOKN请求开始,当前时间:" + saveDate);
String requestUrl = wecomUtil.accessTokenUrl.replace("{corpId}", appid)
.replace("{corpsecret}", appsecret);
JSONObject jsonObject = SendRequest.sendGet(requestUrl);
// 如果请求成功
if (null != jsonObject && jsonObject.getIntValue("errcode") == 0) {
try {
log.info("获取的token: " + jsonObject.getString("access_token"));
log.info("时间" + saveDate);
return jsonObject.getString("access_token");
} catch (Exception e) {
// 获取token失败
log.error("获取token失败 errcode:{} errmsg:{}",jsonObject.getString("errmsg"));
}
} else {
log.error("获取token失败 errcode:{} errmsg:{}",jsonObject.getString("errmsg"));
}
return null;
}
/**
* 获取用户
*
* @param accessToken
* @param userId
* @return
*/
public WeiXinUserInfoDTO getUserInfoByID(String accessToken, String userId) {
//1.获取请求的url
String url = wecomUtil.getUserUrl.replace("ACCESS_TOKEN", accessToken)
.replace("USERID", userId);
//2.调用接口,发送请求,获取成员
JSONObject jsonObject = SendRequest.sendGet(url);
//3.错误消息处理
if (null != jsonObject && 0 != jsonObject.getIntValue("errcode")) {
log.error("获取成员失败 errcode:{} errmsg:{}", jsonObject.getIntValue("errcode"), jsonObject.getString("errmsg"));
} else {
log.info("用户ID:" + jsonObject.getString("userid"));
log.info("用户名称:" + jsonObject.getString("name"));
log.info("用户手机号:" + jsonObject.getString("mobile"));
log.info("用户邮箱:" + jsonObject.getString("email"));
WeiXinUserInfoDTO weiXinUserInfoDTO = new WeiXinUserInfoDTO();
weiXinUserInfoDTO.setUserid(jsonObject.getString("userid"));
weiXinUserInfoDTO.setName(jsonObject.getString("name"));
weiXinUserInfoDTO.setMobile(jsonObject.getString("mobile"));
weiXinUserInfoDTO.setEmail(jsonObject.getString("email"));
weiXinUserInfoDTO.setAvatar(jsonObject.getString("avatar"));//头像
weiXinUserInfoDTO.setEnable(jsonObject.getString("enables"));//成员启用状态。1表示启用的成员,0表示被禁用。注意,服务商调用接口不会返回此字段
return weiXinUserInfoDTO;
}
return null;
}
/**
* 获取用户ID
*
* @param code
*/
public String getUserID(String code) {
log.info("code:" + code);
//逻辑判断token是否过期,如果过期刷新,没有过期直接拿来使用
Object qwChatToken = redisCache.getCacheObject("qwChatToken");
String token =qwChatToken !=null ? qwChatToken.toString() : this.getToken();
return this.getUserIDByToken(token, code);
}
/**
* 获取用户信息
*
* @param userId
* @return
*/
public WeiXinUserInfoDTO getUserInfo(String userId) {
//逻辑判断token是否过期,如果过期刷新,没有过期直接拿来使用
String token = this.getToken();
//根据userID和token获取用户的基本信息
WeiXinUserInfoDTO weiXinUserInfoDTO = this.getUserInfoByID(token, userId);
return weiXinUserInfoDTO;
}
}
获取配置的工具类
package com.cogo.framework.util;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
/**
* 微信配置
*
* @author wangjunjie
* @version 1.0
* @date 2023/5/30 20:50
*/
@Configuration
public class WecomUtil {
//企业ID
@Value("${qwchat.appId}")
public String appId;
//应用AgentId
@Value("${qwchat.agentId}")
public String agentId;
//第三方网站指定自己的端口
@Value("${qwchat.redirectUri}")
public String redirectUri;
@Value("${qwchat.secret}")
public String secret;
public String accessTokenUrl;
@Value("${qwchat.accessTokenUrl}")
public void setAccessTokenUrl(String accessTokenUrl) {
this.accessTokenUrl = accessTokenUrl;
}
public String getUserIDUrl;
@Value("${qwchat.getUserIDUrl}")
public void setGetUserIDUrl(String getUserIDUrl) {
this.getUserIDUrl = getUserIDUrl;
}
public String getUserUrl;
@Value("${qwchat.getUserUrl}")
public void setGetUserUrl(String getUserUrl) {
this.getUserUrl = getUserUrl;
}
}