当前位置: 首页 > news >正文

Java 推送钉钉应用消息

前言:

本文的目的是通过手机号获取钉钉成员的userid,实现钉钉应用的消息推送。

一、创建钉钉应用

登录钉钉开放平台

二、应用相关凭证

需要获取

Client ID (原 AppKey 和 SuiteKey)

Client Secret (原 AppSecret 和 SuiteSecret)

App ID 

原企业内部应用AgentId

三、申请钉钉接口权限

需要先申请对应的接口权限才能调用接口。

但是钉钉的接口太多了,一时半会也找不到对应的接口,推荐直接全勾选。

四、钉钉官方接口

1、获取token

请求方式:GET

参数:appKey,appSecret,reqMethod

url:https://oapi.dingtalk.com/gettoken

2、根据手机号获取用户ID

参数:access_token,mobileNum

url:https://oapi.dingtalk.com/topapi/v2/user/getbymobile

3、发送通知

参数:access_token,msgType,content,userId

url:https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2

五、工具类

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiGettokenRequest;
import com.dingtalk.api.request.OapiMessageCorpconversationAsyncsendV2Request;
import com.dingtalk.api.request.OapiV2UserGetbymobileRequest;
import com.dingtalk.api.response.OapiGettokenResponse;
import com.dingtalk.api.response.OapiMessageCorpconversationAsyncsendV2Response;
import com.dingtalk.api.response.OapiV2UserGetbymobileResponse;
import com.taobao.api.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Component
public class DingTalkUtil {

    private static final String GET_TOKEN_URL = "https://oapi.dingtalk.com/gettoken";
    private static final String GET_BY_MOBILE = "https://oapi.dingtalk.com/topapi/v2/user/getbymobile";
    private static final String ASYNC_SEND_V2_URL = "https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2";
    private static final String DEFAULT_APP_KEY = "XXX";
    private static final String DEFAULT_APP_SECRET = "XXXX";
    private static final Long DEFAULT_AGENT_ID = 123L;
    private static final String DEFAULT_REQUEST_METHOD = "GET";

    private String appKey;
    private String appSecret;
    private Long agentId;
    private String reqMethod;


    public DingTalkUtil() {
        this(DEFAULT_APP_KEY, DEFAULT_APP_SECRET, DEFAULT_AGENT_ID, DEFAULT_REQUEST_METHOD);
    }

    public DingTalkUtil(String appKey, String appSecret, Long agentId, String reqMethod) {
        this.appKey = (appKey != null && !appKey.isEmpty()) ? appKey : DEFAULT_APP_KEY;
        this.appSecret = (appSecret != null && !appSecret.isEmpty()) ? appSecret : DEFAULT_APP_SECRET;
        this.agentId = (agentId != null) ? agentId : DEFAULT_AGENT_ID;
        this.reqMethod = (reqMethod != null && !reqMethod.isEmpty()) ? reqMethod : DEFAULT_REQUEST_METHOD;
    }


    // 获取AccessToken
    public String getTokenResponse() throws ApiException {
        DingTalkClient client = new DefaultDingTalkClient(GET_TOKEN_URL);
        OapiGettokenRequest req = new OapiGettokenRequest();
        req.setAppkey(appKey);
        req.setAppsecret(appSecret);
        req.setHttpMethod(reqMethod);
        OapiGettokenResponse rsp = client.execute(req);
        return rsp.getAccessToken();
    }

    // 根据手机号获取UserId
    public String getUserIdByMobile(String accessToken, String mobileNum) throws ApiException {
        DingTalkClient client = new DefaultDingTalkClient(GET_BY_MOBILE);
        OapiV2UserGetbymobileRequest req = new OapiV2UserGetbymobileRequest();
        req.setMobile(mobileNum);
        OapiV2UserGetbymobileResponse rsp = client.execute(req, accessToken);

        JSONObject jsonObject = JSON.parseObject(rsp.getBody());
        JSONObject result = jsonObject.getJSONObject("result");
        String userid = result.getString("userid");
        return userid;
    }

    // 发送工作通知消息
    public boolean sendWorkNotice(String accessToken, String msgType, String content, List<String> userIds) throws ApiException {
        DingTalkClient client = new DefaultDingTalkClient(ASYNC_SEND_V2_URL);

        OapiMessageCorpconversationAsyncsendV2Request req = new OapiMessageCorpconversationAsyncsendV2Request();
        req.setAgentId(agentId);
        req.setUseridList(String.join(",", userIds));

        OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
        msg.setMsgtype(msgType);
        OapiMessageCorpconversationAsyncsendV2Request.Text text = new OapiMessageCorpconversationAsyncsendV2Request.Text();
        text.setContent(content);
        msg.setText(text);

        req.setMsg(msg);

        OapiMessageCorpconversationAsyncsendV2Response rsp = client.execute(req, accessToken);
        return rsp.isSuccess();
    }

    public static class Builder {
        private String msgType = "text";
        private String content;
        private List<String> mobiles = new ArrayList<>();
        private List<String> userIds = new ArrayList<>();

        public Builder setMsgType(String msgType) {
            this.msgType = msgType;
            return this;
        }

        public Builder setContent(String content) {
            this.content = content;
            return this;
        }

        public Builder addUserId(String userId) {
            this.mobiles.add(userId);
            return this;
        }

        public Builder addUserIds(List<String> userIds) {
            this.mobiles = userIds;
            return this;
        }

        public boolean send(DingTalkUtil utils) throws ApiException {
            // 获取 accessToken
            String accessToken = utils.getTokenResponse();
            // 根据手机获取userId
            for (String mobileNum : mobiles) {
                String userId = utils.getUserIdByMobile(accessToken, mobileNum);
                userIds.add(userId);
            }
            // 调用 sendWorkNotice 发送消息
            return utils.sendWorkNotice(accessToken, msgType, content, userIds);
        }
    }


    // 封装的发送钉钉通知的方法
    public boolean sendDingTalkNotification(List<String> phoneList, String message) throws ApiException {
        DingTalkUtil dingTalkUtil = new DingTalkUtil();
        return new DingTalkUtil.Builder().setMsgType("text")
                .setContent(message)
                .addUserIds(phoneList)
                .send(dingTalkUtil);
    }

    // 内部测试
    public static void main(String[] args) throws ApiException {
        DingTalkUtil dingTalkUtil = new DingTalkUtil();
        List<String> phoneList = Arrays.asList("phoneNum");
        String message = "your message";
        boolean result = dingTalkUtil.sendDingTalkNotification(phoneList, message);
        System.out.println("消息发送结果: " + result);
    }

}

相关文章:

  • MyBatis 的缓存机制 笔记250320
  • 【排序算法】——快速排序
  • 数据分析异步进阶:aiohttp与Asyncio性能提升
  • Kafka自定义分区机制
  • HTTP和RPC的区别
  • 稳定运行的以Microsoft Azure SQL database数据库为数据源和目标的ETL性能变差时提高性能方法和步骤
  • 大模型之蒸馏模型
  • HashMap添加元素的流程图
  • Fiddler使用(一)
  • 嵌入式八股,什么是线程安全
  • 稀疏矩阵的存储
  • 美团 web 最新 mtgsig1.2
  • Spring MVC 拦截器使用
  • 大模型详细配置
  • 人工智能之数学基础:线性方程组求解的得力助手——增广矩阵
  • HarmonyOS Next~鸿蒙系统架构设计解析:分层、模块化与智慧分发的技术革新
  • DeDeCMS靶场攻略
  • pytest的测试报告allure
  • MongoDB 配合python使用的入门教程
  • 微软产品的专有名词和官方视频教程
  • “异常”只停留在医院里,用艺术为“泡泡宝贝”加油
  • 宝通科技:与宇树合作已签约,四足机器人在工业场景落地是重点商业化项目
  • 美国和沙特签署上千亿美元军售协议
  • 浙江公开征集涉企行政执法问题线索,包括乱收费、乱罚款等
  • 云南多地突查公职人员违规饮酒:公安局门口开展酒精吹气测试
  • 印巴战火LIVE丨“快速接近战争状态”?印度袭击巴军事基地,巴启动反制军事行动