Springboot整合飞书向群组/指定个人发送消息/飞书登录

本文主要是介绍Springboot整合飞书向群组/指定个人发送消息/飞书登录,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Springboot整合飞书向群组发送消息

  1. 飞书开放平台创建企业自建应用

image.png

  1. 添加应用能力-机器人

image.png

  1. 创建完成后,进入应用详情页,可以在首页看到 App Id 和 App Secret

image.png
image.png

  1. 在飞书pc端创建一群机器人

image.png
image.png
image.png
image.png
image.png

  1. 此处可以拿到该机器人的webhook地址,通过https的方式,也可以调用发送消息

image.png

  1. 从右侧菜单中,进入“安全设置”页面,配置回调地址

image.png

  1. Springboot进行整合通过发送http请求
package com.admin.manager.core;import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.admin.manager.api.StartApplication;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.request.AuthFeishuRequest;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;/*** @author zr 2024/3/25*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = StartApplication.class)
@Slf4j
public class LarkTest {@Testpublic void name() {sendMessage("test");}public static void sendMessage(String msg){String webHookUrl = "https://open.feishu.cn/open-apis/bot/v2/hook/e3d13a69-e777-4499-a1c9-e1ae0580a248";//请求的JSON数据,这里用map在工具类里转成json格式Map<String,Object> json=new HashMap();Map<String,Object> text=new HashMap();json.put("msg_type", "text");text.put("text", "项目告警通知:" + msg);json.put("content", text);//发送post请求String result = HttpRequest.post(webHookUrl).body(JSON.toJSONString(json), "application/json;charset=UTF-8").execute().body();System.out.println(result);}
}
  1. 测试通过,后续可以自行封装工具类或service

image.png

Springboot整合飞书向指定人员发送消息

其实这个就是两个步骤

  1. 获取人员列表信息

image.png

  1. 从人员列表中选出一个人员,拿到userId,发送对应消息即可

image.png

飞书开放平台-接口列表
飞书开放平台-接口调试平台
image.png
image.png

image.png

SDK 使用文档:https://github.com/larksuite/oapi-sdk-java/tree/v2_main
image.png

如果不需要通过机器人给群发送消息可以先不用webHookUrl

lark:webHookUrl: https://open.feishu.cn/open-apis/bot/v2/hook/xxxxappId: cli_xxxxappSecret: oiB2zcxxxx
  • getEmployees原飞书接口的返回对象属性很多,我只取了userId和name封装为LarkUser,有需要的可以自行参照文档取出自己需要的值,具体字段在Employee中
  • Client client = Client.newBuilder(“YOUR_APP_ID”, “YOUR_APP_SECRET”).build();是飞书官方提供的sdk,可以通过client直接对接口进行操作
package com.admin.manager.core.service;import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.admin.manager.core.exception.BusinessException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lark.oapi.Client;
import com.lark.oapi.service.ehr.v1.model.Employee;
import com.lark.oapi.service.ehr.v1.model.ListEmployeeReq;
import com.lark.oapi.service.ehr.v1.model.ListEmployeeResp;
import com.lark.oapi.service.im.v1.model.CreateMessageReq;
import com.lark.oapi.service.im.v1.model.CreateMessageReqBody;
import com.lark.oapi.service.im.v1.model.CreateMessageResp;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;import javax.annotation.PostConstruct;
import java.util.*;
import java.util.stream.Collectors;/*** 飞书工具** @author zr 2024/3/26*/
@Service
@Slf4j
public class LarkService {public static Client client;@Value("${lark.appId}")private String appId;@Value("${lark.appSecret}")private String appSecret;@Value("${lark.webHookUrl}")private String webHookUrl;@PostConstructpublic void init() {this.client =  Client.newBuilder(appId, appSecret).build();}/**** @param msg*/public  void sendMessageToGroup(String msg) {//请求的JSON数据,这里用map在工具类里转成json格式Map<String, Object> json = new HashMap();Map<String, Object> text = new HashMap();text.put("text", "要素修改通知:" + msg);json.put("msg_type", "text");json.put("content", text);//发送post请求String result = HttpRequest.post(webHookUrl).body(JSON.toJSONString(json), "application/json;charset=UTF-8").execute().body();JSONObject res = JSON.parseObject(result);Integer code = (Integer) res.get("code");}/*** 发送消息给指定userid的员工* @param userId* @param msg* @return* @throws Exception*/public  Boolean sendMessageToPerson(String userId, String msg) throws Exception {HashMap<String, String> content = new HashMap<>();content.put("text", msg);// 创建请求对象CreateMessageReq req = CreateMessageReq.newBuilder().receiveIdType("user_id").createMessageReqBody(CreateMessageReqBody.newBuilder().receiveId(userId).msgType("text").content(JSON.toJSONString(content)).uuid(UUID.randomUUID().toString()).build()).build();// 发起请求CreateMessageResp resp = client.im().message().create(req);// 处理服务端错误if (!resp.success()) {log.info(String.format("code:%s,msg:%s,reqId:%s", resp.getCode(), resp.getMsg(), resp.getRequestId()));throw new BusinessException("飞书接口调用失败");}return true;}/*** 获取飞书员工列表** @return*/public  List<LarkUser> getEmployees() throws Exception {// 创建请求对象ListEmployeeReq req = ListEmployeeReq.newBuilder().userIdType("user_id").build();// 发起请求ListEmployeeResp resp = client.ehr().employee().list(req);// 处理服务端错误if (!resp.success()) {log.info(String.format("code:%s,msg:%s,reqId:%s", resp.getCode(), resp.getMsg(), resp.getRequestId()));throw new BusinessException("飞书接口调用失败");}Employee[] items = resp.getData().getItems();List<LarkUser> larkUsers = Arrays.stream(items).map(x -> {LarkUser larkUser = new LarkUser();larkUser.setUserId(x.getUserId());larkUser.setName(x.getSystemFields().getName());return larkUser;}).collect(Collectors.toList());return larkUsers;}/*** 获取tenantAccessToken** @return 返回null代表失败*/public  String getAccessToken() {String url = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal/";HashMap<String, Object> query = new HashMap<>();query.put("app_id", "cli_a68bb76781b8500e");query.put("app_secret", "oiB2zcIy3MVno2JjWRLBxgJqU2xZ5qWi");String res = HttpUtil.post(url, query);JSONObject resObject = JSON.parseObject(res);Integer code = (Integer) resObject.get("code");if (code == 0) {String appAccessToken = (String) resObject.get("app_access_token");String tenantAccessToken = (String) resObject.get("tenant_access_token");return tenantAccessToken;} else {return null;}}@Datapublic static class LarkUser{public String userId;public String name;}}

此处是需要userId,应该是选择指定的人来进行发送,因为是测试而我的账号刚好最后一个,所以我取集合的最后一个元素

package com.admin.manager.core;import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.admin.manager.api.StartApplication;
import com.admin.manager.core.service.LarkService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;import lombok.extern.slf4j.Slf4j;import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;import java.util.*;/*** @author zr 2024/3/25*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = StartApplication.class)
@Slf4j
public class LarkTest {@Autowiredprivate LarkService larkService;@Testpublic void name() {try {List<LarkService.LarkUser> employees = larkService.getEmployees();System.out.println(employees);LarkService.LarkUser larkUser = employees.get(employees.size() - 1);larkService.sendMessageToPerson(larkUser.getUserId(), "test");} catch (Exception e) {throw new RuntimeException(e);}}}

image.png

从右侧菜单中,进入“权限管理”页面,配置应用权限(选择自己所需的权限)

注:

  • 如需获取用户邮箱,请添加“获取用户邮箱”权限
  • 如需获取用户手机号,请添加“获取用户手机号”权限
  • 其他必选如“获取用户 userid”、“获取用户统一ID”、“获取用户基本信息”
  • 其他权限,请开发者根据自身要求添加

image.png

Springboot-JustAuth整合飞书登录

  1. 配置飞书回调地址http://localhost:8084/oauth/callback/FEISHU可以本地调试,其他环境需要更换ip或域名

image.png

  1. 配置人员(配置可以登录的人员,我这里设置的是全部人员,就不用手动加人了,也可以指定人员)

image.png

  1. 引入依赖
        <dependency><groupId>me.zhyd.oauth</groupId><artifactId>JustAuth</artifactId><version> 1.16.4</version></dependency>
  1. 配置
lark:#机器人地址(自己创建的)webHookUrl: https://open.feishu.cn/open-apis/bot/v2/hook/e3dxxxx#飞书回调地址loginHookUrl: http://localhost:8084/oauth/callback/FEISHU#登录成功重定向地址(根据自己需要配置)redirectUrl: http://localhost:9528/dashboard#token有效期expiry: 12#飞书appIdappId: cli_a69e5b6e0xxxx#飞书appSecretappSecret: ZQ1nqsQ4i4FovYxxxxx
  1. 对应service
package com.admin.manager.core.service;import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.admin.manager.core.exception.BusinessException;
import com.admin.manager.core.model.Result;
import com.admin.manager.core.model.dto.LarkUserInfo;
import com.admin.manager.core.model.dto.SsoResultResDto;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lark.oapi.Client;
import com.lark.oapi.service.ehr.v1.model.Employee;
import com.lark.oapi.service.ehr.v1.model.ListEmployeeReq;
import com.lark.oapi.service.ehr.v1.model.ListEmployeeResp;
import com.lark.oapi.service.im.v1.model.CreateMessageReq;
import com.lark.oapi.service.im.v1.model.CreateMessageReqBody;
import com.lark.oapi.service.im.v1.model.CreateMessageResp;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthFeishuRequest;
import me.zhyd.oauth.request.AuthRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;import javax.annotation.PostConstruct;
import java.util.*;
import java.util.stream.Collectors;/*** 飞书工具** @author zr 2024/3/26*/
@Service
@Slf4j
public class LarkService {public static Client client;@Value("${lark.appId}")private String appId;@Value("${lark.appSecret}")private String appSecret;@Value("${lark.redirectUrl}")public String redirectUrl;@Value("${lark.expiry}")public Integer expiry;@Value("${lark.webHookUrl}")private String webHookUrl;@Value("${lark.loginHookUrl}")private String loginHookUrl;@Autowired//此处ssoService是获取用户信息,可以改成自己所需要的用户信息服务private SsoService ssoService;@PostConstructpublic void init() {this.client =  Client.newBuilder(appId, appSecret).build();}/**** @param msg*/public  void sendMessageToGroup(String msg) {//请求的JSON数据,这里用map在工具类里转成json格式Map<String, Object> json = new HashMap();Map<String, Object> text = new HashMap();text.put("text", "要素修改通知:" + msg);json.put("msg_type", "text");json.put("content", text);//发送post请求String result = HttpRequest.post(webHookUrl).body(JSON.toJSONString(json), "application/json;charset=UTF-8").execute().body();JSONObject res = JSON.parseObject(result);Integer code = (Integer) res.get("code");}/*** 发送消息给指定userid的员工* @param userId* @param msg* @return* @throws Exception*/public  Boolean sendMessageToPerson(String userId, String msg) throws Exception {HashMap<String, String> content = new HashMap<>();content.put("text", msg);// 创建请求对象CreateMessageReq req = CreateMessageReq.newBuilder().receiveIdType("union_id").createMessageReqBody(CreateMessageReqBody.newBuilder().receiveId(userId).msgType("text").content(JSON.toJSONString(content)).uuid(UUID.randomUUID().toString()).build()).build();// 发起请求CreateMessageResp resp = client.im().message().create(req);// 处理服务端错误if (!resp.success()) {log.info(String.format("code:%s,msg:%s,reqId:%s", resp.getCode(), resp.getMsg(), resp.getRequestId()));throw new BusinessException("飞书接口调用失败");}return true;}/*** 获取飞书员工列表** @return*/public  List<LarkUser> getEmployees() throws Exception {// 创建请求对象ListEmployeeReq req = ListEmployeeReq.newBuilder().userIdType("open_id").build();// 发起请求ListEmployeeResp resp = client.ehr().employee().list(req);// 处理服务端错误if (!resp.success()) {log.info(String.format("code:%s,msg:%s,reqId:%s", resp.getCode(), resp.getMsg(), resp.getRequestId()));throw new BusinessException("飞书接口调用失败");}Employee[] items = resp.getData().getItems();List<LarkUser> larkUsers = Arrays.stream(items).map(x -> {LarkUser larkUser = new LarkUser();larkUser.setUserId(x.getUserId());larkUser.setName(x.getSystemFields().getName());return larkUser;}).collect(Collectors.toList());return larkUsers;}/*** 获取tenantAccessToken** @return 返回null代表失败*/public  String getAccessToken() {String url = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal/";HashMap<String, Object> query = new HashMap<>();query.put("app_id", "cli_a68bb76781b8500e");query.put("app_secret", "oiB2zcIy3MVno2JjWRLBxgJqU2xZ5qWi");String res = HttpUtil.post(url, query);JSONObject resObject = JSON.parseObject(res);Integer code = (Integer) resObject.get("code");if (code == 0) {String appAccessToken = (String) resObject.get("app_access_token");String tenantAccessToken = (String) resObject.get("tenant_access_token");return tenantAccessToken;} else {return null;}}public AuthRequest getAuthRequest() {return  new AuthFeishuRequest(AuthConfig.builder().clientId(appId).clientSecret(appSecret).redirectUri(loginHookUrl).build());}
//    http://127.0.0.1:8084/oauth/renderpublic Result<SsoResultResDto.SsoUserInfo> login(AuthCallback callback) {AuthRequest authRequest = getAuthRequest();AuthResponse<AuthUser> authResponse = authRequest.login(callback);log.info("飞书登录返回:{}",JSON.toJSONString(authResponse));if (authResponse.ok()){JSONObject  data = (JSONObject) authResponse.getData().getRawUserInfo().get("data");log.info(JSON.toJSONString(data));LarkUserInfo larkUserInfo = data.toJavaObject(LarkUserInfo.class);AuthToken token = authResponse.getData().getToken();//此处ssoService是获取用户信息,可以改成自己所需要的用户信息服务Result<SsoResultResDto.SsoUserInfo> ssoUserInfo = ssoService.getSsoUserInfoByOpenId(larkUserInfo.getUnionId());log.info("SsoUserInfo 返回:{}",JSON.toJSONString(authResponse));return ssoUserInfo;}else {return Result.failure(authResponse.getMsg());}}@Datapublic static class LarkUser{public String userId;public String name;}
}
  1. 对应Controller
package com.admin.manager.api.controller;import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.ReUtil;
import com.admin.manager.core.model.Result;
import com.admin.manager.core.model.dto.SsoResultResDto;
import com.admin.manager.core.service.LarkService;
import com.admin.manager.core.util.RedisUtil;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.request.AuthFeishuRequest;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;/*** @author zr 2024/3/28*/
@RestController
@Api(tags = "认证")
@RequestMapping("/oauth")
public class RestAuthController {@Autowiredprivate LarkService larkService;@GetMapping("/render")@ApiOperation(value = "飞书登录")public void renderAuth(HttpServletResponse response) throws IOException {AuthRequest authRequest = larkService.getAuthRequest();response.sendRedirect(authRequest.authorize(AuthStateUtils.createState()));}@GetMapping("/callback/FEISHU")@ApiOperation(value = "飞书回调")public void  callback(AuthCallback callback, HttpServletResponse response) throws IOException {Result<SsoResultResDto.SsoUserInfo> res = larkService.login(callback);//此处生成一个12位的tokenString token = RandomUtil.randomString(12);//重定向携带该tokenString redirectUrl = larkService.redirectUrl + "?token=" + token;//将token存入redisRedisUtil.StringOps.setEx("admin:"+token, JSON.toJSONString(res.getResult()), larkService.expiry, TimeUnit.HOURS);response.sendRedirect(redirectUrl);}//重定向后前端拿到token访问这个接口拿到用户信息@GetMapping("/auth")@ApiOperation(value = "获取用户信息")public Result<SsoResultResDto.SsoUserInfo> auth(@RequestParam("token") String token) {String userInfo = RedisUtil.StringOps.get("admin:" + token);if (StringUtils.isNotEmpty(userInfo)){SsoResultResDto.SsoUserInfo ssoUserInfo = JSON.parseObject(userInfo, SsoResultResDto.SsoUserInfo.class);return Result.success(ssoUserInfo);}else {return Result.failure("未登录");}}
}
  1. 测试

http://localhost:8084/oauth/render(记得换端口)
image.png
登录成功后,飞书会回调/oauth/callback/FEISHU接口,我这里是示范地址记得修改
image.png
之后前端就可以调用/oauth/auth接口拿token换用户信息了

这篇关于Springboot整合飞书向群组/指定个人发送消息/飞书登录的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/971470

相关文章

Spring Boot集成/输出/日志级别控制/持久化开发实践

《SpringBoot集成/输出/日志级别控制/持久化开发实践》SpringBoot默认集成Logback,支持灵活日志级别配置(INFO/DEBUG等),输出包含时间戳、级别、类名等信息,并可通过... 目录一、日志概述1.1、Spring Boot日志简介1.2、日志框架与默认配置1.3、日志的核心作用

破茧 JDBC:MyBatis 在 Spring Boot 中的轻量实践指南

《破茧JDBC:MyBatis在SpringBoot中的轻量实践指南》MyBatis是持久层框架,简化JDBC开发,通过接口+XML/注解实现数据访问,动态代理生成实现类,支持增删改查及参数... 目录一、什么是 MyBATis二、 MyBatis 入门2.1、创建项目2.2、配置数据库连接字符串2.3、入

Springboot项目启动失败提示找不到dao类的解决

《Springboot项目启动失败提示找不到dao类的解决》SpringBoot启动失败,因ProductServiceImpl未正确注入ProductDao,原因:Dao未注册为Bean,解决:在启... 目录错误描述原因解决方法总结***************************APPLICA编

深度解析Spring Security 中的 SecurityFilterChain核心功能

《深度解析SpringSecurity中的SecurityFilterChain核心功能》SecurityFilterChain通过组件化配置、类型安全路径匹配、多链协同三大特性,重构了Spri... 目录Spring Security 中的SecurityFilterChain深度解析一、Security

SpringBoot多环境配置数据读取方式

《SpringBoot多环境配置数据读取方式》SpringBoot通过环境隔离机制,支持properties/yaml/yml多格式配置,结合@Value、Environment和@Configura... 目录一、多环境配置的核心思路二、3种配置文件格式详解2.1 properties格式(传统格式)1.

Apache Ignite 与 Spring Boot 集成详细指南

《ApacheIgnite与SpringBoot集成详细指南》ApacheIgnite官方指南详解如何通过SpringBootStarter扩展实现自动配置,支持厚/轻客户端模式,简化Ign... 目录 一、背景:为什么需要这个集成? 二、两种集成方式(对应两种客户端模型) 三、方式一:自动配置 Thick

Spring WebClient从入门到精通

《SpringWebClient从入门到精通》本文详解SpringWebClient非阻塞响应式特性及优势,涵盖核心API、实战应用与性能优化,对比RestTemplate,为微服务通信提供高效解决... 目录一、WebClient 概述1.1 为什么选择 WebClient?1.2 WebClient 与

Java.lang.InterruptedException被中止异常的原因及解决方案

《Java.lang.InterruptedException被中止异常的原因及解决方案》Java.lang.InterruptedException是线程被中断时抛出的异常,用于协作停止执行,常见于... 目录报错问题报错原因解决方法Java.lang.InterruptedException 是 Jav

深入浅出SpringBoot WebSocket构建实时应用全面指南

《深入浅出SpringBootWebSocket构建实时应用全面指南》WebSocket是一种在单个TCP连接上进行全双工通信的协议,这篇文章主要为大家详细介绍了SpringBoot如何集成WebS... 目录前言为什么需要 WebSocketWebSocket 是什么Spring Boot 如何简化 We

java中pdf模版填充表单踩坑实战记录(itextPdf、openPdf、pdfbox)

《java中pdf模版填充表单踩坑实战记录(itextPdf、openPdf、pdfbox)》:本文主要介绍java中pdf模版填充表单踩坑的相关资料,OpenPDF、iText、PDFBox是三... 目录准备Pdf模版方法1:itextpdf7填充表单(1)加入依赖(2)代码(3)遇到的问题方法2:pd