美文网首页
对接腾讯的企业微信API发送IM消息通知

对接腾讯的企业微信API发送IM消息通知

作者: 天草二十六_简村人 | 来源:发表于2023-03-23 17:17 被阅读0次

    一、背景

    在我们的DevOps过程中,总绕不开需要给开发或测试发送消息,推荐的是企业微信、钉钉消息等,而不是SMS短信或email邮件。

    本文将详细描述如何使用java语言来实现消息的推送。

    开发前,建议看清楚官方文档:https://developer.work.weixin.qq.com/document/path/90665

    二、引入三方jar包

            <dependency>
                <groupId>com.github.binarywang</groupId>
                <artifactId>wx-java-cp-spring-boot-starter</artifactId>
                <version>4.4.0</version>
            </dependency>
    

    配置必填项

    # 企业微信号配置(必填)
    wx:
      cp:
        corp-id: xxx
        corp-secret: xxx
        agent-id: 1000001
    

    三、调用发送消息

    支持标签和手机号两种方式。详见文档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;
    
        // 标签名称
        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("根据手机号获取userId出现异常", e);
            }
        }
    
        public void send(String userId, String tagName, String content) {
            // 根据tag反查tagId
            WxCpMessage wxCpMessage = new WxCpMessage();
            // 设置发送用户, 多个接收者用‘|’分隔
            if (StringUtils.isNotEmpty(userId)) {
                wxCpMessage.setToUser(userId);
            } else if (StringUtils.isNotEmpty(tagName)) {
                String tagId = getTagId(tagName);
                wxCpMessage.setToTag(tagId);
            } else {
                return;
            }
    
            // 设置发送主体
            wxCpMessage.setContent(content);
            // 设置发送信息类型
            wxCpMessage.setMsgType("markdown");
    
            try {
                WxCpMessageSendResult result = wxCpService.getMessageService().send(wxCpMessage);
                if (0 != result.getErrCode()) {
                    log.warn("发送企业微信消息失败,content={}, 返回:{}", content, JSON.toJSONString(result));
                }
            } catch (Exception e) {
                log.error("发送企业微信消息出现异常", 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("企业微信获取tag标签列表,出现异常", e);
                throw new IllegalArgumentException("企业微信获取tag标签列表,出现异常");
            }
        }
    }
    
    

    四、总结

    • 标签ID,不是标签名称。我们是有界面,专门管理企业微信的标签列表。对外使用的都是标签名称,接口层面对应的则是标签ID。
    image.png
    • userId,需通过手机号反查出userId。一般我们公司范围内,账户都会支持按手机号来登录,便于维护和管理。

    五、其他

    本次使用到的三方包,还可以用到获取许多企业微信的相关信息,这里仅指出发送消息这一小点。

    相关文章

      网友评论

          本文标题:对接腾讯的企业微信API发送IM消息通知

          本文链接:https://www.haomeiwen.com/subject/cwbirdtx.html