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

相关文章

Java五子棋之坐标校正

上篇针对了Java项目中的解构思维,在这篇内容中我们不妨从整体项目中拆解拿出一个非常重要的五子棋逻辑实现:坐标校正,我们如何使漫无目的鼠标点击变得有序化和可控化呢? 目录 一、从鼠标监听到获取坐标 1.MouseListener和MouseAdapter 2.mousePressed方法 二、坐标校正的具体实现方法 1.关于fillOval方法 2.坐标获取 3.坐标转换 4.坐

Spring Cloud:构建分布式系统的利器

引言 在当今的云计算和微服务架构时代,构建高效、可靠的分布式系统成为软件开发的重要任务。Spring Cloud 提供了一套完整的解决方案,帮助开发者快速构建分布式系统中的一些常见模式(例如配置管理、服务发现、断路器等)。本文将探讨 Spring Cloud 的定义、核心组件、应用场景以及未来的发展趋势。 什么是 Spring Cloud Spring Cloud 是一个基于 Spring

Javascript高级程序设计(第四版)--学习记录之变量、内存

原始值与引用值 原始值:简单的数据即基础数据类型,按值访问。 引用值:由多个值构成的对象即复杂数据类型,按引用访问。 动态属性 对于引用值而言,可以随时添加、修改和删除其属性和方法。 let person = new Object();person.name = 'Jason';person.age = 42;console.log(person.name,person.age);//'J

java8的新特性之一(Java Lambda表达式)

1:Java8的新特性 Lambda 表达式: 允许以更简洁的方式表示匿名函数(或称为闭包)。可以将Lambda表达式作为参数传递给方法或赋值给函数式接口类型的变量。 Stream API: 提供了一种处理集合数据的流式处理方式,支持函数式编程风格。 允许以声明性方式处理数据集合(如List、Set等)。提供了一系列操作,如map、filter、reduce等,以支持复杂的查询和转

Java面试八股之怎么通过Java程序判断JVM是32位还是64位

怎么通过Java程序判断JVM是32位还是64位 可以通过Java程序内部检查系统属性来判断当前运行的JVM是32位还是64位。以下是一个简单的方法: public class JvmBitCheck {public static void main(String[] args) {String arch = System.getProperty("os.arch");String dataM

详细分析Springmvc中的@ModelAttribute基本知识(附Demo)

目录 前言1. 注解用法1.1 方法参数1.2 方法1.3 类 2. 注解场景2.1 表单参数2.2 AJAX请求2.3 文件上传 3. 实战4. 总结 前言 将请求参数绑定到模型对象上,或者在请求处理之前添加模型属性 可以在方法参数、方法或者类上使用 一般适用这几种场景: 表单处理:通过 @ModelAttribute 将表单数据绑定到模型对象上预处理逻辑:在请求处理之前

eclipse运行springboot项目,找不到主类

解决办法尝试了很多种,下载sts压缩包行不通。最后解决办法如图: help--->Eclipse Marketplace--->Popular--->找到Spring Tools 3---->Installed。

JAVA读取MongoDB中的二进制图片并显示在页面上

1:Jsp页面: <td><img src="${ctx}/mongoImg/show"></td> 2:xml配置: <?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001

Java面试题:通过实例说明内连接、左外连接和右外连接的区别

在 SQL 中,连接(JOIN)用于在多个表之间组合行。最常用的连接类型是内连接(INNER JOIN)、左外连接(LEFT OUTER JOIN)和右外连接(RIGHT OUTER JOIN)。它们的主要区别在于它们如何处理表之间的匹配和不匹配行。下面是每种连接的详细说明和示例。 表示例 假设有两个表:Customers 和 Orders。 Customers CustomerIDCus

22.手绘Spring DI运行时序图

1.依赖注入发生的时间 当Spring loC容器完成了 Bean定义资源的定位、载入和解析注册以后,loC容器中已经管理类Bean 定义的相关数据,但是此时loC容器还没有对所管理的Bean进行依赖注入,依赖注入在以下两种情况 发生: 、用户第一次调用getBean()方法时,loC容器触发依赖注入。 、当用户在配置文件中将<bean>元素配置了 lazy-init二false属性,即让