CHAPTER 7

image

Building Social Apps Using Yammer JavaScript SDK

Pathik Rawal

In the last chapter, you learned about the Yammer REST web service interface and learned how to use Yammer REST APIs in your business applications. In this chapter, you will learn about the Yammer SDKs released by Yammer. Yammer has released the following SDKs specifically for developers to build on the Yammer platform:

  • JavaScript SDK
  • Windows Phone 8 SDK
  • .NET SDK
  • iOS SDK
  • Ruby
  • Python

Yammer SDKs are open source code, which enables you to access Yammer APIs from various technology platforms. Yammer SDKs enable developers to include Yammer authentication and integrate Yammer data into their business applications using client-side and server-side code.

In this chapter, we’re going to use Yammer’s JavaScript SDK to integrate Yammer with HTML-based enterprise business applications.

Image Note  SDK (Software Development Kit) is a programming kit that includes platform APIs, programming tools, and help documentation that allows developers to develop applications for a specific platform.

Introduction to the JavaScript SDK

Let’s start working with Yammer’s JavaScript SDK. The Yammer JavaScript SDK allows developers to integrate Yammer into JavaScript-enabled applications using its rich set of functions for adding social plugins, making API calls, and implementing the Yammer login. The JavaScript SDK provides the following features:

  • Enables developers to authenticate users with OAuth 2.0 client-side flow
  • Enables developers to use Yammer login in line-of-business applications to authenticate users
  • Makes it easy to call into Yammer’s API to integrate business applications with Yammer
  • Makes it easy to call into Yammer’s Open Graph and leverage social graphs

JavaScript SDK includes a rich set functions that allow developers to integrate line-of-business applications with Yammer.

Before we implement the Yammer JavaScript SDK, let’s explore the setup that’s required to use the SDK for integrations and learn how to configure authentication to Yammer from a business application using Yammer’s JavaScript SDK functions.

Setup Required to Use the JavaScript SDK

Let’s first explore the very basic setup required to use Yammer JavaScript SDK so it can integrate with external applications. The Yammer SDK for JavaScript doesn’t have to be downloaded or installed. Instead you simply need to include a short piece of regular JavaScript code located on Yammer server (https://c64.assets-yammer.com/assets/platform_js_sdk.js) in your HTML. That will load the SDK on to your web pages or application interface.

The Yammer SDK reference is available at:

https://c64.assets-yammer.com/assets/platform_js_sdk.js

Image Note  At the time of writing this book, c64 is the version released by Yammer. You should refer to the Yammer developer documentation for the latest SDK versions.

The following snippet of code shows the basic version of the JavaScript SDK. You should insert it in the <head> tag on each page you want to load it.

<script type="text/javascript" data-app-id="YOUR-APP-CLIENT-ID" src="https://c64.assets-yammer.com/assets/platform_js_sdk.js"></script>

This script will load and initialize the SDK. You must replace the value in data-app-id with the ID of your own Yammer App. You can find this ID using the client https://www.yammer.com/client_applications, as explained in Chapter 3.

Another important configuration is the JavaScript origins section of your Yammer app’s configuration. An origin is the URL of your web application, SharePoint site, or SharePoint-hosted app.

You need to enter all the URLs of your line-of business-applications. In our case study, this would be the SPDS University SharePoint-hosted app. It’s URL could be https://spdsuniversity.sharepoint.com/sites/Dev or https://SPDS University-1a08e7eeb36b03.sharepoint.com/sites/Dev.

That’s all that is required from a setup point of view. In the next section, we will take a closer look at JavaScript SDK’s authentication functions. You will learn about other JavaScript SDK’s functions that allow you to call Yammer REST APIs from your line-of-business applications.

Authentication Using JavaScript SDK

The Yammer’s JavaScript SDK provides a secure way to authenticate Yammer users in external applications. Yammer’s JavaScript SDKs can be leveraged in a variety of applications, including HTML sites, web applications, Windows 8 apps, and SharePoint-hosted app on the Microsoft platform. In Chapter 4, you built a SPDS University SharePoint-hosted app for SharePoint Online using the JavaScript SDK to authenticate the Yammer users. In this section, we will extend the functionality of that app to post and retrieve data from Yammer by using the JavaScript SDK.

First, let’s explore the different authentication functions provided by the Yammer JavaScript SDK.

Authentication Functions

The Yammer JavaScript SDK includes core authentication functions to authenticate users and retrieve user data from Yammer into your line-of-business applications. The core authentication functions are the heart of the Yammer JavaScript SDK and easily can be invoked from client-side HTML code. Table 7-1 lists all the available authentication functions in the Yammer JavaScript SDK.

Table 7-1. Yammer JavaScript SDK’s Authentication Functions

Function

Table Head

yam.platform.loginButton

Provides a “Log In with Yammer” button using simple HTML markup.

yam.platform.GetLoginStatus

Returns the Yammer user’s login status and, if user is already logged in, it returns the access token.

Yam.platform.logout

This function is used to log out the logged in user.

yam.platform.login

Invokes the Yammer Login window in a popup. Ensure that you call this function inside a function(response) within getLoginStatus.

In the following section, you will learn more about each of the authentication functions listed in Table 7-1.

Function: loginButton

The simplest way to implement OAuth 2.0 authentication flow is to use the “Sign In with Yammer” button. You pass a selector parameter in the login function and second parameter is a callback function to handle the response. The HTML element such as <span id="yammer-login"></span> gets converted into a standard “Sign In with Yammer” button, as shown in Figure 7-1.

9781484209448_Fig07-01.jpg

Figure 7-1. Sign In with Yammer button

Let’s look at the syntax and parameters of the loginButton function.

Here is the syntax of the loginButton function:

yam.platform.loginButton(''#yammer-login'', [callback])

The loginButton function uses two parameters, listed in Table 7-2.

Table 7-2. loginButton Function Parameters

Name

Type

Required

#selector

HTML element name as string

Yes

[callback]

Function

Yes

The complete implementation of the loginButton function is provided in the following code snippet:

<span id="yammer-login"></span>
<script>
yam.connect.loginButton('#yammer-login',
              function (resp) {
                  if (resp.authResponse) {
                      displayAuthResult(resp);
                  }
              });
</script>

When this button is clicked by user, it initiates the OAuth authentication workflow on Yammer. When the user approves or denies the Yammer app, the callback function will execute. To determine whether the user has logged in and has approved your Yammer app, you can check the resp.authResponse property value.

If the user isn’t logged into your application or isn’t logged into Yammer, you can use the Login window to prompt them to do both. If the user isn’t logged into Yammer, he will first be prompted to log in. If he is accessing Yammer for the first time, he will be asked to grant permission to the Yammer app to access his data, as shown in Figure 7-2.

9781484209448_Fig07-02.jpg

Figure 7-2. Validation by Yammer to allow an external application to use the user’s data

Function: getLoginStatus

The JavaScript SDK function getLoginStatus can be called to determine whether the user is already logged into Yammer. The GetLoginStatus function takes two parameters—a callback function and Boolean parameter (true or false) to forceRefresh. When getLoginStatus is called for the first time, it calls the Yammer API. After a successful call, the callback function will be triggered. The server response is passed to the callback function.

Here is the syntax of the getLoginStatus function:

yam.platform.getLoginStatus(callback, [forceRefresh])

The getLoginStatus function uses two parameters, listed in Table 7-3.

Table 7-3. getLoginStatus Function Parameters

Tab3

The complete implementation of the getLoginStatus() function is provided in the following code snippet

1. <script>
2. yam.connect.getLoginStatus(
3. function(response)
4. {
5.  if(response.authResponse){
6.    alert("Already Logged in");
7.    callback();
8.   }
9.  else
10. {
11. alert("Not Logged in");
12. yam.platform.login(function(response)
13. {
14. // Hanlde Resposne here
15.      };
16. });
17.  </script>

Image Note  You do not need to store the access token, as subsequent calls to yam.platform.request() will automatically use the token returned by this call.

Let’s explore this code snippet line by line:

  • Line 2: The method yam.connect.getLoginStatus() gets the login status of the user.
  • Line 3: This line has the callback function that gets called in response to the getLoginStatus() method.
  • Line 5: The if block checks the Boolean field response.authResponse to determine if it is true or not.
  • Lines 6 and 7: If response.authResponse is true then the if block is called and it calls the alert message to display the “Logged in” string. The developer can then write the code to call the REST APIs from line 5 on behalf of the logged in user. For demonstration purposed, a callback() function is called that can make further calls to the other Yammer APIs.
  • Line 9: If respone.authResponse=false then the else block is called.
  • Line 12: Within the else block, the line yam.platform.login() opens a window for the user to log in to Yammer.

Function: login

The yam.platform.login() function is an alternative way to trigger the Yammer login pop-up. This is different from the “Sign In with Yammer” button, which we explained earlier.

Here’s the syntax of the login function:

yam.platform.login([opts], [callback])

The login function uses two parameters, listed in Table 7-4.

Table 7-4. The login Function’s Parameters

Function

Description

[opts]

Object

[callback]

Function

Yam.platform.login() can be used with a GetLoginStatus() method, as shown in the following example:

yam.getLoginStatus(
  function(response) {
    if (response.authResponse) {
      console.log("logged in");
      console.dir(response); //print user information to the console
    }
    else {
      yam.platform.login(function (response) { //prompt user to login and authorize your app, as necessary
        if (response.authResponse) {
          console.dir(response); //print user information to the console
        }
      });
    }
  }
);

You should call the yam.platform.login() method inside a function(response) within getLoginStatus(), as shown in this example. The yam.platform.login() function prompts the user to log in using the Yammer Login screen and then the authorization screen appears so you can authorize your app. Once users take action, the pop-up is closed and the callback function is triggered.

Function: logout

The logout() function enables users to log out from Yammer directly from their business applications. You can check the login status of the user before calling this function, which will ensure that all components required for logout function are loaded.

The syntax of the logout function is as follows:

yam.platform.logout([callback])

The logout function uses one parameter, explained in Table 7-5.

Table 7-5. The logout Function Parameters

Tab5

Implementation of the logout function is very simple, as illustrated in the following code snippet:

yam.platform.logout(function (response) {
            // write your code here
})

So, now you have learned the various authentication functions provided by the Yammer JavaScript SDK to implement the authentication using OAuth 2.0 flow in your line-of-business applications. Next, you will learn about calling Yammer REST APIs using JavaScript SDKs.

Using the JavaScript SDK to Call Other REST APIs

Once you implement the authentication using OAuth 2.0 flow, you need to call the Yammer REST APIs to write or read data from Yammer in your business applications. Let’s explore the functions provided by the JavaScript SDK to make REST APIs calls.

Additional Functions

The Yammer JavaScript SDK includes functions that allow developers to retrieve data from Yammer into their line-of-business applications. Table 7-6 lists the function in Yammer JavaScript SDK.

Table 7-6. Yammer JavaScript SDK’s Additional Function

Function

Table Head

yam.platform.request

This function can be used to call all other Yammer REST APIs.

In the following section, you will learn about the yam.platform.request function in more detail.

Function: request

The Yammer JavaScript SDK also provides a function that can be used to call other REST APIs. This function can be used to read or write data to Yammer. For example, to post a message to a Yammer group or to post a private message on behalf of a user, you use the JavaScript SDK’s yam.platform.request() method to call all the REST APIs.

Here’s the syntax of the yam.platform.request function:

yam.platform.request(options)

The yam.platform.request() takes one parameter—Option—which contains four sub-parameters, as listed in Table 7-7.

Table 7-7. yam.platform.request Function Parameters

Tab7

The yam.platform.request() makes Yammer API calls with a bearer token for the current users. The bearer token is set using the yam.platform.setAuthToken() method.

The complete implementation of the yam.platform.request function is provided in the following code snippet:

yam. platform.request({
                url: "messages.json",
                method: "GET",
                success: function (msg) {
console.dir ("Get was Successful!: " + msg);
},
                        error: function (msg)
{
 console.dir(msg);
}
})

You can make calls to the REST API without the hostname, as shown in the previous example. The previous example uses url:message.json instead of a complete hostname like https://api.yammer.com/api/v1/ messages.json. When calling REST APIs through the JavaScript SDK, you will need to use the api.yammer.com as documented on https://developer.yammer.com/yammer-sdks/.

In Exercise 7-1, you will learn to integrate SharePoint-hosted apps with Yammer using JavaScript SDK. Exercise 7-1 is an extension of Exercise 4-2. In Exercise 4-2, you learned how to implement OAuth 2.0 authentication, which uses JavaScript SDK’s authentication function discussed in this chapter. So before you start Exercise 7-1, go back and work through Exercise 4-2 if you have not already done so.

Implementing Yammer Integration in a SharePoint-Hosted App Using JavaScript SDK

In Exercise 7-1, you will implement Yammer integration in a SharePoint-hosted app using JavaScript SDK. You need Visual Studio 2012 Professional or higher and Office Developer Tools for Visual Studio 2012. These can be downloaded from http://msdn.microsoft.com/en-us/office/apps/fp123627.

EXERCISE 7-1: MESSAGES MANAGEMENT: POST A MESSAGE TO A YAMMER GROUP

In this exercise, we will extend the functionality of the SharePoint-hosted app we built in Exercise 4-2 by adding more social features to it in order to post messages and so on.

  1. Open the Visual Studio Solution SPDS University SharePoint hosted-app for SharePoint Online that we developed in Exercise 4-2.
  2. Add the following code to the ContentPlaceHolderId="PlaceHolderMain" for an input text box (to type the message to be posted) and button (to call the post message function) markup in CustomActionTarget.aspx.
    <div style="position: absolute; top: 510px; left: 20px; width: 300px; height:80px; background-color: azure; border:dotted; border-width:medium">
            <br />
              <input type="text" id="txtmessage" value="hi" style="width:250px; height:20px;"  />
            <br />
              <input type="button" onclick="postAMessage()" value="Post Message to Yammer" />
    </div>
  3. Add a function called postAMessage() to the section ContentPlaceHolderId="PlaceHolderAdditionalPageHead" in the CustomActionTarget.aspx file.
    function postAMessage() {
              var ItemURL = "https://SPDSpetro.sharepoint.com/";
              var group_id = 4966305;
              var message = document.getElementById('txtmessage').value
              postMessagetoYammer(ItemURL, message, group_id);
    }

    This function calls the PostMessagetoYammer function, defined in the YammerCore.js, by passing the ItemURL, the message, and the group_id.

    The group_id is hard-coded in this example; however, you can use the message retrieval REST API to get the group_Id to post a message to group.

  4. Add a new JavaScript file by right-clicking on the project and choosing Add image New Item image Web image JavaScript File, as illustrated in Figure 7-3. Enter YammerCore.js into the Name box.

    9781484209448_Fig07-03.jpg

    Figure 7-3. Add a new JavaScript file and name it YammerCore.js

  5. Open YammerCore.js and add the following code:
    function postMessagetoYammer(ItemURL, message, group_id) {
        var testMessage = { "body": "Hello Test, have you seen this" + ItemURL };
        yam.platform.request({
            url: "https://api.yammer.com/api/v1/messages.json",
            method: "POST",
           data: {
               "body": testMessage,
               "group_id": group_id
            } ,
            success: function (msg) {
                console.log("Message Posted Successfully");
            },
            error: function (msg) {
                console.log("Message Posting Error: " + msg.statusText);

            }
        });
    }

    Image Note  As you are using Yammer SDK, you do not need to set the header for the bearer token. The Yammer SDK does it for your and generates the request header with the authentication bearer retrieved by using the OAuth flow.

  6. Add the JavaScript reference to YammerCore.js in the section called ContentPlaceHolderId="PlaceHolderAdditionalPageHead" in the CustomActionTarget.aspx file.
    <script src="../Scripts/yammercore.js"></script>

Messages Management: Like a Message

Image Note  Yammer JavaScript SDK provides the following REST API to mark a message as liked by the current user. https://www.yammer.com/api/v1/messages/liked_by/current.json?message_id=[:id]

Where the ID represents the target message ID and request requires a POST method.

  1. In CustomActionTarget.aspx, add a button’s markup “Like a Message” button in ContentPlaceHolderId="PlaceHolderMain".
    <div style="position: absolute; top: 610px; left: 20px; width: 300px; height:100px; background-color: azure; border:dotted; border-width:medium">
            Like A Message
            <br />
            Message Id <input type="text" id="txtmessageid" value="507867284" style="width: 250px; height: 20px;" />
            <br />

            <input type="button" onclick="likeMessage()" value="Like a Message on Yammer" />
            <br />
    </div>
  2. Add a function called likeMessage() to the script tag, which will be triggered on the “Like a Message on Yammer” button. This function then calls another function called likeaMessage(), which is defined in the YammerCore.js file.
    function likeMessage() {
              var messageid = document.getElementById('txtmessageid').value;
              likeaMessage(messageid);
    }

    Image Note  The likemessage function gets the message ID from the textbox and calls likeaMessage, defined in YammerCore.js, by passing the message ID.

  3. Open YammerCore.js and add the following code to define a new function called likeaMessage(messageid).
    function likeaMessage(messageid) {

        var endpoint = "https://www.yammer.com/api/v1/messages/liked_by/current.json?message_id=[:id]".replace('[:id]', messageid)
         yam.platform.request({
            url: endpoint,
            data:'',
            method: "POST",
            success: function (msg) {
                console.log("Message liked Successfully");
            },
            error: function (msg) {
                console.log("Message Posting Error: " + msg.statusText);

            }
        });
    }

This code snippet first forms the endpoint for invoking the “like a message” API. The endpoint is https://www.yammer.com/api/v1/messages/liked_by/current.json?message_id=[:id], first replace the [:id] with the message ID of the message you would like to mark as liked. In this example, message_id is passed from customActionTarget.aspx using an input text box. The next code is the standard yam.platform.request call done by passing the URL (the endpoint we form in the first line of the function, data as empty string, method:POST, and callback functions to handle the success and failure scenarios.

Messages Management: Unlike a Liked Message

The Yammer JavaScript SDK provides following REST API, which is the same one we saw in the previous section, “Like a Message”.

https://www.yammer.com/api/v1/messages/liked_by/current.json?message_id=[:id]

Where the ID represents the target message ID and request requires a DELETE method.

  1. Add the following code to add a button to the CustomActionTarget.aspx file.
    <div style="position: absolute; top: 810px; left: 20px; width: 300px; height:80px; background-color: azure; border:dotted; border-width:medium">
            <input type="button" onclick="UnlikeMessage()" value="Unlike a Message on Yammer" />
            <br />
    </div>
  2. Add a function called likeMessage() to the script tag, which will be triggered on the “Like a Message on Yammer” button. This function then calls another function, called likeaMessage(), which is defined in the YammerCore.js file.
    function UnlikeMessage() {
              var messageid = document.getElementById('txtmessageid').value;
              UnlikeaMessage(messageid);
    }
  3. Add the following code to define a function called UnlikeaMessage in the YammerCore.js file.
    function UnlikeaMessage(messageid) {
        var endpoint = "https://www.yammer.com/api/v1/messages/liked_by/current.json?message_id=[:id]".replace('[:id]', messageid)
         yam.platform.request({
            url: endpoint,
            data:'',
            method: "DELETE",
            success: function (msg) {
                console.log("Message was unliked Successfully");
            },
            error: function (msg) {
                console.log("Message Posting Error: " + msg.statusText);

            }
        });
    }

This code snippet first forms the endpoint for invoking the “unlike a message” API. The endpoint is https://www.yammer.com/api/v1/messages/liked_by/current.json?message_id=[:id], so we need to replace the [:id] with the message ID of the message you would like to mark as unliked. In this example, the message_id is passed from customActionTarget.aspx using an input textbox. The next code is the standard yam.platform.request call created by passing the URL (the endpoint we form in the first line of the function, data as empty string, method :DELETE and call back functions to handle the success and failure scenarios.

Run the SharePoint-Hosted App

You have added all the necessary code for the SharePoint-hosted app, so you can now run the application and see the integration of the app with Yammer using JavaScript SDK in action.

  1. In Solution Explorer, open the shortcut menu for the app in the SharePoint project, and then choose Deploy, as illustrated in Figure 7-4.

    9781484209448_Fig07-04.jpg

    Figure 7-4. Deploy the SharePoint-hosted app using Visual Studio

  2. Once the app is deployed, navigate to https://spdsuniversity.sharepoint.com/sites/dev/_layouts/15/start.aspx#/SitePages/DevHome.aspx using your browser, as illustrated in Figure 7-5. Click on SPDS UniversityApp, as highlighted.

    9781484209448_Fig07-05.jpg

    Figure 7-5. Deployed SharePoint-hosted app on the SharePoint Online Dev site

  3. You will be presented with the app’s default page, called CustomActionTarget.aspx, as illustrated in Figure 7-6.

    9781484209448_Fig07-06.jpg

    Figure 7-6. SharePoint-hosted app’s default page, CustomActionTarget.aspx

  4. Enter the URL of the SharePoint-hosted app, as shown in Figure 7-7. This should be the URL of the SharePoint web where your SharePoint-hosted app is deployed.

    9781484209448_Fig07-07.jpg

    Figure 7-7. Yammer app’s JavaScript Origins section

  5. The first thing you need to do is log in using the “Log In with Yammer” button. Once you click on that button, you will be presented with Yammer’s Login window, as shown in Figure 7-8. Enter your Yammer credentials and click on the Login button.

    9781484209448_Fig07-08.jpg

    Figure 7-8. Yammer’s login window, which is initiated by clicking on the “Log In with Yammer” button

  6. After a successful login, you will be taken back to the CustomActionTarget.aspx page, where the displayAuthResult() function will display the access token for the logged-in user, which we already saw in Chapter 4. As illustrated in Figure 7-9, the page also has three div sections that display buttons and textboxes for posting a message, liking a message, and unliking a message.

9781484209448_Fig07-09.jpg

Figure 7-9. After successful login, the page displays the markup to test other features of the JavaScript SDK

So, in this exercise, we extended the SPDS University SharePoint-hosted app to integrate Yammer functionalities by using the Yammer JavaScript SDK.

In a similar manner, you can use the Yammer JavaScript SDK in your business application to provide authentication using Yammer and then read and write data to Yammer.

Summary

By now you are familiar with the Yammer SDKs released by Yammer. First, you learned about the Yammer JavaScript SDK, the authentication functions, and the other functions available in the SDK. You also learned to integrate a JavaScript-enabled application with Yammer. In the next chapter, you will learn how to integrate a Windows phone app with Yammer using the Windows Phone SDK.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset