一、背景
在我們的DevOps過程中,總繞不開需要給開發(fā)或測試發(fā)送消息,推薦的是企業(yè)微信、釘釘消息等,而不是SMS短信或email郵件。
本文將詳細描述如何使用java語言來實現(xiàn)消息的推送。
開發(fā)前,建議看清楚官方文檔:https://developer.work.weixin.qq.com/document/path/90665
二、引入三方j(luò)ar包
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>wx-java-cp-spring-boot-starter</artifactId>
<version>4.4.0</version>
</dependency>
配置必填項
# 企業(yè)微信號配置(必填)
wx:
cp:
corp-id: xxx
corp-secret: xxx
agent-id: 1000001
三、調(diào)用發(fā)送消息
支持標(biāo)簽和手機號兩種方式。詳見文檔https://developer.work.weixin.qq.com/document/path/90236
直接上源碼示例:
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.WxCpTag;
import me.chanjar.weixin.cp.bean.message.WxCpMessage;
import me.chanjar.weixin.cp.bean.message.WxCpMessageSendResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Slf4j
@Service
public class WechatService {
@Autowired
private WxCpService wxCpService;
// 標(biāo)簽名稱
public void sendByTagName(String tagName, String content) {
this.send(null, tagName, content);
}
// 賬號是手機號
public void sendByAccount(String account, String content) {
try {
String userId = wxCpService.getUserService().getUserId(account);
this.send(userId, null, content);
} catch (Exception e) {
log.error("根據(jù)手機號獲取userId出現(xiàn)異常", e);
}
}
public void send(String userId, String tagName, String content) {
// 根據(jù)tag反查tagId
WxCpMessage wxCpMessage = new WxCpMessage();
// 設(shè)置發(fā)送用戶, 多個接收者用‘|’分隔
if (StringUtils.isNotEmpty(userId)) {
wxCpMessage.setToUser(userId);
} else if (StringUtils.isNotEmpty(tagName)) {
String tagId = getTagId(tagName);
wxCpMessage.setToTag(tagId);
} else {
return;
}
// 設(shè)置發(fā)送主體
wxCpMessage.setContent(content);
// 設(shè)置發(fā)送信息類型
wxCpMessage.setMsgType("markdown");
try {
WxCpMessageSendResult result = wxCpService.getMessageService().send(wxCpMessage);
if (0 != result.getErrCode()) {
log.warn("發(fā)送企業(yè)微信消息失敗,content={}, 返回:{}", content, JSON.toJSONString(result));
}
} catch (Exception e) {
log.error("發(fā)送企業(yè)微信消息出現(xiàn)異常", e);
}
}
private String getTagId(String tagName) {
try {
List<WxCpTag> tags = wxCpService.getTagService().listAll();
Map<String, String> tagMap = tags.stream().collect(
Collectors.toMap(WxCpTag::getName, WxCpTag::getId, (key1, key2) -> key2));
return tagMap.get(tagName);
} catch (Exception e) {
log.error("企業(yè)微信獲取tag標(biāo)簽列表,出現(xiàn)異常", e);
throw new IllegalArgumentException("企業(yè)微信獲取tag標(biāo)簽列表,出現(xiàn)異常");
}
}
}
四、總結(jié)
- 標(biāo)簽ID,不是標(biāo)簽名稱。我們是有界面,專門管理企業(yè)微信的標(biāo)簽列表。對外使用的都是標(biāo)簽名稱,接口層面對應(yīng)的則是標(biāo)簽ID。

image.png
- userId,需通過手機號反查出userId。一般我們公司范圍內(nèi),賬戶都會支持按手機號來登錄,便于維護和管理。
五、其他
本次使用到的三方包,還可以用到獲取許多企業(yè)微信的相關(guān)信息,這里僅指出發(fā)送消息這一小點。