钉钉简单的推送钉消息
一、钉钉准备工作
首先进入钉钉开放平台 你得有企业内部微应用或者小程序 没有创建的话去看我另一篇文章有说明
钉钉开放平台创建企业内部H5微应用或者小程序-CSDN博客
看不懂话也可以参考官方文档:创建应用 - 钉钉开放平台
二、开发的准备工作
1.pom的导入
<!-- 钉钉SDK -->
<dependency><groupId>com.aliyun</groupId><artifactId>dingtalk</artifactId><version>1.2.15</version>
</dependency>
<dependency><groupId>com.aliyun</groupId><artifactId>alibaba-dingtalk-service-sdk</artifactId><version>2.0.0</version>
</dependency>
2.配置文件(yml配置文件)
#钉钉信息
dingtalk:corpid: dingxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxappkey: dingxxxxxxxxxxxxxxxxappsecret: 89QA-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-xxxxagentid: 2xxxxxxxxx
这里的配置信息是你的应用信息(在钉钉后台-应用管理)
三、代码实现
添加工具类 获取钉钉AccessToken
/*** 钉钉工具类* @date 2023-07-07 9:30*/
@Slf4j
@Component
public class DingTalkUtil {@Value("${dingtalk.appKey}")private String appKey;@Value("${dingtalk.appSecret}")private String appSecret;/*** 获取钉钉AccessToken** @return*/public String getAccessToken() {try {DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");OapiGettokenRequest req = new OapiGettokenRequest();req.setAppkey(appKey);req.setAppsecret(appSecret);req.setHttpMethod("GET");OapiGettokenResponse rsp = client.execute(req);if (rsp.getErrcode() == 0) {return rsp.getAccessToken();} else {throw new JeecgBootException("获取dingtalk授权失败!");}} catch (ApiException e) {e.printStackTrace();}return null;}}
调用钉钉接口之前都是需要用到access_token校验的,接着调用用户电话获得钉钉的userId(某个人在企业里的唯一ID)
/*** 获取钉钉的用户的userid** @param phone 用户电话* @return 钉钉用户内部userId*/public String getDingTalkUserId(String phone) throws Exception {String accessToken = this.getAccessToken();if (accessToken == null) {throw new Exception("获取到access_token失败!");}try {DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/getbymobile");OapiV2UserGetbymobileRequest req = new OapiV2UserGetbymobileRequest();req.setMobile(phone);OapiV2UserGetbymobileResponse rsp = client.execute(req, accessToken);String userId = rsp.getResult().getUserid();return userId;} catch (ApiException e) {log.error("请求获取钉钉用户的userid失败:{}", e.getErrMsg());}return null;}
发送消息工具类(可给单个或多个人发送)
package org.jeecg.modules.aigoes.util;import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.modules.message.util.DingTalkUtil;
import org.jeecg.modules.system.entity.SysTenant;
import org.jeecg.modules.system.service.ISysTenantService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;import javax.annotation.Resource;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.stream.Collectors;/*** rwy* @date 2023-07-07 9:30*/
@Slf4j
@Component
public class MessageUtils {@Resourceprivate DingTalkUtil dingTalkUtil;// 钉钉发送消息给指定用户列表public void sendMessageNew(List<String> userIdList, String picUrl, String messageUrlDing, String text, String title) throws Exception {String accessToken = dingTalkUtil.getAccessToken();String messageUrl = "https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2?access_token=" + accessToken;JSONObject jsonObject = new JSONObject();//钉钉后台应用的agent_idjsonObject.put("agent_id", sysTenant.getAgentId());//推送的userId jsonObject.put("userid_list",userIdList.stream().collect(Collectors.joining(",")));jsonObject.put("to_all_user", false);JSONObject msgObj = new JSONObject();//消息类型msgObj.put("msgtype", "action_card");JSONObject textObj = new JSONObject();//标题textObj.put("title", title);//内容textObj.put("markdown", text);//按钮名称textObj.put("single_title", picUrl);//跳转地址 填小程序莫页面地址或微应用的textObj.put("single_url", messageUrlDing);msgObj.put("action_card",textObj);jsonObject.put("msg", msgObj);String jsonBody = jsonObject.toJSONString();System.out.println(jsonBody);//发送POST请求JSONObject response = httpPost(messageUrl, jsonBody, "UTF-8");System.out.println(response);}public JSONObject httpPost(String url, String requestData, String charset) throws IOException {URL apiUrl = new URL(url);HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection();connection.setRequestMethod("POST");connection.setDoOutput(true);// 设置请求头部connection.setRequestProperty("Content-Type", "application/json;charset=" + charset);// 发送请求数据try (OutputStream outputStream = connection.getOutputStream()) {outputStream.write(requestData.getBytes(charset));outputStream.flush();}// 获取响应结果try (InputStream inputStream = connection.getInputStream();BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, charset))) {StringBuilder response = new StringBuilder();String line;while ((line = reader.readLine()) != null) {response.append(line);}return JSONObject.parseObject(response.toString());}} }
这里需要注意的是你选择的消息通知类型 - 钉钉开放平台,我这里选择是卡片消息 因为卡片消息支持整体跳转ActionCard样式和独立跳转ActionCard样式以及可以展示图片和添加多个按钮 样式和可玩性比较高。
测试发送钉消息
注意事项:小程序链接和微应用微应用唯一区别在这跳转地址 要跳转小程序前面是需要加 eapp:// 列如以下是这样的 eapp://pagesA/pages/Home/h-psy/ 而微应用不用加
/*** 发送钉消息* @return* @throws Exception*/@GetMapping("/cs2")public Result<?> cs() throws Exception {String headteacherId = "661xxxxxxxxxxxxxxx";messageUtils.sendMessageNew(Collections.singletonList(headteacherId),"点击查看详情","pagesA/pages/Home/h-psy/mood","### <font color=#04CFFF>测试天气消息</font> \n **天气还不错。**","天气报告");return Result.OK();}
四、调试API Explorer
钉钉专门的API调用工具可以自己试试API Explorer
1.根据自己应用的appKey和appSecret来获取accessToken。
2. 工作通知-异步发送工作通知
填入内容 然后往下拉找到我们要发的消息类型我这里是卡片消息(这里你也可以选别的消息类型)填入必填的参数再点发起调用 也是能够成功发送的。
最后希望能帮助到你们。