com.admin4j.chatbot.dingtalk.DingRobot Maven / Gradle / Ivy
package com.admin4j.chatbot.dingtalk;
import com.admin4j.chatbot.dingtalk.core.RobotResponse;
import com.admin4j.chatbot.dingtalk.request.base.AbstractRobotRequest;
import io.github.admin4j.http.ApiJsonClient;
import io.github.admin4j.http.core.HttpDefaultConfig;
import io.github.admin4j.http.exception.HttpException;
import lombok.Data;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
/**
* https://open.dingtalk.com/document/orgapp/robot-overview#e744a9d0adhpm
* https://open.dingtalk.com/document/group/custom-robot-access
*
* @author andanyang
* @since 2022/5/11 11:43
*/
@Data
@Slf4j
public class DingRobot {
//private Map queryMap;
private String accessToken;
private String secret;
@Setter
private ApiJsonClient apiJsonClient;
/**
* 初始化
*
* @param accessToken
* @param secret
*/
public DingRobot(String accessToken, String secret) {
super();
if (!accessToken.contains("https://oapi.dingtalk.com")) {
accessToken = "https://oapi.dingtalk.com/robot/send?access_token=" + accessToken;
}
this.secret = secret;
this.accessToken = accessToken;
apiJsonClient = new ApiJsonClient(HttpDefaultConfig.get());
}
public DingRobot(String accessToken) {
this(accessToken, null);
}
/**
* // 消息内容中不包含任何关键词
* {
* "errcode":310000,
* "errmsg":"keywords not in content"
* }
*
* // timestamp 无效
* {
* "errcode":310000,
* "errmsg":"invalid timestamp"
* }
*
* // 签名不匹配
* {
* "errcode":310000,
* "errmsg":"sign not match"
* }
*
* // IP地址不在白名单
* {
* "errcode":310000,
* "errmsg":"ip X.X.X.X not in whitelist"
* }
*
* @param request
*/
public void send(AbstractRobotRequest request) {
String url;
if (StringUtils.isNotBlank(secret)) {
try {
//https://oapi.dingtalk.com/robot/send?access_token=XXXXXX×tamp=XXX&sign=XXX
long timestamp = System.currentTimeMillis();
String stringToSign = timestamp + "\n" + secret;
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
String sign = URLEncoder.encode(Base64.getEncoder().encodeToString(signData), "UTF-8");
url = accessToken + "×tamp=" + timestamp + "&sign=" + sign;
} catch (Exception e) {
log.error("DingRobot sign error", e);
throw new HttpException("DingRobot sign error");
}
} else {
url = accessToken;
}
//response {"errcode":0,"errmsg":"ok"}
RobotResponse response = apiJsonClient.post(url, request, RobotResponse.class);
if (response != null && response.getErrcode() != 0) {
throw new HttpException(response.getErrmsg(), response.getErrcode());
}
}
}