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;}// 获取AccessTokenpublic 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();}// 根据手机号获取UserIdpublic 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 {// 获取 accessTokenString accessToken = utils.getTokenResponse();// 根据手机获取userIdfor (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);}}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/38531.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

SpringCloud介绍

什么是SpringCloud&#xff1f; SpringCloud 是分布式微服务架构下的一站式解决方案&#xff0c;是各个微服务架构落地技术的集合体&#xff0c;俗称微服务全家桶。 官方介绍&#xff1a; SpringCloud是基于SpringBoot提供了一套微服务解决方案&#xff0c;包括服务注册与发现…

YOLOv11 目标检测

本文章不再赘述anaconda的下载以及虚拟环境的配置&#xff0c;博主使用的python版本为3.8 1.获取YOLOv11的源工程文件 链接&#xff1a;GitHub - ultralytics/ultralytics: Ultralytics YOLO11 &#x1f680; 直接下载解压 2.需要自己准备的文件 文件结构如下&#xff1a;红…

【Linux】——环境变量与进程地址空间

文章目录 环境变量环境变量的概念常见的环境变量PATH相关指令 main的三个参数前两个参数第三个参数 程序地址空间进程地址空间 环境变量 环境变量的概念 环境变量一般是指在操作系统中用来指定操作系统运行环境的一些参数&#xff0c;将来会以shell的形式传递给所有进程&…

Kafka--常见问题

1.为什么要使用 Kafka&#xff0c;起到什么作用 Kafka是一个高吞吐量、分布式、基于发布订阅的消息系统&#xff0c;它主要用于处理实时数据流 Kafka 设计上支持高吞吐量的消息传输&#xff0c;每秒可以处理数百万条消息。它能够在处理大量并发请求时&#xff0c;保持低延迟和…

Flutter:页面滚动,导航栏背景颜色过渡动画

记录&#xff1a;导航默认透明&#xff0c;页面发生滚动后&#xff0c;导航背景色由0-1&#xff0c;过渡到白色背景。 view import package:ducafe_ui_core/ducafe_ui_core.dart; import package:flutter/material.dart; import package:get/get.dart; import package:redo…

探秘格式化:数据危机与恢复之道

引言 在数字化飞速发展的当下&#xff0c;数据已然成为我们生活中不可或缺的一部分。无论是珍贵的家庭照片、重要的工作文档&#xff0c;还是企业关键的业务数据&#xff0c;都承载着我们的回忆、努力和希望。然而&#xff0c;格式化这一操作却如同隐藏在数字世界中的“幽灵”…

人工智能 - 通用 AI Agent 之 LangManus、Manus、OpenManus 和 OWL 技术选型

一、核心项目概览 1. Manus(闭源通用 AI Agent) 定位 :全球首个全流程自动化通用 AI Agent,GAIA 基准测试 SOTA 水平。核心能力 : 全流程自动化 :从任务规划(如撰写报告)到执行(代码生成、表格制作)的端到端处理。智能纠错机制 :基于沙箱环境的实时错误反思与调整…

封装一个分割线组件

最终样式 Vue2代码 <template><div class"sep-line"><div class"sep-label"><span class"sep-box-text"><slot>{{ title }}</slot> <!-- 默认插槽内容&#xff0c;如果没有传递内容则使用title -->&…

走进Java:String字符串的基本使用

❀❀❀ 大佬求个关注吧~祝您开心每一天 ❀❀❀ 目录 一、什么是String 二、如何定义一个String 1. 用双引号定义 2. 通过构造函数定义 三、String中的一些常用方法 1 字符串比较 1.1 字符串使用 1.2 字符串使用equals() 1.3 使用 equalsIgnoreCase() 1.4 cpmpareTo…

第2.2节 Android Jacoco插件覆盖率采集

JaCoCo&#xff08;Java Code Coverage&#xff09;是一款开源的代码覆盖率分析工具&#xff0c;适用于Java和Android项目。它通过插桩技术统计测试过程中代码的执行情况&#xff0c;生成可视化报告&#xff0c;帮助开发者评估测试用例的有效性。在github上开源的项目&#xff…

OpenGL ES ->乒乓缓冲,计算只用两个帧缓冲对象(Frame Buffer Object)+叠加多个滤镜作用后的Bitmap

乒乓缓冲核心思想 不使用乒乓缓冲&#xff0c;如果要每个滤镜作用下的绘制内容&#xff0c;也就是这个滤镜作用下的帧缓冲&#xff0c;需要创建一个Frame Buffer Object加上对应的Frame Buffer Object Texture使用乒乓缓冲&#xff0c;只用两个Frame Buffer Object加上对应的F…

Unity导出WebGL,无法加载,data文件无法找到 404(NotFound)

问题&#xff1a;data文件无法找到404Not found 示例是使用IIS托管启动 F12可以看到not found 的报错 解决办法&#xff1a; iis无法识别data文件&#xff0c;在MIME类型中增加data 类型&#xff1a;application/octet-stream 添加之后&#xff0c;会在根目录下生产一个…

C++与OO思想的联系

一、C与OO思想的联系 C&#xff1a;OO思想&#xff08;面向对象--属性和行为&#xff09; 任何事务都可以被看做一个个对象&#xff0c;一个再复杂的模型结构都是由千千万万个对象组成。 OO思想两个要素&#xff1a;属性和行为(方法)。 OO思想的特点&#xff1a; 封装&#x…

单表达式倒计时工具:datetime的极度优雅(DeepSeek)

一个简单表达式&#xff0c;也可以优雅自成工具。 笔记模板由python脚本于2025-03-22 20:25:49创建&#xff0c;本篇笔记适合任意喜欢学习的coder翻阅。 【学习的细节是欢悦的历程】 博客的核心价值&#xff1a;在于输出思考与经验&#xff0c;而不仅仅是知识的简单复述。 Pyth…

Kubernetes的Replica Set和ReplicaController有什么区别

ReplicaSet 和 ReplicationController 是 Kubernetes 中用于管理应用程序副本的两种资源&#xff0c;它们有类似的功能&#xff0c;但 ReplicaSet 是 ReplicationController 的增强版本。 以下是它们的主要区别&#xff1a; 1. 功能的演进 ReplicationController 是 Kubernete…

CSS基础知识一览

持续维护 选择器 display 常用属性 浮动 弹性布局

IS-IS原理与配置

一、IS-IS概述 IS-IS&#xff08;Intermediate System to Intermediate System&#xff0c;中间系统到中间系统&#xff09;是ISO&#xff08;International Organization for Standardization&#xff0c;国际标准化组织&#xff09;为它的CLNP&#xff08;ConnectionLessNet…

【前端】Visual Studio Code安装配置教程:下载、汉化、常用组件、基本操作

文章目录 一、Visual Studio Code下载二、汉化三、常用组件1、Auto Rename Tag2、view-in-browser3、Live Server 四、基本操作五、感谢观看&#xff01; 一、Visual Studio Code下载 下载官网&#xff1a;https://code.visualstudio.com/ 进入官网后点击右上角的Download &…

git推送代码相关学习——(一)

推荐去阅读一下廖老师的git相关的教程https://liaoxuefeng.com/books/git/introduction/index.html 这个系列就来学习一下git操作。 第一步&#xff0c;新建项目 去github中新建一个项目&#xff0c;然后依据项目来进行本地的开发工作。 第二步&#xff0c;拉取项目 git c…

CMS网站模板设计与用户定制化实战评测

内容概要 在数字化转型背景下&#xff0c;CMS平台作为企业内容管理的核心载体&#xff0c;其模板架构的灵活性与用户定制能力直接影响运营效率。通过对WordPress、Baklib等主流系统的技术解构发现&#xff0c;模块化设计理念已成为行业基准——WordPress依托超过6万款主题库实…