springboot集成微软teams的实例代码
前言
最近做了一个有关微软的平台teams开发,在国内用微软teams聊天工具的少之又少,整个亚洲也没什么开发的实例,官方文档写的有点乱,在没有第三方支持下开发有点头疼。需求是做一个管理后台跟teams打通,支持各种通告发送,以及撤回。没时间具体些,用的东西丢在上面用上的可以参考。
【springboot集成微软teams的实例代码】添加依赖
com.microsoft.graph microsoft-graph2.3.2 com.microsoft.graph microsoft-graph-core1.0.5 com.microsoft.graph microsoft-graph-auth0.3.0-SNAPSHOT com.microsoft.azure msal4j1.0.0
业务逻辑层
package com.tg.admin.service; import com.tg.admin.utils.CommonResult; import java.util.Map; /** * 用户信息 * * @author summer.chou * @date 2020/11/26 */public interface SplGraphService {/*** 获取token(自动刷新)** @return token*/String getToken(); * 获取用户所属团队* @return 结果CommonResult
业务逻辑实现
package com.tg.admin.service.impl; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.microsoft.graph.models.extensions.IGraphServiceClient; import com.microsoft.graph.requests.extensions.GraphServiceClient; import com.tg.admin.service.ChannelUserLogService; import com.tg.admin.service.SplGraphService; import com.tg.admin.utils.*; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Lazy; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import java.util.HashMap; import java.util.List; import java.util.Map; /** * teams Graph模块 第三方接口调用封装 * * @author summer.chou * @date 2020/12/30 */@Service@Slf4jpublic class SplGraphServiceImpl implements SplGraphService {@Value("#{'${teams.graph.scopes}'.split(',')}")private List scopes; @Value("${teams.graph.clientId}")private String clientId; @Value("${teams.graph.team.url}")private String teamsUrl; @Value("${teams.graph.channel.url}")private String channelUrl; @Value("${teams.graph.add.channel.url}")private String addChannelUrl; @Value("${teams.graph.ms.url}")private String msUrl; @Value("${teams.graph.member.url}")private String memberUrl; @Value("${teams.graph.add.channel.members.url}")private String addChannelMembersUrl; @Value("${teams.graph.account}")private String account; @Value("${teams.graph.password}")private String password; private RedisUtil redisUtil; private RestTemplate restTemplate; private ChannelUserLogService channelUserLogService; public SplGraphServiceImpl(RestTemplate restTemplate, RedisUtil redisUtil, @Lazy ChannelUserLogService channelUserLogService) {this.restTemplate = restTemplate; this.redisUtil = redisUtil; this.channelUserLogService = channelUserLogService; }@Overridepublic String getToken() {Object token = redisUtil.get(Constants.ADMIN_TOKEN_KEY + account); try {if (token == null) {MyAuthenticationProvider authProvider = new MyAuthenticationProvider(clientId, scopes, account, password); IGraphServiceClient graphClient = GraphServiceClient.builder().authenticationProvider(authProvider).buildClient(); graphClient.me().buildRequest().get(); token = authProvider.getToken(); redisUtil.set(Constants.ADMIN_TOKEN_KEY + account, token, Constants.TOKEN_EXPIRES_TIME); }} catch (Exception e) {log.info("获取teams-graph,获取token接口异常", e); }return token.toString(); public CommonResultgetTeamsInfo() {JSONArray value = https://www.it610.com/article/null; Map result = new HashMap<>(); JSONObject jsonObject = new JSONObject(); log.info("调用temas获取团队信息:teamsUrl{}", teamsUrl); //设置请求头HttpHeaders headers = new HttpHeaders(); headers.set("Authorization", getToken()); headers.setContentType(MediaType.APPLICATION_JSON_UTF8); jsonObject = RestTemplateUtils.requestByGet(teamsUrl, null, restTemplate, headers); log.info("返回值:jsonObject:{}", jsonObject.toJSONString()); value = https://www.it610.com/article/jsonObject.getJSONArray("value"); result.put("value", value); e.printStackTrace(); return CommonResult.ok(result); public CommonResult getChannel(String teamId) {JSONArray array = null; String url = channelUrl.replace("{team-id}", teamId); log.info("调用teams获取用户渠道url:{}", url); jsonObject = RestTemplateUtils.requestByGet(url, null, restTemplate, headers); log.info("返回结果:jsonObject:{}", jsonObject.toJSONString()); array = jsonObject.getJSONArray("value"); result.put("value", array); public CommonResult getMember(String teamsId, String channelId) {String url = memberUrl.replace("{team-id}", teamsId).replace("{channel-id}", channelId); log.info("调用teams获取渠道成员:url:{}", url); public CommonResult sendMs(String content, String teamId, String channelId) {String url = msUrl.replace("{team-id}", teamId).replace("{channel-id}", channelId); log.info("调用teams发送消息:url:{}", url); Map map = new HashMap(); Map body = new HashMap<>(); map.put("content", content); map.put("contentType", "html"); body.put("body", map); jsonObject = RestTemplateUtils.requestByPost(url, body, restTemplate, headers); log.info("返回结果:jsonObject:{}", jsonObject.toJSONString()); return CommonResult.ok(); public CommonResult addChannel(String displayName, String description, String teamId) {String url = addChannelUrl.replace("{id}", teamId); log.info("调用teams添加渠道:url:{}", url); map.put("displayName", displayName); map.put("description", description); jsonObject = RestTemplateUtils.requestByPost(url, map, restTemplate, headers); if (jsonObject != null) {result.put("id", jsonObject.getString("id")); public CommonResult addMembers(String teamId, String channelId, String userNum) {String url = addChannelMembersUrl.replace("{team-id}", teamId).replace("{channel-id}", channelId); log.info("调用teams添加成员:url:{}", url); map.put("@odata.type", "#microsoft.graph.aadUserConversationMember"); JSONArray roles = new JSONArray(); roles.add("owner"); map.put("roles", roles); }
RestTemplateUtils 工具类
package com.tg.admin.utils; import com.alibaba.fastjson.JSONObject; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriComponentsBuilder; import java.util.HashMap; import java.util.Map; /** * RestTemplateUtils工具类 * * @author summer.chou * @date 2020/11/26 */@Componentpublic class RestTemplateUtils { /*** 根据get方式请求接口(复合类型get请求,支持所有get请求)** @param url请求路劲* @param map请求参数 无传null* @param restTemplate restTemplate对象* @return json*/public static JSONObject requestByGet(String url, HashMap map, RestTemplate restTemplate, HttpHeaders headers) { // header填充HttpEntityrequest = new HttpEntity(null, headers); UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url); //ResponseEntity responseEntity; ResponseEntity responseEntity; //如果存在參數if (map != null) {for (Map.Entry e :map.entrySet()) {//构建查询参数builder.queryParam(e.getKey(), e.getValue()); }//拼接好参数后的URl//test.com/url?param1={param1}¶m2={param2}; String reallyUrl = builder.build().toString(); responseEntity = restTemplate.exchange(reallyUrl, HttpMethod.GET, request, JSONObject.class); } else {responseEntity = restTemplate.exchange(url, HttpMethod.GET, request, JSONObject.class); } return responseEntity.getBody(); } /*** 根据Post方式请求接口(复合类型,post支持所有json格式传参请求post请求)** @param url请求路径* @param map请求参数(无参数传null)* @param restTemplate restTemplate对象* @return json*/public static JSONObject requestByPost(String url, Map map, RestTemplate restTemplate, HttpHeaders headers) {// header填充,map填充HttpEntity request = new HttpEntity (map, headers); ResponseEntity entity = restTemplate.postForEntity(url, request, JSONObject.class); return entity.getBody(); } }
测试接口
package com.tg.admin.controller; import com.tg.admin.service.SplGraphService; import com.tg.admin.utils.CommonResult; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.web.bind.annotation.*; @Api(description = "teams-graph模块(第三方测试接口)")@RestController@RequestMapping("/graph")@RefreshScope@Slf4j@Deprecated //添加过期注解,接口保留方便后期异常排查public class GraphController {private SplGraphService tgService; public GraphController(SplGraphService tgService) {this.tgService = tgService; }@ApiOperation("获取所属团队信息")@GetMapping("/getTeamsInfo")public CommonResult getTeamsInfo() {return tgService.getTeamsInfo(); @ApiOperation("获取token")@GetMapping("/getToken")public CommonResult getToken() {return CommonResult.ok(tgService.getToken()); @ApiOperation("获取用户所属渠道")@ApiImplicitParams({@ApiImplicitParam(name = "teamId", value = "https://www.it610.com/article/团队Id", dataType = "string", required = true)})@GetMapping("/getChannel")public CommonResult getChannel(@RequestParam(value = "https://www.it610.com/article/teamId") String teamId) {return tgService.getChannel(teamId); @ApiOperation("获取渠道下的成员")@ApiImplicitParam(name = "teamId", value = "https://www.it610.com/article/团队Id", dataType = "string", required = true),@ApiImplicitParam(name = "channelId", value = "https://www.it610.com/article/渠道Id", dataType = "string", required = true)@GetMapping("/getMember")public CommonResult getMember(@RequestParam(value = "https://www.it610.com/article/teamId") String teamId,@RequestParam(value = "https://www.it610.com/article/channelId") String channelId) {return tgService.getMember(teamId, channelId); @ApiOperation("创建团队下的渠道(备用接口)")@ApiImplicitParam(name = "displayName", value = "https://www.it610.com/article/渠道名称", dataType = "string", required = true),@ApiImplicitParam(name = "description", value = "https://www.it610.com/article/渠道备注", dataType = "string", required = true)@PostMapping("/addChannel")public CommonResult addChannel(@RequestParam(value = "https://www.it610.com/article/teamId") String teamId,@RequestParam(value = "https://www.it610.com/article/displayName") String displayName,@RequestParam(value = "https://www.it610.com/article/description") String description) {return tgService.addChannel(displayName, description, teamId); @ApiOperation("向渠道里面添加成员(备用接口)")@ApiImplicitParam(name = "channelId", value = "https://www.it610.com/article/渠道ID", dataType = "string", required = true),@ApiImplicitParam(name = "userNum", value = "https://www.it610.com/article/用户Id", dataType = "string", required = true)@PostMapping("/addMembers")public CommonResult addMembers(@RequestParam(value = "https://www.it610.com/article/teamId") String teamId,@RequestParam(value = "https://www.it610.com/article/channelId") String channelId,@RequestParam(value = "https://www.it610.com/article/userNum") String userNumreturn tgService.addMembers(teamId, channelId, userNum); @ApiOperation("通过teamId,channelId发送消息")@PostMapping("/sendMs")@ApiImplicitParam(name = "content", value = "https://www.it610.com/article/内容", dataType = "string", required = true),public CommonResult sendMs(@RequestParam(value = "https://www.it610.com/article/teamId") String teamId,@RequestParam(value = "https://www.it610.com/article/content") String content,@RequestParam(value = "https://www.it610.com/article/channelId") String channelId) {return tgService.sendMs(content, teamId, channelId); }
yml 配置
teams:graph:#微软master账号,密码account: 管理员账号password: 管理员密码add:channel:members:url: https://graph.microsoft.com/v1.0/teams/{team-id}/channels/{channel-id}/membersurl: https://graph.microsoft.com/v1.0/teams/{id}/channelschannel:url: https://graph.microsoft.com/v1.0/teams/{team-id}/channelsclientId: e730901a-8bf3-472b-93dd-afe79713bc5bmember:url: https://graph.microsoft.com/v1.0/teams/{team-id}/channels/{channel-id}/membersms:url: https://graph.microsoft.com/v1.0/teams/{team-id}/channels/{channel-id}/messagesscopes: Group.Read.All,User.Readteam:url: https://graph.microsoft.com/v1.0/me/joinedTeams
到此这篇关于springboot集成微软teams的文章就介绍到这了,更多相关springboot集成微软teams内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
推荐阅读
- springboot~ObjectMapper~dto到entity的自动赋值
- springboot基于maven多模块项目搭建(直接启动webApplication)
- springboot情操陶冶-SpringApplication
- SpringBoot加载运行时监听器(SpringApplicationRunListeners)
- SpringBoot2.x 给Controller的RequestMapping添加统一前缀
- win8/win10系统删除自带微软输入法的办法
- springboot[2.3.4.RELEASE]application.properties常用配置
- Android | 零代码快速集成AGC崩溃服务
- Win10电脑加速技巧
- 建立Azure Dev Ops持续集成和持续交付(CICD)(准备好Azure Web App资源)