java对接钉钉发送消息通知

现在,许多的消息会议,工作任务安排都不在是通过邮件呀,或者是使用口头表达的形式了,都是一些通讯软件进行分发,在工作中,也会有一些东西需要通过程序进行自动发送一些消息通知到指定的人,告诉他,你的,干活的干活!
现在钉钉被小学生差评之后,反而一些大人更喜欢用它来管理“孩子“们了,也就是通过钉钉消息通知,告诉同学们,这个东西有问题需要改了~
博主也在工作中给老师安排了一道,结果呢,百度上面呢,只有机器人,没有工作通知(老师就要通知),博主大大就拿着钉钉的开发平台文档,捣鼓了两天,终于是发出去一个比较OK的通知了
(效果图!)
java对接钉钉发送消息通知_第1张图片
看起来还是比较OK的哦,是吧!不多说废话了,出货了!
钉钉发送消息,第一步肯定是要获取到用户的token,不然我怎么去调用接口(除非钉钉不要你的token,但是是不可能的,发送消息,肯定要登录了,用户合法才行)代码示例如下

/**
     * 获取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(APP_KEY);
        //Appsecret
        request.setAppsecret(APP_SECRET);
        /*请求方式*/
        request.setHttpMethod("GET");
        OapiGettokenResponse response = client.execute(request);
        return response.getAccessToken();
    }

这里面有一个APPkey和APPsecret 这两个东西是企业管理钉钉账号里面的连个密钥,获取方式呢,可以看一下钉钉开发平台开发文档
好了,获取到token了,就可以进行发送消息了(发送消息代码如下)

@Override
    public void sendNotification(String mobile,String park,String alarmCode,String severityDesc) throws ApiException {
        log.info("发送钉钉通知");
        String accessToken = getAccessToken();
        if(StringUtils.isBlank(mobile)){
            return;
        }
        //电话号码数组
        String[] split = mobile.split(",");
        for (String s : split) {
            DingTalkClient client2 = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/get_by_mobile");
            OapiUserGetByMobileRequest req = new OapiUserGetByMobileRequest();
            req.setMobile(s);
            req.setHttpMethod("GET");
            OapiUserGetByMobileResponse rsp = client2.execute(req, accessToken);
            //获取到Urid就是在公司里要发送到那个人的id
            String urid = rsp.getUserid();
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2");
            OapiMessageCorpconversationAsyncsendV2Request request = new OapiMessageCorpconversationAsyncsendV2Request();
            request.setUseridList(urid);
            request.setAgentId(AGENT_ID);
            request.setToAllUser(false);
            OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
            msg.setOa(new OapiMessageCorpconversationAsyncsendV2Request.OA());
            msg.getOa().setMessageUrl(MESSAGE_URL);
            msg.getOa().setPcMessageUrl(PC_MESSAGE_URL);
            msg.getOa().setHead(new OapiMessageCorpconversationAsyncsendV2Request.Head());
            msg.getOa().getHead().setText("text");
            msg.getOa().getHead().setBgcolor("FFBBBBBB");
            msg.getOa().setBody(new OapiMessageCorpconversationAsyncsendV2Request.Body());
            msg.getOa().getBody().setContent("******");
            OapiMessageCorpconversationAsyncsendV2Request.Form formPark = new OapiMessageCorpconversationAsyncsendV2Request.Form();
            formPark.setKey(park);
            OapiMessageCorpconversationAsyncsendV2Request.Form formAlarmCode = new OapiMessageCorpconversationAsyncsendV2Request.Form();
            formAlarmCode.setKey("************");
            formAlarmCode.setValue(alarmCode);
            OapiMessageCorpconversationAsyncsendV2Request.Form formSeverityDesc = new OapiMessageCorpconversationAsyncsendV2Request.Form();
            formSeverityDesc.setKey("************");
            formSeverityDesc.setValue(severityDesc);
            OapiMessageCorpconversationAsyncsendV2Request.Form formConner = new OapiMessageCorpconversationAsyncsendV2Request.Form();
            formConner.setKey("************");
            ArrayList<OapiMessageCorpconversationAsyncsendV2Request.Form> objects = new ArrayList<>();
            objects.add(formPark);
            objects.add(formSeverityDesc);
            objects.add(formAlarmCode);
            objects.add(formConner);
            msg.getOa().getBody().setForm(objects);
            msg.setMsgtype("oa");
            request.setMsg(msg);
            log.info("获取发送通知消息体和获取发送通知人完成");
            OapiMessageCorpconversationAsyncsendV2Response response = client.execute(request,accessToken);
            log.info("发送消息是否成功"+response.isSuccess());
            System.out.println(response.isSuccess());
            log.info("消息任务ID"+response.getTaskId());
            System.out.println(response.getTaskId());
        }
    }

这上面的代码中都有注释,可以看到很清楚,博主在开发的时候唯有困了的就是设置那个消息体也就是这个

    OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
            msg.setOa(new OapiMessageCorpconversationAsyncsendV2Request.OA());
            msg.getOa().setMessageUrl(MESSAGE_URL);
            msg.getOa().setPcMessageUrl(PC_MESSAGE_URL);
            msg.getOa().setHead(new OapiMessageCorpconversationAsyncsendV2Request.Head());
            msg.getOa().getHead().setText("text");
            msg.getOa().getHead().setBgcolor("FFBBBBBB");
            msg.getOa().setBody(new OapiMessageCorpconversationAsyncsendV2Request.Body());
            msg.getOa().getBody().setContent("******");
            OapiMessageCorpconversationAsyncsendV2Request.Form formPark = new OapiMessageCorpconversationAsyncsendV2Request.Form();
            formPark.setKey(park);
            OapiMessageCorpconversationAsyncsendV2Request.Form formAlarmCode = new OapiMessageCorpconversationAsyncsendV2Request.Form();
            formAlarmCode.setKey("************");
            formAlarmCode.setValue(alarmCode);
            OapiMessageCorpconversationAsyncsendV2Request.Form formSeverityDesc = new OapiMessageCorpconversationAsyncsendV2Request.Form();
            formSeverityDesc.setKey("************");
            formSeverityDesc.setValue(severityDesc);
            OapiMessageCorpconversationAsyncsendV2Request.Form formConner = new OapiMessageCorpconversationAsyncsendV2Request.Form();
            formConner.setKey("************");
            ArrayList<OapiMessageCorpconversationAsyncsendV2Request.Form> objects = new ArrayList<>();
            objects.add(formPark);
            objects.add(formSeverityDesc);
            objects.add(formAlarmCode);
            objects.add(formConner);
            msg.getOa().getBody().setForm(objects);
            msg.setMsgtype("oa");

这里面的Msgtype是系统通知的类型,在钉钉开发文档中也有说明,可以参考
java对接钉钉发送消息通知_第2张图片
到这来,是不是就以为结束了,nonono,还有最重要的一个,消息通知发过去了,怎么保证进去的那个人就是合法的(也就是说,这个坑怎么知道是不是这个萝卜的!)
嘿嘿,不慌,钉钉有一个免密登录code,我们可以通过这个code获取到用户信息,同时通过网关或者拦截器这一类的东西,进行过滤用户请求,判断萝卜对不对!

 /***
     * 根据免密登录code获取用户信息
     * @param requestAuthCode 免密登录code
     * @throws ApiException
     */
    @Override
    public ResponseMessage getUserInfo(String requestAuthCode) throws ApiException {
        if(StringUtils.isBlank(requestAuthCode)){
            return ResponseMessage.error("免登录code不能为空");
        }
        String accessToken = getAccessToken();
        /*获取用户ID*/
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/getuserinfo");
        OapiUserGetuserinfoRequest request = new OapiUserGetuserinfoRequest();
        request.setCode(requestAuthCode);
        request.setHttpMethod("GET");
        OapiUserGetuserinfoResponse response = client.execute(request, accessToken);
        String userId = response.getUserid();
        /*获取用户详细信息*/
        DingTalkClient getUserInfoClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/get");
        OapiUserGetRequest getUserInfoRequest = new OapiUserGetRequest();
        getUserInfoRequest.setUserid(userId);
        getUserInfoRequest.setHttpMethod("GET");
        OapiUserGetResponse execute = getUserInfoClient.execute(getUserInfoRequest, accessToken);
        /*手机号*/
        String mobile = execute.getMobile();
        /*用户名*/
        String name = execute.getName();
        /*员工工号*/
        String jobNumber = execute.getJobnumber();
        String redisValues = mobile+":"+name+":"+jobNumber;
        String md5Value = MD5.create().digestHex(redisValues);
        /*存放Redis*/
        try {
            redisTemplate.opsForValue().set(requestAuthCode, md5Value, 2, TimeUnit.HOURS);
            return ResponseMessage.ok(execute);
        }catch (Exception e){
            return ResponseMessage.error("token生产存储失败!");
        }
    }

看见没有,这个时候需要前台调用钉钉的免密登录接口,通过免密登录接口就能获取到code,把code发后台就能获取到钉钉用户的具体信息,可以将一些数据加密存入我们自己的token里面,用户每次将我们给他的token带回来,去rides中获取到token对比,如果存在,用户合法,如果token不存在获取过期了,提醒前台,用户需要重新登录!
对于拦截器的和网关的使用可以查看博主的博客SpringBoot拦截器配置与使用
SpringCloud组件4值zuul网关
好了,老师,交作业了,多谢同学梦的支持,如有不对的地方,欢迎指正!

你可能感兴趣的:(java,SpringBoot,SpringCloud,java,redis,http)