钉钉企业内部H5微应用或小程序之钉消息推送

钉钉简单的推送钉消息

一、钉钉准备工作

首先进入钉钉开放平台 你得有企业内部微应用 或者小程序 没有创建的话去看我另一篇文章有说明

钉钉开放平台创建企业内部H5微应用或者小程序-CSDN博客

看不懂话也可以参考官方文档:创建应用 - 钉钉开放平台

二、开发的准备工作

1.pom的导入

java 复制代码
<!-- 钉钉SDK -->
<dependency>
   <groupId>com.aliyun</groupId>
   <artifactId>dingtalk</artifactId>
   <version>1.2.15</version>
</dependency>
<dependency>
   <groupId>com.aliyun</groupId>
   <artifactId>alibaba-dingtalk-service-sdk</artifactId>
   <version>2.0.0</version>
</dependency>
            

2.配置文件(yml配置文件)

java 复制代码
#钉钉信息
dingtalk:
  corpid: dingxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
  appkey: dingxxxxxxxxxxxxxxxx
  appsecret: 89QA-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-xxxx
  agentid: 2xxxxxxxxx

这里的配置信息是你的应用信息(在钉钉后台-应用管理)

三、代码实现

添加工具类 获取钉钉AccessToken

/**
 * 钉钉工具类
 * @date 2023-07-07 9:30
 */
@Slf4j
@Component
public class DingTalkUtil {

    @Value("${dingtalk.appKey}")
    private String appKey;

    @Value("${dingtalk.appSecret}")
    private String appSecret;

    /**
     * 获取钉钉AccessToken
     *
     * @return
     */
    public String getAccessToken() {
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
            OapiGettokenRequest req = new OapiGettokenRequest();
            req.setAppkey(appKey);
            req.setAppsecret(appSecret);
            req.setHttpMethod("GET");
            OapiGettokenResponse rsp = client.execute(req);
            if (rsp.getErrcode() == 0) {
                return rsp.getAccessToken();
            } else {
                throw new JeecgBootException("获取dingtalk授权失败!");
            }
        } catch (ApiException e) {
            e.printStackTrace();
        }

        return null;
    }

}

调用钉钉接口之前都是需要用到access_token校验的,接着调用用户电话获得钉钉的userId(某个人在企业里的唯一ID)

java 复制代码
/**
     * 获取钉钉的用户的userid
     *
     * @param phone 用户电话
     * @return 钉钉用户内部userId
     */
    public String getDingTalkUserId(String phone) throws Exception {

        String accessToken = this.getAccessToken();
        if (accessToken == null) {
            throw new Exception("获取到access_token失败!");
        }
        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, accessToken);
            String userId = rsp.getResult().getUserid();
            return userId;
        } catch (ApiException e) {
            log.error("请求获取钉钉用户的userid失败:{}", e.getErrMsg());
        }
        return null;
    }

发送消息工具类(可给单个或多个人发送)

java 复制代码
package org.jeecg.modules.aigoes.util;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.modules.message.util.DingTalkUtil;
import org.jeecg.modules.system.entity.SysTenant;
import org.jeecg.modules.system.service.ISysTenantService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.stream.Collectors;

/**
 * rwy
 * @date 2023-07-07 9:30
 */
@Slf4j
@Component
public class MessageUtils {

    @Resource
    private DingTalkUtil dingTalkUtil;

    // 钉钉发送消息给指定用户列表
    public void sendMessageNew(List<String> userIdList, String picUrl, String messageUrlDing, String text, String title) throws Exception {
        String accessToken = dingTalkUtil.getAccessToken();
        String messageUrl = "https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2?access_token=" + accessToken;

        JSONObject jsonObject = new JSONObject();
        //钉钉后台应用的agent_id
        jsonObject.put("agent_id", sysTenant.getAgentId());
        //推送的userId                                                              
      jsonObject.put("userid_list",userIdList.stream().collect(Collectors.joining(",")));
        jsonObject.put("to_all_user", false);
        JSONObject msgObj = new JSONObject();
        //消息类型
        msgObj.put("msgtype", "action_card");

        JSONObject textObj = new JSONObject();
        //标题
        textObj.put("title", title);
        //内容
        textObj.put("markdown", text);
        //按钮名称
        textObj.put("single_title", picUrl);
        //跳转地址 填小程序莫页面地址或微应用的
        textObj.put("single_url", messageUrlDing);
        msgObj.put("action_card",textObj);
        jsonObject.put("msg", msgObj);

        String jsonBody = jsonObject.toJSONString();
        System.out.println(jsonBody);

        //发送POST请求
        JSONObject response = httpPost(messageUrl, jsonBody, "UTF-8");
        System.out.println(response);
    }


   public JSONObject httpPost(String url, String requestData, String charset) throws IOException {
        URL apiUrl = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);

        // 设置请求头部
        connection.setRequestProperty("Content-Type", "application/json;charset=" + charset);

        // 发送请求数据
        try (OutputStream outputStream = connection.getOutputStream()) {
            outputStream.write(requestData.getBytes(charset));
            outputStream.flush();
        }

        // 获取响应结果
        try (InputStream inputStream = connection.getInputStream();
             BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, charset))) {
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            return JSONObject.parseObject(response.toString());
        }
    } 

}

这里需要注意的是你选择的消息通知类型 - 钉钉开放平台,我这里选择是卡片消息因为卡片消息支持整体跳转ActionCard样式和独立跳转ActionCard样式以及可以展示图片和添加多个按钮 样式和可玩性比较高。
测试发送钉消息

注意事项:小程序链接和微应用微应用唯一区别在这跳转地址 要跳转小程序前面是需要加 eapp:// 列如以下是这样的 eapp://pagesA/pages/Home/h-psy/ 而微应用不用加

java 复制代码
/**
     * 发送钉消息
     * @return
     * @throws Exception
     */
    @GetMapping("/cs2")
    public Result<?> cs() throws Exception {
        String headteacherId = "661xxxxxxxxxxxxxxx";
        messageUtils.sendMessageNew(Collections.singletonList(headteacherId),
                "点击查看详情","pagesA/pages/Home/h-psy/mood",
                "### <font color=#04CFFF>测试天气消息</font>  \n  **天气还不错。**",
                "天气报告");
        return Result.OK();
    }

四、调试API Explorer

钉钉专门的API调用工具可以自己试试API Explorer

1.根据自己应用的appKey和appSecret来获取accessToken。

  1. 工作通知-异步发送工作通知

填入内容 然后往下拉找到我们要发的消息类型我这里是卡片消息(这里你也可以选别的消息类型)填入必填的参数再点发起调用 也是能够成功发送的。

最后希望能帮助到你们。

相关推荐
爷可是个天才1 小时前
uniapp小程序IOS端,uni.createInnerAudioContext()无声音
小程序·uni-app
白臻5 小时前
小程序 npm 支持
前端·小程序·npm
guanpinkeji8 小时前
剧本杀小程序:助力商家发展,提高游戏体验
游戏·小程序·游戏开发·小程序开发·剧本杀·剧本杀小程序
酷爱码9 小时前
新闻电影资讯类小程序模板源码
小程序
Conan_Ritchie10 小时前
微信小程序简历Demo
微信小程序·小程序
酷爱码12 小时前
旅游计划定制小程序网页模板源码
小程序·旅游
努力学习的木子18 小时前
uniapp如何隐藏默认的页面头部导航栏,uniapp开发小程序如何隐藏默认的页面头部导航栏
前端·小程序·uni-app
guanpinkeji1 天前
家政小程序的开发,带动市场快速发展,提高家政服务质量
小程序·小程序开发·家政·家政小程序·家政服务小程序
Cc_Debugger1 天前
微信小程序消息通知(一次订阅)
微信小程序·小程序
栗豆包1 天前
【计算机毕业设计】020基于weixin小程序订餐系统
小程序·课程设计