陈昶聿
昨天 574f63b57552e85406076bc0a2da511a040d263f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
package com.smartor.service.impl;
 
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.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.OapiUserListidRequest;
import com.dingtalk.api.request.OapiV2UserGetbymobileRequest;
import com.dingtalk.api.response.OapiGettokenResponse;
import com.dingtalk.api.response.OapiMessageCorpconversationAsyncsendV2Response;
import com.dingtalk.api.response.OapiUserListidResponse;
import com.dingtalk.api.response.OapiV2UserGetbymobileResponse;
import com.ruoyi.common.core.domain.DingAsyncSendMsgReq;
import com.ruoyi.common.core.domain.DingAsyncSendMsgResp;
import com.ruoyi.common.core.domain.DingTalkReqVo;
import com.ruoyi.common.core.domain.DingTokenResp;
import com.ruoyi.common.utils.DingTalkUtils;
import com.ruoyi.common.utils.StringUtils;
import com.smartor.service.DingTalkService;
import com.taobao.api.ApiException;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
 
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
 * 智能中心
 *
 * @author ls
 * @date 2023-05-23
 */
@Service
@Log4j
public class DingTalkServiceImpl implements DingTalkService {
 
 
    @Value("${dingAppid}")
    private String dingAppid;
 
    @Value("${dingAppSecret}")
    private String dingAppSecret;
 
    @Value("${dingAppAgentId}")
    private Long dingAppAgentId;
 
    @Override
    public Boolean sendNotification(DingTalkReqVo dingTalkReqVo) {
        String body = null;
        List<String> userIdlist = new ArrayList();
        Boolean result = false;
        log.info("发送钉钉通知");
 
        String accessToken = null;
        try {
            accessToken = getAccessToken();
        } catch (ApiException e) {
            e.printStackTrace();
        }
        if (StringUtils.isNotEmpty(dingTalkReqVo.getNumber())) {
            DingTalkClient clientT = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/getbymobile");
            OapiV2UserGetbymobileRequest req = new OapiV2UserGetbymobileRequest();
            req.setMobile(dingTalkReqVo.getNumber());
            OapiV2UserGetbymobileResponse rsp = null;
            try {
                rsp = clientT.execute(req, accessToken);
                body = rsp.getBody();
                String jsonObject = JSONObject.parseObject(body).getJSONObject("result").get("userid").toString();
                userIdlist.add(jsonObject);
 
            } catch (ApiException e) {
                e.printStackTrace();
            }
        } else {
            DingTalkClient client3 = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/user/listid");
 
            OapiUserListidRequest request2 = new OapiUserListidRequest();
            request2.setDeptId(dingTalkReqVo.getDeptId()); // 设置要获取的部门 ID,这里以根部门为例675909059L
            // 设置部门 ID,如果获取所有员工手机号,可以设置为根部门的 ID
            OapiUserListidResponse response2 = null;
            try {
                response2 = client3.execute(request2, accessToken);
            } catch (ApiException e) {
                e.printStackTrace();
            }
            body = response2.getBody();
            // 解析为JSONObject
            JSONObject jsonObject = JSONObject.parseObject(body);
            // 提取出JSONArray
            JSONArray jsonArray = new JSONArray(jsonObject.getJSONObject("result").getJSONArray("userid_list"));
            // 将JSONArray转为List列表
            String str = JSONObject.toJSONString(jsonArray);
            userIdlist = JSONObject.parseObject(str, List.class);
        }
 
 
        //userid数组
        for (String urid : userIdlist) {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2");
            OapiMessageCorpconversationAsyncsendV2Request request = new OapiMessageCorpconversationAsyncsendV2Request();
            request.setUseridList(urid);
            request.setAgentId(1779052814L);
            request.setToAllUser(false);
 
            //发送内容处理
            List<ConcurrentHashMap<String, String>> contents = dingTalkReqVo.getContents();
            ArrayList<OapiMessageCorpconversationAsyncsendV2Request.Form> objects = new ArrayList<>();
            for (int i = 0; i < contents.size(); i++) {
                ConcurrentHashMap<String, String> map = contents.get(i);
                for (Map.Entry<String, String> entry : map.entrySet()) {
                    OapiMessageCorpconversationAsyncsendV2Request.Form formSeverityDesc = new OapiMessageCorpconversationAsyncsendV2Request.Form();
                    formSeverityDesc.setKey(entry.getKey());
                    formSeverityDesc.setValue(entry.getValue());
                    objects.add(formSeverityDesc);
                }
            }
 
            OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
            msg.setOa(new OapiMessageCorpconversationAsyncsendV2Request.OA());
            msg.getOa().setMessageUrl(dingTalkReqVo.getUrl());
            msg.getOa().setPcMessageUrl(dingTalkReqVo.getUrl());
            msg.getOa().setHead(new OapiMessageCorpconversationAsyncsendV2Request.Head());
            //   msg.getOa().getHead().setText("你在说啥呢绒顶替苛夺阿斯蒂芬阿斯蒂芬");
            msg.getOa().getHead().setBgcolor("00409eff");
            msg.getOa().setBody(new OapiMessageCorpconversationAsyncsendV2Request.Body());
            msg.getOa().getBody().setTitle(dingTalkReqVo.getTitle());
            // msg.getOa().getBody().setContent("待处理:" + "123" + "条");
 
            msg.getOa().getBody().setForm(objects);
            msg.setMsgtype("oa");
            request.setMsg(msg);
            //  log.info("获取发送通知消息体和获取发送通知人完成");
            OapiMessageCorpconversationAsyncsendV2Response response = null;
            try {
                response = client.execute(request, accessToken);
            } catch (ApiException e) {
                e.printStackTrace();
            }
 
            //  log.info("消息任务ID"+response.getTaskId());
            System.out.println(response.getTaskId());
 
            result = response.isSuccess();
        }
        return result;
    }
 
 
    /**
     * 获取 access_token
     */
    private String getAccessToken() throws ApiException {
        DefaultDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
        OapiGettokenRequest request = new OapiGettokenRequest();
        //Appkey
        request.setAppkey(dingAppid);
        //Appsecret
        request.setAppsecret(dingAppSecret);
        /*请求方式*/
        request.setHttpMethod("GET");
        OapiGettokenResponse response = client.execute(request);
        return response.getAccessToken();
    }
 
    /**
     * 获取post access_token
     */
    private String getAccessTokenPost() throws ApiException {
        DefaultDingTalkClient client = new DefaultDingTalkClient("https://api.dingtalk.com/v1.0/oauth2/{corpId}/token");
        OapiGettokenRequest request = new OapiGettokenRequest();
        //Appkey
        request.setAppkey(dingAppid);
        //Appsecret
        request.setAppsecret(dingAppSecret);
        /*请求方式*/
        request.setHttpMethod("Post");
        OapiGettokenResponse response = client.execute(request);
        return response.getAccessToken();
    }
 
//    /**
//     * 发送钉钉消息-景宁
//     * @param sMessageContent
//     * @throws Exception
//     */
//    public void sendDingTalkText(String sMessageContent) throws Exception {
//        String CORP_ID = "你的企业corpid";
//        String CORP_SECRET = "企业应用的corpsecret";
//        Long AGENT_ID = 4992829038L; // 你的应用agentId
//
//        try {
//            // 1. 获取access_token
//            DingTokenResp tokenResp = DingTalkUtils.getAccessToken(CORP_ID, CORP_SECRET);
//            if (tokenResp.getErrcode() != 0) {
//                System.err.println("获取token失败:" + tokenResp.getErrmsg());
//                return;
//            }
//            String accessToken = tokenResp.getAccess_token();
//            System.out.println("access_token=" + accessToken);
//
//            // 2. 组装发送请求
//            DingAsyncSendMsgReq sendReq = new DingAsyncSendMsgReq();
//            sendReq.setAgent_id(AGENT_ID);
//            sendReq.setUserid_list("user01,user02"); // 接收人钉钉userId,多个逗号
//            sendReq.setTo_all_user(false);
//            // 设置消息内容,这里用文本消息
//            sendReq.setMsg(DingTalkUtils.buildTextMsg("你好,这是异步发送钉钉消息测试"));
//
//            // 3. 调用异步发送接口
//            DingAsyncSendMsgResp sendResp = DingTalkUtils.asyncSendCorpMsg(accessToken, sendReq);
//            if (sendResp.getErrcode() == 0) {
//                System.out.println("提交消息任务成功,task_id=" + sendResp.getTask_id());
//                System.out.println("消息实际发送结果,需要在钉钉后台配置回调接收");
//            } else {
//                System.err.println("提交消息任务失败:code=" + sendResp.getErrcode() + ",msg=" + sendResp.getErrmsg());
//            }
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
 
    /**
     * 发送钉钉消息-景宁
     * @param sMessageContent
     * @throws Exception
     */
    @Override
    public void sendDingTalkText(String sMessageContent, String userId) throws Exception {
        Long agentId = dingAppAgentId;
        String accessToken = getAccessToken();
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2");
        OapiMessageCorpconversationAsyncsendV2Request request = new OapiMessageCorpconversationAsyncsendV2Request();
        request.setAgentId(agentId);
        request.setUseridList(userId);
        request.setToAllUser(false);
 
        OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
        msg.setMsgtype("text");
        OapiMessageCorpconversationAsyncsendV2Request.Text text = new OapiMessageCorpconversationAsyncsendV2Request.Text();
        text.setContent(sMessageContent);
        msg.setText(text);
        request.setMsg(msg);
 
        OapiMessageCorpconversationAsyncsendV2Response rsp = client.execute(request, accessToken);
        System.out.println(rsp.getBody());
    }
 
    /**
     * 根据电话获取用户
     * @param mobile
     * @return
     * @throws Exception
     */
    @Override
    public String getDingTalkUserByMobile(String mobile) throws Exception {
        String accessToken = getAccessToken();
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/getbymobile");
        OapiV2UserGetbymobileRequest req = new OapiV2UserGetbymobileRequest();
        req.setMobile(mobile);
        OapiV2UserGetbymobileResponse rsp = client.execute(req, accessToken);
        return rsp.getBody();
    }
 
}