企业微信获取用户信息
首先访问https://open.weixin.qq.com/connect/oauth2/authorize?appid=CORPID&redirect_uri=REDIRECT_URI&response_type=code&scope=snsapi_base&state=STATE&agentid=AGENTID#wechat_redirect根据重定向地址获取到code
//获取token
private String getWeChatAccessToken() { String accessToken = CacheUtil.get("wx_token", String.class); if (StringUtils.isBlank(accessToken)) { try { String wxUrl = wxAuthConfig.getGettokenUrl() + "?corpid=" + wxAuthConfig.getCorpid() + "&corpsecret=" + wxAuthConfig.getSecret(); WeChatTokenResponse tokenResponse = restTemplate.getForObject(wxUrl, WeChatTokenResponse.class); if (tokenResponse != null && tokenResponse.getErrcode() == 0) { accessToken = tokenResponse.getAccess_token(); // long expiresIn = tokenResponse.getExpires_in(); CacheUtil.put("wx_token", accessToken); // 支持过期时间 } else { throw new RuntimeException("获取 access_token 失败: " + tokenResponse.getErrmsg()); } } catch (Exception e) { throw new RuntimeException("请求微信获取 token 接口失败", e); } } return accessToken; }
根据重定向地址获取到的code和上面获取的token就能获取到访问用户的userId
//获取访问用户信息
private UserInfoResponse getUserInfo(String accessToken, String code) {
String url = wxAuthConfig.getGetuserinfoUrl() + "?access_token=" + accessToken + "&code=" + code;
try {
UserInfoResponse response = restTemplate.getForObject(url, UserInfoResponse.class);
if (response == null || response.getErrcode() != 0) {
throw new RuntimeException("获取用户信息失败: " + (response != null ? response.getErrmsg() : "空响应"));
}
return response;
} catch (Exception e) {
throw new RuntimeException("请求微信获取用户信息接口失败", e);
}
}
//获取用户详细信息
private UserInfoDetaiResponse getUserDetailInfo(String accessToken, String userId) {
String url = wxAuthConfig.getGetuserdetailUrl() + "?access_token=" + accessToken + "&userid=" + userId;
try {
UserInfoDetaiResponse response = restTemplate.getForObject(url, UserInfoDetaiResponse.class);
if (response == null || response.getErrcode() != 0) {
throw new RuntimeException("获取用户详情失败: " + (response != null ? response.getErrmsg() : "空响应"));
}
return response;
} catch (Exception e) {
throw new RuntimeException("请求微信获取用户详情接口失败", e);
}
}

浙公网安备 33010602011771号