前言:
本文的目的是通过手机号获取钉钉成员的userid,实现钉钉应用的消息推送。
一、创建钉钉应用
登录钉钉开放平台
二、应用相关凭证
需要获取
Client ID (原 AppKey 和 SuiteKey)
Client Secret (原 AppSecret 和 SuiteSecret)
App ID
原企业内部应用AgentId
三、申请钉钉接口权限
需要先申请对应的接口权限才能调用接口。
但是钉钉的接口太多了,一时半会也找不到对应的接口,推荐直接全勾选。
四、钉钉官方接口
1、获取token
请求方式:GET
参数:appKey,appSecret,reqMethod
url:https://oapi.dingtalk.com/gettoken
2、根据手机号获取用户ID
参数:access_token,mobileNum
url:https://oapi.dingtalk.com/topapi/v2/user/getbymobile
3、发送通知
参数:access_token,msgType,content,userId
url:https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2
五、工具类
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.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.OapiV2UserGetbymobileRequest;
import com.dingtalk.api.response.OapiGettokenResponse;
import com.dingtalk.api.response.OapiMessageCorpconversationAsyncsendV2Response;
import com.dingtalk.api.response.OapiV2UserGetbymobileResponse;
import com.taobao.api.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;@Slf4j
@Component
public class DingTalkUtil {private static final String GET_TOKEN_URL = "https://oapi.dingtalk.com/gettoken";private static final String GET_BY_MOBILE = "https://oapi.dingtalk.com/topapi/v2/user/getbymobile";private static final String ASYNC_SEND_V2_URL = "https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2";private static final String DEFAULT_APP_KEY = "XXX";private static final String DEFAULT_APP_SECRET = "XXXX";private static final Long DEFAULT_AGENT_ID = 123L;private static final String DEFAULT_REQUEST_METHOD = "GET";private String appKey;private String appSecret;private Long agentId;private String reqMethod;public DingTalkUtil() {this(DEFAULT_APP_KEY, DEFAULT_APP_SECRET, DEFAULT_AGENT_ID, DEFAULT_REQUEST_METHOD);}public DingTalkUtil(String appKey, String appSecret, Long agentId, String reqMethod) {this.appKey = (appKey != null && !appKey.isEmpty()) ? appKey : DEFAULT_APP_KEY;this.appSecret = (appSecret != null && !appSecret.isEmpty()) ? appSecret : DEFAULT_APP_SECRET;this.agentId = (agentId != null) ? agentId : DEFAULT_AGENT_ID;this.reqMethod = (reqMethod != null && !reqMethod.isEmpty()) ? reqMethod : DEFAULT_REQUEST_METHOD;}// 获取AccessTokenpublic String getTokenResponse() throws ApiException {DingTalkClient client = new DefaultDingTalkClient(GET_TOKEN_URL);OapiGettokenRequest req = new OapiGettokenRequest();req.setAppkey(appKey);req.setAppsecret(appSecret);req.setHttpMethod(reqMethod);OapiGettokenResponse rsp = client.execute(req);return rsp.getAccessToken();}// 根据手机号获取UserIdpublic String getUserIdByMobile(String accessToken, String mobileNum) throws ApiException {DingTalkClient client = new DefaultDingTalkClient(GET_BY_MOBILE);OapiV2UserGetbymobileRequest req = new OapiV2UserGetbymobileRequest();req.setMobile(mobileNum);OapiV2UserGetbymobileResponse rsp = client.execute(req, accessToken);JSONObject jsonObject = JSON.parseObject(rsp.getBody());JSONObject result = jsonObject.getJSONObject("result");String userid = result.getString("userid");return userid;}// 发送工作通知消息public boolean sendWorkNotice(String accessToken, String msgType, String content, List<String> userIds) throws ApiException {DingTalkClient client = new DefaultDingTalkClient(ASYNC_SEND_V2_URL);OapiMessageCorpconversationAsyncsendV2Request req = new OapiMessageCorpconversationAsyncsendV2Request();req.setAgentId(agentId);req.setUseridList(String.join(",", userIds));OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();msg.setMsgtype(msgType);OapiMessageCorpconversationAsyncsendV2Request.Text text = new OapiMessageCorpconversationAsyncsendV2Request.Text();text.setContent(content);msg.setText(text);req.setMsg(msg);OapiMessageCorpconversationAsyncsendV2Response rsp = client.execute(req, accessToken);return rsp.isSuccess();}public static class Builder {private String msgType = "text";private String content;private List<String> mobiles = new ArrayList<>();private List<String> userIds = new ArrayList<>();public Builder setMsgType(String msgType) {this.msgType = msgType;return this;}public Builder setContent(String content) {this.content = content;return this;}public Builder addUserId(String userId) {this.mobiles.add(userId);return this;}public Builder addUserIds(List<String> userIds) {this.mobiles = userIds;return this;}public boolean send(DingTalkUtil utils) throws ApiException {// 获取 accessTokenString accessToken = utils.getTokenResponse();// 根据手机获取userIdfor (String mobileNum : mobiles) {String userId = utils.getUserIdByMobile(accessToken, mobileNum);userIds.add(userId);}// 调用 sendWorkNotice 发送消息return utils.sendWorkNotice(accessToken, msgType, content, userIds);}}// 封装的发送钉钉通知的方法public boolean sendDingTalkNotification(List<String> phoneList, String message) throws ApiException {DingTalkUtil dingTalkUtil = new DingTalkUtil();return new DingTalkUtil.Builder().setMsgType("text").setContent(message).addUserIds(phoneList).send(dingTalkUtil);}// 内部测试public static void main(String[] args) throws ApiException {DingTalkUtil dingTalkUtil = new DingTalkUtil();List<String> phoneList = Arrays.asList("phoneNum");String message = "your message";boolean result = dingTalkUtil.sendDingTalkNotification(phoneList, message);System.out.println("消息发送结果: " + result);}}