Using external services in your webpage

Some of you might know; I play in a soccer team located in Balkbrug, just for fun and also maintain their website. The club I play for, SC Balkbrug, has a facebook page, twitter and a website to reach several groups of people. All these pages takes a lot of time to maintain. For example, if there is a news item, we have to put it on facebook and the website which is manually 2 actions. It is also difficult to find volunteers who want to update every page with news items and competition information. Wouldn’t it be easier to update one resource and the other resource gets updated automatically? In this blog, I am going to show how to setup and make use of data from external resources facebook and voetbalnoord.

The first resource is Facebook. We want to get the most recent posts from our facebook page. Facebook has an API for this called the ‘Graph Api’ available at https://developers.facebook.com. You can find documentation per programming language and some tooling. Login with your facebook credentials.

In my case, I am moderator of my own profile and the SC Balkbrug Facebook page. I can give grants to anybody for several actions like creating posts, remove comments etc. This is mandatory when you want to grand facebook data to external resources. The first thing you need to do is to create an ‘app’. This app contains a set of credentials, but also a lot of options and tracks statistics (e.g. how much users accessed your app). In my case I created an app called ‘SC Balkbrug Website’. See the screenshot below.

facebook-app

After creating the app via developers.facebook.com we need to create some code to obtain the data.

The code should obtain an acces token and use this acces token to get the data from facebook. To obtain an acces token, Facebook has 2 options:
– Using an external service (e.g. your own set of credentials, facebook credentails etc, also known as federated identity)
– Using the app id and app secret directly to obtain an acces token.
For my use case I use option 2. All the resources that I want to use is public data, so I do not need to authenticate if users are allowed to acces several pages. Note; Only use option 2 in a serverside environment and not in a clientside environment (e.g. javascript). Don’t publish your app-id and app-secret or use it in clientside code.

For option 2, Facebook has a http GET service with the following url: https://graph.facebook.com/oauth/accestoken?client_id=[appId]&client_secret=[appSecret]&grant_type=client_credentials. This service returns an acces token.

Using the acces token we can obtain the recent posts from our page using a http GET service with the following url: https://graph.facebook.com/[your page]/posts?fields=id,message,full_picture,created_time&accestoken=[your acces token]

The url is constructed as follows; First you define what kind of information you want. In my example, I want to get the posts, so the url looks like graph.facebook.com/[your page]/posts. Other options are feeds, photo’s, likes etc. Then you define which fields you want from the information. In my case, i am interested in the id, message, a picture (optional) and the created (date and time).

My strategy is to create wrapper/facade services around the original services for 2 reasons.  First reason is to keep authentication settings per service server side instead of client side. Second reason is to keep in control when a service change. When an external service changes (input, output, host etc), I only need to change the wrapper/facade service instead of all the code that calls the external service. In my case I use PHP, because our host only supports PHP.  I used a library called Requests to perform http requests in PHP (see http://requests.ryanmccue.info/ for more information about the library itself)

Below my wrapper service for Facebook:

<?php
include('libs/Requests.php');

// Global variables
$appId = "[here your app id]";
$appSecret = "[here your app secret]";
$page = "ScBalkbrug";

// Load request libs
Requests::register_autoloader();

// Get acces token
$tokenResponse = Requests::get("https://graph.facebook.com/oauth/access_token?client_id=".$appId."&client_secret=".$appSecret."&grant_type=client_credentials");

// Get data using acces token
$jsonResponse = Requests::get("https://graph.facebook.com/".$page."/posts?fields=id,message,full_picture,created_time&".$tokenResponse->body);

// Return result directly
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

echo($jsonResponse->body);
?>

 

We also have another resource called voetbalnoord. This web page contains information about the competition of our club. Instead of maintaining this manually on our webpage, it would be also easier to get the information from their services. They have some REST services, programmed in .NET, to get this information. I also created a wrapper service around their external service. See the code below:

<?php
include('libs/Requests.php');

// Load request libs
Requests::register_autoloader();

// Get data from voetbalnoord.nl using a POST request
$jsonArray = array('k' => '201603551');
$response = Requests::post("http://www.voetbalnoord.nl/SVC_Ranglijst.asmx/ranglijst_klasse",  array('Content-Type' => 'application/json'), json_encode($jsonArray));
               
// Create headers to tell we return JSON
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

// Create my own JSON result
$resultString = substr($response->body, 6);

echo("{ \"results\": [ ");
if($resultString != '') {
  
  $rows = explode("#", $resultString);
  $noRows = count($rows);
  for ($i = 0; $i < $noRows; ++$i) {

    //Per row...
    $columns = explode("@", $rows[$i]);
    
    // Ignore empty lines
    if(count($columns) < 10) {
      continue;
    }
    
    echo("{ ");
    echo("\"teamnaam\": ");
    echo("\"");
    echo($columns[2]);
    echo("\"");
    echo(", ");
    
    echo("\"gespeeld\": ");
    echo("\"");
    echo($columns[4]);
    echo("\"");
    echo(", ");
    
    echo("\"punten\": ");
    echo("\"");
    echo($columns[8]);
    echo("\"");
    echo(", ");
    
    echo("\"voor\": ");
    echo("\"");
    echo($columns[9]);
    echo("\"");
    echo(", ");

    echo("\"tegen\": ");
    echo("\"");
    echo($columns[10]);
    echo("\"");
    echo(" }");
    
    if($i + 1 < $noRows) {
      echo(", ");
    }
  }
}
echo(" ]}");
?>

The difference between the Facebook service wrapper and the voetbalnoord service wrapper is that I return an own JSON format, because they return more data than I need. Their JSON format also contains a lot of string concatinations which is not very handy for clientside code.

Now I created 2 php services, but I also need to embed this in my webpage. There are several ways to do this. You can use any environment for this (e.g. PHP, Javascript, Java, .Net). The code below shows an example how to use these services in javascript:

var xhttpposts = new XMLHttpRequest();
xhttpposts.onreadystatechange = function() {
  if (xhttpposts.readyState == 4 && xhttpposts.status == 200) {
    var result = JSON.parse(xhttpposts.responseText);
    // Do your thing here with the result
  }
};
xhttpposts.open("GET", "http://yourhost.com/myservice.php", true);
xhttpposts.send();

In this blog, I showed  how to fetch data from external services (facebook and voetbalnoord) using wrapper services and how to use them in your own wepage. Personally, I am convinced that this piece of code give me more spare time! 🙂