首先,我们要明确需求:自己的系统需要发送通知消息到用户,接收消息用户为同一企业内的人员,选用短信可能涉及到费用问题,故可以选用钉钉或者企业微信,在此我使用钉钉进行发送消息。
调用钉钉发送企业内部消息:
第一步:需要单位授权为子管理员,以便进行应用的创建;
登录钉钉开发者后台开发者后台 (dingtalk.com)https://open-dev.dingtalk.com/#/
确认自己的开发者信息
选择 应用开发 --> 企业内部应用开发
选择创建应用
应用创建示例:
此处不再创建,用之前创建的进行演示,进入应用,可以看到应用凭证,在开发时会重点用到,
由于需求简单,故不需要做过多配置,只需要添加 根据手机号姓名获取成员信息的接口访问权限 即可,用户根据手机号获取钉钉用户信息,进行发送到指定用户。
关于消息的发送,应用最基本的权限已经包括了此功能,直接使用即可;
到此步,配置完成,上代码
pom.xml
<!--钉钉开放平台SDK-->
<dependency>
<groupId>com.aliyun.api</groupId>
<artifactId>top-api-sdk</artifactId>
<version>0.0.1</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>dingtalk</artifactId>
<version>1.1.88</version>
</dependency>
application.yml
service接口class
import com.taobao.api.ApiException;
/**
* 钉钉service
* @Author zhangjiantianya
* @create 2021/10/19 9:10
*/
public interface IDingtalkService {
/**
* xxxx状态通知
* @param mobiles
* @param info
* @return
* @throws ApiException
*/
Boolean xxxxStatusNotice(String mobiles, String info) throws ApiException;
}
serviceImpl实现类
import cn.hutool.core.util.StrUtil;
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.OapiUserGetByMobileRequest;
import com.dingtalk.api.response.OapiGettokenResponse;
import com.dingtalk.api.response.OapiMessageCorpconversationAsyncsendV2Response;
import com.dingtalk.api.response.OapiUserGetByMobileResponse;
import com.taobao.api.ApiException;
import com.xha.job.export.executor.dingtalkService.IDingtalkService;
import com.xha.job.export.executor.util.MyStringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
/**
* 钉钉Service实现类
* @Author zhangjiantianya
* @create 2021/10/18 14:42
*/
@Service
public class DingtalkServiceImpl implements IDingtalkService {
@Value("${dingtalk.xxxxStatusNotice.DingAppkey}")
private String DING_APP_KEY;
@Value("${dingtalk.xxxxStatusNotice.DingAppsecret}")
private String DING_APP_SECRET;
@Value("${dingtalk.xxxxStatusNotice.dingAccessToken}")
private int DING_AGENT_ID;
/**
* 获取AccessToken
*
* @return AccessToken
* @throws ApiException
*/
private String getAccessToken() throws ApiException {
DefaultDingTalkClient client =
new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
OapiGettokenRequest request = new OapiGettokenRequest();
//Appkey
request.setAppkey(DING_APP_KEY);
//Appsecret
request.setAppsecret(DING_APP_SECRET);
/*请求方式*/
request.setHttpMethod("GET");
OapiGettokenResponse response = client.execute(request);
return response.getAccessToken();
}
/**
* 根据手机号获取用户urid
* @param mobiles
* @return
* @throws ApiException
*/
private String getUridByMobile(String mobiles) throws ApiException{
//获取应用密钥
String accessToken = getAccessToken();
String[] mobilesList = mobiles.split(",");
List<String> list = new ArrayList<>();
for (String mobile : mobilesList) {
//根据手机号获取用户信息Urid
DingTalkClient clientByMobile = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/get_by_mobile");
OapiUserGetByMobileRequest req = new OapiUserGetByMobileRequest();
req.setMobile(mobile);
req.setHttpMethod("GET");
OapiUserGetByMobileResponse rsp = clientByMobile.execute(req, accessToken);
if (rsp.isSuccess()){
list.add(rsp.getUserid());
}
}
return MyStringUtils.ListToString(list); // list转为String(逗号分隔)
}
@Override
public Boolean xxxxStatusNotice(String mobiles, String info) throws ApiException{
//获取应用密钥
String accessToken = getAccessToken();
boolean result = true;
//根据手机号获取用户信息Urid
String uridList = getUridByMobile(mobiles);
if (StrUtil.isEmpty(uridList)){
return false;
}
DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2");
OapiMessageCorpconversationAsyncsendV2Request request = new OapiMessageCorpconversationAsyncsendV2Request();
request.setUseridList(uridList); // 接收者的userid列表,最大用户列表长度100。
request.setAgentId(Long.valueOf(DING_AGENT_ID)); // 发送消息时使用的微应用的AgentID
request.setToAllUser(false); //是否发送给企业全部用户
OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
//文本消息
OapiMessageCorpconversationAsyncsendV2Request.Text text = new OapiMessageCorpconversationAsyncsendV2Request.Text();
text.setContent(info);
msg.setMsgtype("text");
msg.setText(text);
request.setMsg(msg);
OapiMessageCorpconversationAsyncsendV2Response response = client.execute(request, accessToken);
result = response.isSuccess();
return result;
}
}
工具类
import java.util.List;
/**
* @Author zhangjiantianya
* @create 2021/10/18 17:59
*/
public class MyStringUtils {
/**
* List<String>转以逗号分隔的String
* @param data
* @return
*/
public static String ListToString(List<String> data) {
StringBuilder sb = new StringBuilder();
for(int i = 0; i < data.size(); i++) {
if (sb.length() > 0) {//该步即不会第一位有逗号,也防止最后一位拼接逗号!
sb.append(",");
}
sb.append(data.get(i));
}
return sb.toString();
}
}
调用service代码,仅供参考:
/**
* @Author zhangjiantianya
* @create 2021/9/23 10:39
*/
@Service
public class test {
@Autowired
private IDingtalkService iDingtalkService;
@Autowired
private CyyDingtalkPushUserDao cyyDingtalkPushUserDao;
/**
* XXXX状态通知
* @return
*/
@Override
public R noticeForxxxxStatus() {
try {
// 编辑钉钉推送手机号
List<String> mobileList = new ArrayList<>();
List<CyyDingtalkPushUser> cyyDingtalkPushUserList =cyyDingtalkPushUserDao.createLambdaQuery().andEq(CyyDingtalkPushUser::getStatus, 0).select();
if (cyyDingtalkPushUserList.size() == 0){
// 手机号没有,直接抛出异常
throw new Exception(String.format("未查询到需推送手机号!"));
}
for (int i = 0; i < cyyDingtalkPushUserList.size(); i++) {
mobileList.add(cyyDingtalkPushUserList.get(i).getMobile());
}
String mobiles = MyStringUtils.ListToString(mobileList);
// 编辑钉钉推送文本
List<String> infoList = new ArrayList<>();
String info = "*****XXXX状态通知*****";
Boolean res = iDingtalkService.transferStatusNotice(mobiles, info);
if (!res){
XxlJobLogger.log("<< 钉钉推送服务异常:{}", info);
return R.fail("转关单状态钉钉推送失败!");
}
XxlJobLogger.log(">> 推送成功!");
}
} catch (Exception e) {
XxlJobLogger.log("<<XXXX状态通知推送服务异常:{},{}", e.getMessage(), e);
}
return R.success();
}
}
应用类型介绍 - 钉钉开放平台 (dingtalk.com)https://open.dingtalk.com/document/org/application-types