springboot集成微软teams的实例代码

前言

最近做了一个有关微软的平台teams开发,在国内用微软teams聊天工具的少之又少,整个亚洲也没什么开发的实例,官方文档写的有点乱,在没有第三方支持下开发有点头疼。需求是做一个管理后台跟teams打通,支持各种通告发送,以及撤回。没时间具体些,用的东西丢在上面用上的可以参考。

添加依赖

<dependency>
           <groupId>com.microsoft.graph</groupId>
           <artifactId>microsoft-graph</artifactId>
           <version>2.3.2</version>
       </dependency>
       <dependency>
           <groupId>com.microsoft.graph</groupId>
           <artifactId>microsoft-graph-core</artifactId>
           <version>1.0.5</version>
       </dependency>

       <dependency>
           <groupId>com.microsoft.graph</groupId>
           <artifactId>microsoft-graph-auth</artifactId>
           <version>0.3.0-SNAPSHOT</version>
       </dependency>
       <dependency>
           <groupId>com.microsoft.azure</groupId>
           <artifactId>msal4j</artifactId>
           <version>1.0.0</version>
       </dependency>

业务逻辑层

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<Map<String, Object>> getTeamsInfo();
     * 获取用户所属渠道
     * @param teamsId 团队ID
    CommonResult<Map<String, Object>> getChannel(String teamsId);
     * 根据teamsId、channelId获取用户信息
     * @param teamsId   团队ID
     * @param channelId 渠道ID
    CommonResult<Map<String, Object>> getMember(String teamsId, String channelId);
     * 发送消息
     * @param content   消息内容
     * @param teamId    团队ID
    CommonResult<Map<String, Object>> sendMs(String content, String teamId, String channelId);
     * 添加渠道
     * @param displayName 渠道名称
     * @param description 渠道备注
     * @param teamId      渠道ID
     * @return 渠道ID
    CommonResult<Map<String, Object>> addChannel(String displayName, String description, String teamId);
     * 添加成员
     * @param userNum   用户名称
    CommonResult<Map<String, Object>> addMembers(String teamId, String channelId, String userNum);
}

业务逻辑实现

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
@Slf4j
public class SplGraphServiceImpl implements SplGraphService {
    @Value("#{'${teams.graph.scopes}'.split(',')}")
    private List<String> 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;
    }
    @Override
    public 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 CommonResult<Map<String, Object>> getTeamsInfo() {
        JSONArray value = null;
        Map<String, Object> 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 = jsonObject.getJSONArray("value");
            result.put("value", value);
            e.printStackTrace();
        return CommonResult.ok(result);
    public CommonResult<Map<String, Object>> 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<Map<String, Object>> getMember(String teamsId, String channelId) {
            String url = memberUrl.replace("{team-id}", teamsId).replace("{channel-id}", channelId);
            log.info("调用teams获取渠道成员:url:{}", url);
    public CommonResult<Map<String, Object>> sendMs(String content, String teamId, String channelId) {
            String url = msUrl.replace("{team-id}", teamId).replace("{channel-id}", channelId);
            log.info("调用teams发送消息:url:{}", url);
            Map<String, Object> map = new HashMap<String, Object>();
            Map<String, Object> 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<Map<String, Object>> 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<Map<String, Object>> 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
 */
@Component
public class RestTemplateUtils {

    /**
     * 根据get方式请求接口(复合类型get请求,支持所有get请求)
     *
     * @param url          请求路劲
     * @param map          请求参数 无传null
     * @param restTemplate restTemplate对象
     * @return json
     */
    public static JSONObject requestByGet(String url, HashMap<String, Object> map, RestTemplate restTemplate, HttpHeaders headers) {

        // header填充
        HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity(null, headers);

        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
        //ResponseEntity responseEntity;
        ResponseEntity<JSONObject> responseEntity;
        //如果存在參數
        if (map != null) {
            for (Map.Entry<String, Object> e :
                    map.entrySet()) {
                //构建查询参数
                builder.queryParam(e.getKey(), e.getValue());
            }
            //拼接好参数后的URl//test.com/url?param1={param1}&param2={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<String, Object> map, RestTemplate restTemplate, HttpHeaders headers) {
        // header填充,map填充
        HttpEntity<Map<String, Object>> request = new HttpEntity<Map<String, Object>>(map, headers);
        ResponseEntity<JSONObject> 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 = "团队Id", dataType = "string", required = true)
    })
    @GetMapping("/getChannel")
    public CommonResult getChannel(@RequestParam(value = "teamId") String teamId) {
        return tgService.getChannel(teamId);
    @ApiOperation("获取渠道下的成员")
            @ApiImplicitParam(name = "teamId", value = "团队Id", dataType = "string", required = true),
            @ApiImplicitParam(name = "channelId", value = "渠道Id", dataType = "string", required = true)
    @GetMapping("/getMember")
    public CommonResult getMember(@RequestParam(value = "teamId") String teamId,
                                  @RequestParam(value = "channelId") String channelId) {
        return tgService.getMember(teamId, channelId);
    @ApiOperation("创建团队下的渠道(备用接口)")
            @ApiImplicitParam(name = "displayName", value = "渠道名称", dataType = "string", required = true),
            @ApiImplicitParam(name = "description", value = "渠道备注", dataType = "string", required = true)
    @PostMapping("/addChannel")
    public CommonResult addChannel(@RequestParam(value = "teamId") String teamId,
                                   @RequestParam(value = "displayName") String displayName,
                                   @RequestParam(value = "description") String description
    ) {
        return tgService.addChannel(displayName, description, teamId);
    @ApiOperation("向渠道里面添加成员(备用接口)")
            @ApiImplicitParam(name = "channelId", value = "渠道ID", dataType = "string", required = true),
            @ApiImplicitParam(name = "userNum", value = "用户Id", dataType = "string", required = true)
    @PostMapping("/addMembers")
    public CommonResult addMembers(@RequestParam(value = "teamId") String teamId,
                                   @RequestParam(value = "channelId") String channelId,
                                   @RequestParam(value = "userNum") String userNum
        return tgService.addMembers(teamId, channelId, userNum);
    @ApiOperation("通过teamId,channelId发送消息")
    @PostMapping("/sendMs")
            @ApiImplicitParam(name = "content", value = "内容", dataType = "string", required = true),
    public CommonResult sendMs(@RequestParam(value = "teamId") String teamId,
                               @RequestParam(value = "content") String content,
                               @RequestParam(value = "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}/members
        url: https://graph.microsoft.com/v1.0/teams/{id}/channels
    channel:
      url: https://graph.microsoft.com/v1.0/teams/{team-id}/channels
    clientId: e730901a-8bf3-472b-93dd-afe79713bc5b
    member:
      url: https://graph.microsoft.com/v1.0/teams/{team-id}/channels/{channel-id}/members
    ms:
      url: https://graph.microsoft.com/v1.0/teams/{team-id}/channels/{channel-id}/messages
    scopes: Group.Read.All,User.Read
    team:
      url: https://graph.microsoft.com/v1.0/me/joinedTeams

到此这篇关于springboot集成微软teams的文章就介绍到这了,更多相关springboot集成微软teams内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • 实战SpringBoot集成JWT实现token验证

    目录 环境搭建 1.新建一个SpringBoot项目Jwt-Demo,引入项目后面需要用到的jar包 2.数据库结构 3.配置文件application.properties 4.Entity包下新建一个User类 5.Dao包下新建一个UserDao 6.Service包下新建一个USerService 7.UseService的实现类UserServiceImp 8.controller包下新建一个UserController 9.在resource文件夹下新建一个Usermapper文件

  • SpringBoot集成极光推送完整实现代码

    目录 1.pom.xml 2.application.yml 3.MyJPushClient 4.test 工作中经常会遇到服务器向App推送消息的需求,一般企业中选择用极光推送的比较多,在集成极光时发现极光的文档并不完整,网上的文章也很多不能直接使用,这里列出我在工作中集成极光的全部代码,只需要按照如下代码保证一次性实现. 1.pom.xml <!-- 极光推送 begin --> <dependency> <groupId>cn.jpush.api</grou

  • springboot集成微软teams的实例代码

    前言 最近做了一个有关微软的平台teams开发,在国内用微软teams聊天工具的少之又少,整个亚洲也没什么开发的实例,官方文档写的有点乱,在没有第三方支持下开发有点头疼.需求是做一个管理后台跟teams打通,支持各种通告发送,以及撤回.没时间具体些,用的东西丢在上面用上的可以参考. 添加依赖 <dependency> <groupId>com.microsoft.graph</groupId> <artifactId>microsoft-graph</

  • springboot hazelcast缓存中间件的实例代码

    缓存来了 在dotnet平台有自己的缓存框架,在java springboot里当然了集成了很多,而且缓存的中间件也可以进行多种选择,向 redis , hazelcast 都是分布式的缓存中间件,今天主要说一下后者的实现. 添加依赖包 dependencies { compile("org.springframework.boot:spring-boot-starter-cache") compile("com.hazelcast:hazelcast:3.7.4"

  • springboot 集成支付宝支付的示例代码

    最简单的springboot集成支付宝 1 注册沙箱 沙箱是一个模拟环境登录,百度蚂蚁金服开放平台,支付宝扫码登录如下 然后沙箱需要注册一下,非常之简单,注册好以后进入到如下页面,选沙箱工具,然后下载一个生成密钥的工具.然后解压按照里面的readme生成公私密钥, 选择沙箱应用 上传公钥即可..沙箱到这里就基本完成了,里面还有沙箱版本的的android app可以下载下来. java 程序 1 新建一个springboot项目 因为我们创建的是一个web工程,所以,仅仅演示支付宝的demo,只需

  • SpringBoot集成ElaticJob定时器的实现代码

    本文介绍了SpringBoot集成ElaticJob定时器的实现代码,分享给大家,具体如下: POM文件配置 <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:sch

  • Android中使用ShareSDK集成分享功能的实例代码

    引言 现在APP开发集成分享功能已经是非常普遍的需求了.其他集成分享技术我没有使用过,今天我就来介绍下使用ShareSDK来进行分享功能开发的一些基本步骤和注意点,帮助朋友们避免一些坑.好了,下面切入正题正式开始介绍. 1.ShareSDK开发包及配置 这个不用多说,去他们官网看找SDK开发包和集成文档即可. Android版本地址:http://www.mob.com/downloadDetail/ShareSDK/android. 注意:记得要注册ShareSDK账号获取AppKey哦.这些

  • SpringBoot集成slf4j+log4j2的示例代码

    本文介绍了SpringBoot集成slf4j+log4j2的示例代码,分享给大家,具体如下: Maven依赖 <!--增加log4j2依赖↓--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-log4j2</artifactId> </dependency> <dependency&g

  • SpringBoot集成Auth0 JWT的示例代码

    目录 前言 session认证与Token认证 session认证 Token认证 JWT简介 JWT定义 JWT的类库 具体实现 JWT配置 JWT工具类 测试接口 前言 说说JWT,先说下互联网服务常见的两种用户认证方式: session认证与Token认证 session认证 传统的Session认证的大体流程可以表示为用户提供用户名和密码登录后由服务器存储一份用户登录信息并传递给浏览器保存为Cookie,并在下次请求中根据Cookie来识别用户,但这种方式缺陷明显: Session都是保

  • SpringBoot配置拦截器方式实例代码

    步骤: 1.实现WebMvcConfigurer配置类 2.实现拦截器 3 . 把拦截器添加到配置中 4.添加需要拦截的请求 5.添加需要排除的请求 package com.zp.springbootdemo.interceptor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springfr

  • springboot集成spring cache缓存示例代码

    本文介绍如何在springboot中使用默认的spring cache, 声明式缓存 Spring 定义 CacheManager 和 Cache 接口用来统一不同的缓存技术.例如 JCache. EhCache. Hazelcast. Guava. Redis 等.在使用 Spring 集成 Cache 的时候,我们需要注册实现的 CacheManager 的 Bean. Spring Boot 为我们自动配置了 JcacheCacheConfiguration. EhCacheCacheCo

  • springboot配置mysql连接的实例代码

    一:导入pmo.xm配置包 mysql库连接.druid连接池.mybatis组件 <!-- 使用MySQL数据库--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <!--druid连接池--&g

随机推荐