Accessing MS Teams (Teams) from inside SPFX Webpart

Download Code Here: TeamsInSP.zip

SharePoint Framework:    SPFx is a Framework solution that helps you build custom apps for your SharePoint Modern sites and lets you integrate them on classic sites as well.

Why SharePoint Framework?

  • The controls are responsive and accessible by nature.
  • User can use any JavaScript framework that you like: React, Handlebars, Knockout, Angular, and more.
  • User can use client development tools such as npm, TypeScript, Yeoman, webpack, and gulp.

Now that we have a knowledge of SharePoint framework, let us see what MS Teams is.

Microsoft Teams:

Teams is a communication tool which helps members of an organization to communicate effectively with conversational tabs, easily schedule meetings, record calls and upload them on Microsoft Streams for later access.

Pre-requisites:

  • Visual studio code installed.
  • Node version 8.11.3
  • Gulp and yeoman installed globally.

Getting started:

From inside the command prompt, Create your project folder and switch to it.

Then type below command in your command terminal

“yo @microsoft/sharepoint”,

This will prompt you with questions like,

  • What is your solution name? TeamsInSP (you can name as per your choice)
  • Which baseline packages do you want to target for your component(s)? SharePoint Online
  • Where do you want to place the files? Use the Current Folder
  • Do you want to allow the tenant admin the choice of being able to deploy the solution to all sites immediately without running any feature deployment or adding apps in sites? Yes
  • Will the components in the solution require permissions to access web APIs that are unique and not shared with other components in the tenant? Yes
  • Which type of client-side component to create? WebPart
  • What is your Web part name? TeamsInSP
  • What is your Web part description? TeamsInSP description
  • Which framework would you like to use? React

Wait some time while yeoman creates your project structure and gives you a confirmation message.

Run “gulp serve” and check if your localhost pops up.

Now navigate to “https://yourTenant.sharepoint.com/layouts/15/workbench.aspx” ,search the name of your webpart and add it.


After you’ve added your webpart successfully, you would see a welcome screen in it. Now you are good to code further 😊


For connecting MS Teams from SharePoint, we can use Microsoft Graph API.

 Microsoft Graph API: With Microsoft Graph API you can access data of users present in Microsoft cloud.

End point URL: https://graph.microsoft.com

We have used pnp/graph to call the graph rest services.

Before proceeding with the code, let us check if the rest services work properly.

For this, go to “https://developer.microsoft.com/en-us/graph/graph-explorer

Make sure to sign in with your office 365 account.

Run a sample Query to fetch all the MS teams that you are connected to by typing

https://graph.microsoft.com/v1.0/users./joinedTeams

It will list all MS Teams of yours.

Troubleshooting the errors in the response:

If you happen to receive a 403-status code in the response don’t panic, click on the “modify permissions”,

Enable the following permissions and click approve.

  • User.Read.All
  • User.ReadWrite.All
  • Group.Read.All
  • Group.ReadWrite.All

Run the query again and you’ll be able to see a successful response.

Now that our API is working fine, Let us integrate with our SPFx Webpart.

To use Graph API services inside SPFx, run

“npm install @pnp/graph –save”

Move to your <solutionName>WebPart.ts file and Import the library into your application, update OnInit function, and access the root SP object in render

import { graph } from "@pnp/graph";

export interface ITeamsInSpWebPartProps {
  description: string;
  context:any;
}

export default class TeamsInSpWebPart extends BaseClientSideWebPart<ITeamsInSpWebPartProps> {


  public onInit(): Promise<void> {
    return super.onInit().then(_ => {
    graph.setup({
      spfxContext: this.context
    });
    });
  }

Now modify the render method to get all the teams and add another Batching function to loop through each teams properties and get its webUrl for redirection.

  public async render(): Promise<void> {
    let array = [];
    const myJoinedTeams = await graph.me.joinedTeams.get();
    this.domElement.innerHTML = `Loading...`;
    myJoinedTeams.map((res) => {
      array.push(this.Batching(res.id));
    });
    Promise.all(array).then((res)=>{
            this.domElement.innerHTML = `Groups: <ul>${
              res.map(g =>
          `<li><a href='${g.webUrl}'>${g.displayName}</a></li>`
        )
        .join("")
      }</ul>`;
    })
  }
  private async Batching(ID) {
    const team = await graph.teams.getById(`${ID}`).get();
    return team;
  }

If you switch to your workbench.aspx you can see list of your teams being rendered on the DOM which on clicking takes you to that particular Team.

Wow 😊 we have got our MS Teams inside SPFX, we’ll customize it to look more pleasing for the end user.

Add a little bit of CSS Touch to do the magic,

Deployment:

So far, we have our application running locally from “https://<tenant>.sharepoint.com/_layouts/15/workbench.aspx”. To move it to production,

  • Go to your package-solution.json file inside config folder and insert the following piece of code,
    "webApiPermissionRequests": [
      {
        "resource": "Microsoft Graph",
        "scope": "User.Read.All"

      },
      {
        "resource": "Microsoft Graph",
        "scope":"User.ReadWrite.All"
      },
      {
        "resource": "Microsoft Graph",
        "scope": "Group.Read.All"

      },
      {
        "resource": "Microsoft Graph",
        "scope":"Group.ReadWrite.All"
      }
    ]
  },

These are the permissions to be enabled organization wide for our application to work.

  • Do a “gulp bundle –ship
  • And finally run “gulp package-solution –ship”

You can upload  the .sppkg file inside sharepoint/solution folder to your app catalog.

Before adding this webpart to any site, switch to

“https://<Tenant>-admin.sharepoint.com/_layouts/15/online/AdminHome.aspx#/home” and click “API Management”

You can see the Permissions that is required for our application in the being listed under “Pending Approvals”

Approve them and just add the webpart to any of your modern sites and Play with it 😊.

What the Complete solution Looks like:

On clicking the cards, we get redirected to that particular team,

Congrats we have successfully integrated our SPFx webpart with Teams.

You can refer https://pnp.github.io/pnpjs/graph/docs/teams/ for specific API service according to your requirements.


Vidhya Vaidhiyanathan

Add a Comment

Your email address will not be published. Required fields are marked *