How to exploit Facebook data to refine contact profiling

A common will among companies is to exploit relevant data coming from third-party systems such as social networks in order to improve the profiling of contacts in THRON. This aspect is crucial to achieve the main objective of the Content Strategy, since a better profiling of contacts helps to understand what are the best content for the various types of people accessing your channels; moreover it will allow you to refine your recommendations, improving User Retention.

In this tutorial we will learn how to retrieve from  Facebook some of the information which can be useful to enrich THRON intelligence by adding tags related to users accessing content.

This activity can be segmented into steps. Some of these steps, even if preparatory, are not strictly related to this tutorial. Feel free to skip them if you already know the presented argument. Different steps are:

  1. How to retrieve data from Facebook
  2. How to identify user with the tracking library
  3. How to use jquery in order to send collected information to the server
  4. How to authorize server-side implementation in order to perform requests
  5. How to create THRON tags which will map information coming from Facebook
  6. How to profile contacts with such information

 

So if you are already familiar with some of these steps, you can skip directly to the next one, in particular to step 6, which is the main focus of this tutorial. In the end, when an user will use Facebook connect button, we will try to retrieve gender, fullname, email and age range from his Facebook profile (if he gives consent) and add such data as tags to enrich his THRON profile, as depicted in the diagram below. 

 

Facebook can provide to THRON useful "targeting" profile data, while THRON Behavior Engine , will analyze content usage to understand user interests. Behavior engine will also leverage Facebook obtained data to enrich content target information and unlock powerful data-driven analysis for communication targeting.

This tutorial shows code snippets only to improve readability, you can download full sample code from the appropriate links.

This code is for demonstration purpose, it's strongly recommended to adapt it to your specific case before using it in production environments.

 

Step 1: Facebook Application

In the first step we will configure Facebook to allow access to desired information about connected user.

To do this, we need to create a Facebook application linked to a login button. Through this login button, Facebook will ask user to grant the permission to retrieve such information. In this tutorial, we will create a Facebook login button that will ask for email and public profile that normally provide name, gender and age range (exact birthday needs a special approval process).

In this article https://developers.facebook.com/docs/facebook-login/web you will get all the HTML that is needed in order to obtain the button and all the useful callbacks to handle users' login, logout and so on. We will need to make some little adjustments, but for now simply paste provided code in your webpage.

Next thing to do is to create a Facebook application. Starting from https://developers.facebook.com/apps you will be able to create a WEB app and update some settings:

  • You need to set the app domain (which must be the url of the page hosting the Facebook login button).
  • You need to set a reference email in order to make the application available to the public.

Make sure to copy the app ID which will be given to you once the application has been created.

Now go back to the html page and find " FB.init calls". Paste your Facebook app id there. 

You will also need to change the information requested by the application by updating the “scope" of the <fb:login-button> code snippet.

For our use case, we need to set this scope:

<fb:login-button data-size="xlarge" scope="public_profile,email" onlogin="checkLoginState();"></fb:login-button>

Now, if you open your page and click on the login button, Facebook will ask for your authorization in order to retrieve that set of information. Authorizing the login process, the information will pass through the callback until userConnected() will confirm that user has connected to Facebook; at this point you can use a Facebook API to retrieve for those information. The code snippet is:

FB.api('/me?fields=gender,age_range,name,email', function(response) { } );

and the response contains: gender, age range, name and email of the connected user, if provided.

 

Step 2: Contact identification

The current step will show how to send contact detail data to THRON through the Tracking Library.

Once included in the <head> of your page, you will have to use the loginAs method in order to add new identities to your contacts (Facebook Id and Email). Those identities can be used in THRON's Single Customer View to identify contacts' behavior. The loginAs method will return a javascript promise which we are going to use to send the information to our application ( Promise.all code) when async requests are performed via storeFacebookInformation. Another promise is returned by getContactInformation, another method of the tracking library used to identify the user visiting the page.

Take a look at this simplified code snippet to get examples of how to pratically use the previous described information.

function userConnected() {
     //requesting information from facebook
     FB.api('/me?fields=gender,age_range,name,email', function(response) {

         //a loginAs example
         var storeFacebookId = clientIdtracker.loginAs('facebook-id', facebookId, fullName).then(function() {
             console.log("facebook id acquired.");
         });

         //a getContactInformation example
         var obtainContactId = _ta.getContactInformation('YOUR CLIENTID HERE').then(
             function(ci) {
                 console.log("your contact id is " + ci.contactId);
                 //storing
                 contactId = ci.contactId;
             }
         );

         //when i have both contact id and login as has finished, i store facebook information and i go on
         Promise.all([obtainContactId, storeFacebookEmail, storeFacebookId]).then(function(values) {
             console.log("Login completed and contact id obtained, storing information");
             storeFacebookInformation(response, contactId);
         });
     });
 }

 

Step 3: sending information to server side implementation

Now that Facebook information have been gathered and the contact has been identified, we need to send all the data to our application. The operation is quite easy, we just need to use the jquery POST implementation as you can see here. In this case the html page hosting the login button is in the same folder as the facebookDataParser.php, which is our server side implementation of the integration.

var clientIdtracker = _ta.initTracker("YOUR CLIENTID HERE");
var storeFacebookInformation = function(information, contactId) {
    console.log("storing");
    var data = {
        "contactId": contactId,
        "information": information
    };

    $.ajax({
        type: "POST",
        url: "facebookDataParser.php",
        data: data,
        success: function(response) {
            //everything is ok ! maybe now you want to go somewhere...
        }
    });
}


Step 4: THRON CUSTOM APPLICATION MANAGER

During step 2 we used the loginAs method in order to add a new identity to the connected user client-side, since this method does not need authentication. In the next steps we are going to use some web services that require a tokenId in order to be invoked, so we need to create a THRON Custom Application Manager. Such application permits to authenticate in order to obtain a token which must be used to perform requests.

 

Step 5: THRON tags creation and mapping

Next thing to do is to create some tags representing the information collected via Facebook. You can consider Facebook information as raw data that can be processed to understand if some of your tags can be applied to the user visiting the page. Tags can be created both via Dashboard and via web services, following the instructions provided in this article. Let's supposed we create the following tag trees within our TARGET classification:

  • gender
    • male
    • female
  • age range
    • 13-17
    • 18-21
    • over 21

You will have to use tags ids when invoking web services in order to tag contacts visiting your page, so make sure you set some easy tag ids too.

 

Step 6: Contact profiling

For our server-side implementation we are going to use a bit of php language since it is widely used.  As stated before, the first thing to do is to retrieve a valid token to be used in order to perform web services requests, so the first service we are going to invoke is the loginApp . In this article you will find a detailed explanation on how to move the first steps into THRON API, and more specifically on how to perform authentication using a specific application, which is the case hereby considered; we recommend you read the article for an in-depth understanding of the operations.

Once the token has been retrieved you will be able to use it to perform an insert request in order to link tags to your contacts.

First of all, as we said, we need a token to call webservices, so let’s start with the App Login. App Login can be used as example to call the other required web services.

//Given app information, it returns a tokenId
    function getTokenId($clientId, $appId, $appKey) {
        $url = "https://".$clientId.
        "-view.thron.com/api/xadmin/resources/apps/loginApp/".$clientId;
        $request = "appId=".$appId.
        "&appKey=".$appKey;

        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_HEADER, true);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $request);

        $curlRes = curl_exec($curl);
        $curlResInfo = curl_getinfo($curl);
        curl_close($curl);

        $resHeadersString = substr($curlRes, 0, $curlResInfo['header_size']);
        $resBody = substr($curlRes, $curlResInfo['header_size']);

        $response = json_decode($resBody);

        if (gettype($response -> appUserTokenId) == "NULL") {
            writeLog("Unauthorized!");
            header('HTTP/1.0 401 Unauthorized');
            echo 'Unauthorized';
            exit;
        } else {
            return $response -> appUserTokenId;
        }
    }

Given clientId, appId and appKey, https://developer.thron.com/#!/apps/loginApp will return the token.

So, with the token, you can use this web service https://developer.thron.com/#!/itag/insert to add tags to the contact.

In step 2 you saw how to identify a contact thanks to Tracking Library, which provides you a contactId; in step 5 you have created the tags. Now we need to use those information to assign the proper tags to your contacts according to your taxonomy by making some logic.

Take a look at this sample code. We receive information by Post Data, we choose the right tag and we call the function that assigns this tag to the contact.

//facebook will give us 13+ ,18+ or 21+
    if (gettype($data['age_range']) != "NULL") {
        $age = $data['age_range']['min'];
        switch ($age) {
            case 13:
                tagContact($clientId, $tokenId, $contactId, $classId, $facebook13);
                break;
            case 18:
                tagContact($clientId, $tokenId, $contactId, $classId, $facebook18);
                break;
            case 21:
                tagContact($clientId, $tokenId, $contactId, $classId, $facebook21);
                break;
        }

    }

In the attached code you will also find writeLog function, which can be useful in order to store a log file. If you have any question feel free to write any comment or to contact us on any channel. Happy integration.

 

Was this article helpful?
1 out of 1 found this helpful

Have any question?

Open a ticket
Comments