weixin-java sdk对接企业微信,会话内容存档踩坑

897 阅读2分钟

前言

用的Binary Wang(gitee.com/binary/weix…) 的wx-java包,所以,官网的Finance.java你不用看了,官网的目录com.tencent.wework你也不用创建了.

完整的项目建议直接下载binary的demo包就行~ weixin-java-cp-demo

<dependency>
    <groupId>com.github.binarywang</groupId>
    <artifactId>weixin-java-cp</artifactId>
    <version>4.3.0</version>
</dependency>

官网文档,顺便下载好sdk

https://developer.work.weixin.qq.com/document/path/91774

1.开发

初始化你的wxcp service

@PostConstruct
public void initServices() {
    cpServices = this.properties.getAppConfigs().stream().map(a -> {
        val configStorage = new WxCpDefaultConfigImpl();
        configStorage.setCorpId(this.properties.getCorpId());
        configStorage.setAgentId(a.getAgentId());
        configStorage.setCorpSecret(a.getSecret());
        configStorage.setToken(a.getToken());
        configStorage.setAesKey(a.getAesKey());

        if (Finance.isWindows()){
            //四个dll文件 一定要放在 C:\Windows\System32 下!!!!!
           //FileUtil是 hutool的,wecome是resource下面的文件夹~
           configStorage.setMsgAuditLibPath(FileUtil.getAbsolutePath("wecome\win\WeWorkFinanceSdk.dll"));
        }else{
            configStorage.setMsgAuditLibPath(libPath);
        }
        val service = new WxCpServiceImpl();
        service.setWxCpConfigStorage(configStorage);
        routers.put(a.getAgentId(), this.newRouter(service));
        return service;
    }).collect(Collectors.toMap(service -> service.getWxCpConfigStorage().getAgentId(), a -> a));
}

win环境开发

1.把下载好的sdk,解压出来,只取里面的四个“dll”文件即可;
2.把四个dll文件放在 C:\Windows\System32(也可以放在别的library目录,通过System.getProperty("java.library.path")获取)
3.再把这四个dll文件放在你的项目下,我的处理是 放在resource目录下,然后程序跑的时候加载它的绝对路径~

mac环境开发

一边去吧,没你的事 ~ 会报错 not a match-o file

获取会话内容

//指定一个应用id去拿到对应的service
long seq = 0L;
final WxCpService wxCpService = WxCpConfiguration.getCpService(Integer.valueOf("你的agentId"));
WxCpChatDatas chatDatas = wxCpService.getMsgAuditService().getChatDatas(seq, 100, null, null, 60);
List<WxCpChatDatas.WxCpChatData> chatData = chatDatas.getChatData();
for (WxCpChatDatas.WxCpChatData chatDatum : chatData) {
    try {
        //解密聊天信息
        WxCpChatModel decryptData = wxCpService.getMsgAuditService().getDecryptData(chatDatum);
        System.out.println("decryptData = " + JsonUtils.toJson(decryptData));
        
        //自行存储上次同步到的seq值
        seq++;
    }catch (Exception ignored){}
}

这里是我的文件放置目录,wecome在resource目录下

image.png

2. 部署

linux环境

1.把下载好的sdk,解压出来,只取里面的“libWeWorkFinanceSdk_Java.so”文件即可;
2.然后丢到你的服务器去,在代码里指定sdk的绝对路径即可

3.关于公钥私钥

  • 去这里,web.chacuo.net/netrsakeypa…,生成你的公钥和私钥(PKCS#8,2048bit),配在企微后台,注意不同的公钥是有不同的public_ver版本的

  • 公钥填写在企微后台,私钥写在你的配置文件里面

  • 私钥配置文件要换行怎么写进去application.properties? 加个换行符就行了 springboot yml配置文件中换行问题

image.png

4. 获取企业会话有一个专门的agentID,找对应的人拿就行了

5.收藏下别人写的

企业微信-会话内容存档(从零开始,完整demo)_不正经壁纸的博客-CSDN博客

企业微信会话存档Java SDK使用 - 掘金 (juejin.cn)