package com.dy.pmsGlobal.util; import com.dingtalk.api.DefaultDingTalkClient; import com.dingtalk.api.DingTalkClient; import com.dingtalk.api.request.OapiRobotSendRequest; import com.dingtalk.api.response.OapiRobotSendResponse; import com.taobao.api.ApiException; import lombok.extern.slf4j.Slf4j; import org.apache.commons.codec.binary.Base64; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; @Slf4j @Component public class DingDingUtils { @Value("${dingtalk.robot.access-token}") private String custom_robot_token; // public static final String USER_ID= ""; @Value("${dingtalk.at-all}") private boolean at_all; @Value("${dingtalk.robot.secret}") private String secret; @Value("${dingtalk.robot.url}") private String url; public OapiRobotSendResponse send(String msg) { try { Long timestamp = System.currentTimeMillis(); String sign = sign(timestamp, secret); System.out.println(sign); //sign字段和timestamp字段必须拼接到请求URL上,否则会出现 310000 的错误信息 DingTalkClient client = new DefaultDingTalkClient(url+"?sign="+sign+"×tamp="+timestamp); OapiRobotSendRequest req = new OapiRobotSendRequest(); /** * 发送文本消息 */ //定义文本内容 OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text(); text.setContent(msg); //定义 @ 对象 OapiRobotSendRequest.At at = new OapiRobotSendRequest.At(); if(at_all) { at.setIsAtAll(true); } //设置消息类型 req.setMsgtype("text"); req.setText(text); req.setAt(at); OapiRobotSendResponse rsp = client.execute(req, custom_robot_token); log.error("钉钉响应:"+rsp); return rsp; } catch (ApiException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (InvalidKeyException e) { throw new RuntimeException(e); } return null; } private String sign(Long timestamp, String secret) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException { String stringToSign = timestamp + "\n" + secret; Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256")); byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8")); String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)),"UTF-8"); return sign; } }