使用工具类
https://gitee.com/binary/weixin-java-tools
1 pom引用
<!-- 企业微信工具集 https://mvnrepository.com/artifact/com.github.binarywang/wx-java -->
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-cp</artifactId>
<version>3.9.0</version>
</dependency>
2 增加配置 application.yml
普通企业微信不需要配置baseApiUrl / oauth2redirectUri
# 微信相关
wechat:
# 私有部署企业微信
privatecp:
corpId: wwxxxxxxxxxx
baseApiUrl: http://127.0.0.1:161
oauth2redirectUri: http://127.0.0.1:161
# 应用配置
appConfigs:
- agentId: 1000001
secret: xxxxxxxxxxxxxxxxxxxxx
- agentId: 1000002
secret: xxxxxxxxxxxxxxxxxxxxx
3 增加配置信息类
package com.xxx.auth.config;
import java.util.List;
import com.xxx.auth.urils.JsonUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import lombok.Getter;
import lombok.Setter;
/**
* @author GuanWeiMail@163.com
*/
@Getter
@Setter
@ConfigurationProperties(prefix = "wechat.privatecp")
public class WxCpPrivateProperties {
/**
* 设置微信企业号的corpId
*/
private String corpId;
/**
* 基础api域名
*/
private String baseApiUrl;
/**
* oauth2 网页授权请求域名
*/
private String oauth2redirectUri;
/**
* 应用配置集合
*/
private List<AppConfig> appConfigs;
@Getter
@Setter
public static class AppConfig {
/**
* 设置微信企业应用的AgentId
*/
private Integer agentId;
/**
* 设置微信企业应用的Secret
*/
private String secret;
/**
* 设置微信企业号的token
*/
private String token;
/**
* 设置微信企业号的EncodingAESKey
*/
private String aesKey;
}
@Override
public String toString() {
return JsonUtils.toJson(this);
}
}
工具类
package com.tpln.auth.urils;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
/**
*
* Json工具类
* @author
*/
public class JsonUtils {
private static final ObjectMapper JSON = new ObjectMapper();
static {
JSON.setSerializationInclusion(Include.NON_NULL);
JSON.configure(SerializationFeature.INDENT_OUTPUT, Boolean.TRUE);
}
public static String toJson(Object obj) {
try {
return JSON.writeValueAsString(obj);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
}
4 增加配置类
普通企业微信不需要配置baseApiUrl / oauth2redirectUri
package com.xxx.auth.config;
import java.util.Map;
import java.util.stream.Collectors;
import javax.annotation.PostConstruct;
import me.chanjar.weixin.cp.config.impl.WxCpDefaultConfigImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import com.google.common.collect.Maps;
import lombok.val;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.api.impl.WxCpServiceImpl;
import me.chanjar.weixin.cp.message.WxCpMessageRouter;
/**
* @Title: 私有部署企业微信配置类
* @Description: 集成企业微信认证
* @Version: v1.0
* @Author: Mr.Guan
* @Mail GuanWeiMail@163.com
* @DateTime: 2020-09-08 20:01:04
* @Package com.xxx.auth.config
*/
@Configuration
@EnableConfigurationProperties(WxCpPrivateProperties.class)
public class WxCpPrivateConfiguration {
/**
* 配置信息
*/
private WxCpPrivateProperties properties;
private static Map<Integer, WxCpMessageRouter> routers = Maps.newHashMap();
private static Map<Integer, WxCpService> cpServices = Maps.newHashMap();
@Autowired
public WxCpPrivateConfiguration(WxCpPrivateProperties properties) {
this.properties = properties;
}
public static Map<Integer, WxCpMessageRouter> getRouters() {
return routers;
}
public static WxCpService getCpService(Integer agentId) {
return cpServices.get(agentId);
}
/**
* 初始化Services
* 初始化多个企业应用
*/
@PostConstruct
public void initServices() {
cpServices = this.properties.getAppConfigs().stream().map(appConfig -> {
val configStorage = new WxCpDefaultConfigImpl();
//普通企业微信不需要配置baseApiUrl / oauth2redirectUri
configStorage.setBaseApiUrl(this.properties.getBaseApiUrl());
configStorage.setOauth2redirectUri(this.properties.getOauth2redirectUri());
configStorage.setCorpId(this.properties.getCorpId());
configStorage.setAgentId(appConfig.getAgentId());
configStorage.setCorpSecret(appConfig.getSecret());
configStorage.setToken(appConfig.getToken());
configStorage.setAesKey(appConfig.getAesKey());
val service = new WxCpServiceImpl();
service.setWxCpConfigStorage(configStorage);
routers.put(appConfig.getAgentId(), this.newRouter(service));
return service;
}).collect(Collectors.toMap(service -> service.getWxCpConfigStorage().getAgentId(), a -> a));
}
private WxCpMessageRouter newRouter(WxCpService wxCpService) {
final val newRouter = new WxCpMessageRouter(wxCpService);
return newRouter;
}
}
5 网页授权地址
http://127.0.0.1:161/connect/oauth2/authorize?appid=wwxxxxxxxxxx&redirect_uri=http://服务器ip:8889/auth/callback/WECHAT_ENTERPRISE&response_type=code&scope=SCOPE&agentid=1000001&state=STATE#wechat_redirect
参考
package com.xxx.auth.controller;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.xxx.auth.config.WxCpPrivateConfiguration;
import com.xxx.auth.emnu.SourceInfoEnum;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.WxCpOauth2UserInfo;
import me.chanjar.weixin.cp.bean.WxCpUser;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
/**
* @Title: 认证Controller
* @Description: 描述
* @Version: v1.0
* @Author: Mr.Guan
* @Mail GuanWeiMail@163.com
* @DateTime: 2020-08-24 20:01:04
*/
@RestController
@RequestMapping("auth")
public class AuthController {
public static void main(String[] args) {
System.out.println(SourceInfoEnum.valueOf("WECHAT_ENTERPRISE"));
}
/**
* auth平台中配置的授权回调地址
* 以本项目为例,在创建"企业微信"授权应用时的回调地址应为:http://127.0.0.1:8443/auth/callback/wechat_enterprise?callback=
* 企业微信免登陆
* 获取企业用户信息 关联子系统用户 实现免登
* @param request
* @param source 请求来源:WECHAT_ENTERPRISE:企业微信
* @return
* @throws Exception
*/
@RequestMapping("callback/{source}")
public Object login(HttpServletRequest request, @PathVariable("source") String source) throws Exception{
//获取请求参数
Map<String, String[]> parameterMap = request.getParameterMap();
System.out.println(JSONUtil.parse(parameterMap).toStringPretty());
if(StrUtil.isBlank(source)){
return "error";
}
switch (SourceInfoEnum.valueOf(source)){
// 企业微信
case WECHAT_ENTERPRISE:
String code = parameterMap.get("code")[0];
//获取微信服务
WxCpService wxCpService = WxCpPrivateConfiguration.getCpService(1000001);
//获取用户ID
WxCpOauth2UserInfo userInfo = wxCpService.getOauth2Service().getUserInfo(code);
System.out.println(JSONUtil.parse(userInfo).toStringPretty());
//获取通讯录
// List<WxCpDepart> list = wxCpService.getDepartmentService().list(1L);
// for (WxCpDepart wxCpDepart : list) {
// List<WxCpUser> wxCpUsers = wxCpService.getUserService().listByDepartment(wxCpDepart.getId(), false, 0);
// System.out.println(JSONUtil.parse(wxCpDepart).toStringPretty());
// System.out.println(JSONUtil.parse(wxCpUsers).toStringPretty());
// }
//获取用户明细信息
WxCpUser byId = wxCpService.getUserService().getById(userInfo.getUserId());
System.out.println(byId);
//判断子系统是否存在该用户, 存在则直接免登, 生成 token 存入session / redis
//不存在则创建用户
break;
default:
break;
}
return "ok";
}
}