对接钉钉的企业内部机器人与企业号主动发送群聊通知:
企业号主动发送群聊通知:
步骤:
- 通过后台的AppKey和AppSecret获取到请求的access_token:
文档地址:https://ding-doc.dingtalk.com/document#/org-dev-guide/obtain-access_token
/**
2. 获取token请求接口
3. 4. @param appKey 密钥
5. @param appSecret 密钥
6. @return token
*/
public String getToken(String appKey, String appSecret) {
//获取token值
String token = "";
try {
DefaultDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
OapiGettokenRequest request = new OapiGettokenRequest();
request.setAppkey(appKey);
request.setAppsecret(appSecret);
request.setHttpMethod("GET");
OapiGettokenResponse response = client.execute(request);
token = response.getAccessToken();
return token;
} catch (Exception e) {
log.info("钉钉异常" + e);
}
return token;
}
- 创建群聊前需要知道用户的userId,可通过用户手机号获取:
文档地址:https://ding-doc.dingtalk.com/document#/org-dev-guide/get-userid-By-Mobile
/**
1. 获取用户的userId
2. @param phone 手机号
3. @param token token值
4. @return userId
*/
public String getUserId(String phone,String token) {
String userId = "";
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, token);
userId = rsp.getResult().getUserid();
} catch (Exception e) {
log.info("钉钉异常" + e);
}
return userId;
}
- 带着access_token创建群聊,保存群聊id:
文档地址:https://ding-doc.dingtalk.com/document#/org-dev-guide/create-chat
/**
1. 创建群聊
2. @param userId 群主id
3. @param memberList 群成员ids
4. @param chatroomName 群聊名称
5. @param token token值
6. @return 群聊id
*/
public String createChatroom(String userId, List<String> memberList,String chatroomName,String token){
String chatroomId = "";
try{
DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/chat/create");
OapiChatCreateRequest req = new OapiChatCreateRequest();
req.setName(chatroomName);
req.setOwner(userId);
req.setUseridlist(memberList);
OapiChatCreateResponse rsp = client.execute(req, token);
chatroomId = rsp.getChatid();//获取到群聊id
return chatroomId;
}catch (Exception e){
log.info("钉钉异常" + e);
}
return chatroomId;
}
- 根据群聊id,按照自己所需要格式发送消息:
文档地址:https://ding-doc.dingtalk.com/document#/org-dev-guide/send-chat-messages
/**
* 发送群消息
* @param chatId 群聊id
* @param content 发送内容
* @param msgType 内容类型
* @param token token值
* @return 发送状态码
*/
public String sendMessage(String chatId,String content,String msgType,String token){
String msg="";
try {
DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/chat/send");
OapiChatSendRequest req = new OapiChatSendRequest();
req.setChatid(chatId);
OapiChatSendRequest.Msg obj1 = new OapiChatSendRequest.Msg();
OapiChatSendRequest.Text obj2 = new OapiChatSendRequest.Text();
obj2.setContent(content);
obj1.setText(obj2);
obj1.setMsgtype(msgType);
req.setMsg(obj1);
OapiChatSendResponse rsp = client.execute(req, token);
return rsp.getErrorCode();
}catch (Exception e){
log.info("钉钉异常" + e);
}
return msg;
}
注意事项:
1.提示访问ip不在白名单的时候:
2.获取AppKey和AppSecret的文档地址:https://ding-doc.dingtalk.com/doc#/serverapi2/eev437
3.钉钉接口状态码大全:https://blog.csdn.net/weixin_38171468/article/details/106051120
对接钉钉企业内部outgoing机器人通知:
1.官方客服给予的JAVA代码(亲测可用,其中的appSecret修改为自己的):
@Controller
public class BotController {
@RequestMapping(value = "/robot",method = RequestMethod.POST)
public void robot(HttpServletRequest request, HttpServletResponse response,
@RequestBody(required = false) JSONObject json) throws NoSuchAlgorithmException, IOException, InvalidKeyException, ApiException {
response.setContentType("text/html; charset=utf-8");
//请求header中的timestamp
String headerTimestamp = request.getHeader("timestamp");
//请求header中的sign
String headerSign = request.getHeader("sign");
//从请求body中可以获取到@机器人时的消息内容
System.out.println(json.getJSONObject("text").getString("content"));
System.out.println(json);
//当前机器人的webHook地址
String webHook = json.getString("sessionWebhook");
//计算签名值
String timestamp = headerTimestamp;
String appSecret = "zNyI0MqeEjxUqXYeGn_WlcynPNmmC0bW0m7i3xDCftA6R5jYl2hjZiu-VHjjEbqK";//当前企业内部机器人应用的appSecret值
String stringToSign = timestamp + "\n" + appSecret;
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(appSecret.getBytes("UTF-8"), "HmacSHA256"));
byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
String sign = new String(Base64.encodeBase64(signData));
//判断计算得到的签名与request中的签名是否一致
if (sign.equals(headerSign)){
//计算的签名与header中的签名值一致,可以响应
DingTalkClient client = new DefaultDingTalkClient(webHook+"×tamp="+headerTimestamp+"&sign="+sign);
OapiRobotSendRequest webhookRequest = new OapiRobotSendRequest();
//可以根据需求使用不同的响应消息格式,目前支持text、markdown、actionCard、feedCard这4种消息类型
// webhookRequest.setMsgtype("text");
// OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();
// text.setContent("测试文本消息");
// webhookRequest.setText(text);
// OapiRobotSendRequest.At at = new OapiRobotSendRequest.At();
// at.setAtMobiles(Arrays.asList("132xxxxxxxx"));
// isAtAll类型如果不为Boolean,请升级至最新SDK
// at.setIsAtAll(false);
// webhookRequest.setAt(at);
webhookRequest.setMsgtype("actionCard");
OapiRobotSendRequest.Actioncard actioncard = new OapiRobotSendRequest.Actioncard();
actioncard.setSingleURL("http://www.dingtalk.com");
actioncard.setSingleTitle("按钮");
actioncard.setTitle("测试消息");
actioncard.setText("haha@18537608557");
OapiRobotSendRequest.At at = new OapiRobotSendRequest.At();
at.setAtMobiles(Arrays.asList("18537608557"));
at.setIsAtAll(false);
webhookRequest.setAt(at);
webhookRequest.setActionCard(actioncard);
OapiRobotSendResponse webhookResponse = client.execute(webhookRequest);
}else {
//计算的签名与header中的签名不一致,不响应
System.out.println("非法请求");
}
}
2.本地测试,切记开启本地内网穿透:
①钉钉提供的内网穿透github地址,https://github.com/open-dingtalk/pierced,拉取可用
Windows启动命令:ding.exe -config=ding.cfg -subdomain=xiaomge 89
3.设置机器人的消息接收地址:
4.切记群机器人不是拉进群,是通过添加智能群助手