package com.ruoyi.common.utils;
|
|
import com.alibaba.fastjson2.JSON;
|
import com.ruoyi.common.core.domain.DingAsyncSendMsgReq;
|
import com.ruoyi.common.core.domain.DingAsyncSendMsgResp;
|
import com.ruoyi.common.core.domain.DingTokenResp;
|
import okhttp3.*;
|
|
import java.io.IOException;
|
import java.util.HashMap;
|
import java.util.Map;
|
import java.util.concurrent.TimeUnit;
|
|
public class DingTalkUtils {
|
|
private static final OkHttpClient HTTP_CLIENT = new OkHttpClient.Builder()
|
.connectTimeout(10, TimeUnit.SECONDS)
|
.readTimeout(10, TimeUnit.SECONDS)
|
.build();
|
|
/**
|
* 获取企业access_token
|
* @param corpid 企业ID
|
* @param corpsecret 应用的凭证密钥
|
* @return DingTokenResp
|
*/
|
public static DingTokenResp getAccessToken(String corpid, String corpsecret) throws IOException {
|
String url = "https://oapi.dingtalk.com/gettoken?corpid=" + corpid + "&corpsecret=" + corpsecret;
|
Request request = new Request.Builder()
|
.url(url)
|
.get()
|
.build();
|
try (Response response = HTTP_CLIENT.newCall(request).execute()) {
|
String body = response.body().string();
|
return JSON.parseObject(body, DingTokenResp.class);
|
}
|
}
|
|
/**
|
* 异步发送企业会话消息 asyncsend_v2
|
*/
|
public static DingAsyncSendMsgResp asyncSendCorpMsg(String accessToken, DingAsyncSendMsgReq req) throws IOException {
|
String url = "https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2?access_token=" + accessToken;
|
|
String jsonBody = JSON.toJSONString(req);
|
RequestBody body = RequestBody.create(jsonBody, MediaType.get("application/json; charset=utf-8"));
|
|
Request request = new Request.Builder()
|
.url(url)
|
.post(body)
|
.build();
|
|
try (Response response = HTTP_CLIENT.newCall(request).execute()) {
|
String respBody = response.body().string();
|
return JSON.parseObject(respBody, DingAsyncSendMsgResp.class);
|
}
|
}
|
|
// ========== 构建消息示例:文本消息 ==========
|
public static Map<String, Object> buildTextMsg(String content) {
|
Map<String, Object> msgMap = new HashMap<>();
|
msgMap.put("msgtype", "text");
|
Map<String, Object> text = new HashMap<>();
|
text.put("content", content);
|
msgMap.put("text", text);
|
return msgMap;
|
}
|
|
// ========== 构建消息示例:markdown消息 ==========
|
public static Map<String, Object> buildMarkdownMsg(String title, String text) {
|
Map<String, Object> msgMap = new HashMap<>();
|
msgMap.put("msgtype", "markdown");
|
Map<String, Object> markdown = new HashMap<>();
|
markdown.put("title", title);
|
markdown.put("text", text);
|
msgMap.put("markdown", markdown);
|
return msgMap;
|
}
|
}
|