We’ve migrated our documentation to a new site, which means some URLs have changed.
Audience

Audience Integrations: Twitter

The Twitter integration allows linking Twitter user IDs with Piano user IDs to use them for audience segmentation, reporting, and targeting. Also, you can use the Twitter API to get extra information about a user (timezone, location, language, last tweet, number of followers etc; read more in Twitter's documentation.


User linking

 With a Piano user ID a Twitter user ID, all you need to link them is issue a Piano API call to map the two IDs.

  1. For you to get the current user's Twitter ID, the user should log in to your site with such an ID (see how to add Twitter Sign-In to your site).

  2. Add the normal Piano Insight script to all pages on your site. It will ensure that the Piano user ID is added as a cookie in all the HTTP requests your web server receives.
    In the Twitter OAuth callback URL handler on your server, add the code to read 1) the Identity Management from the cookie and 2) the Twitter ID from the authentication result (see the example below). To link the IDs use the Piano API /profile/user/external/link/update

// In the Twitter Oauth callback URL handler, map the user IDs:
app.get('/auth/twitter/callback',
    passport.authenticate('twitter', { failureRedirect: '/login.html' }),
    function(req, res) {
  
        // Successful authentication, link the user IDs and then redirect home.
        var cxenseId = req.cookies['cX_P'];
        var twitterId = req.user.id;
        console.log('Mapping user cxense ID: ' + cxenseId + ' and twitter ID: ' + twitterId);
  
        // The actual linking of IDs:
        cxApiRequest('/profile/user/external/link/update', { type: prefix, id: twitterId, cxid: cxenseId },
            function (error, response, body) {
                if (!error && response.statusCode === 200) {
                    console.log('Link update success!');
                } else {
                    console.log('Map error: ' + (error || response.statusCode))
                }
        });
  
        res.redirect('/');
    });

 Below is an example of full server-side code adding a Twitter login and linking Twitter user IDs to Piano user IDs.

var crypto = require('crypto'),
    http = require('http'),
    express = require('express'),
    expressSession = require('express-session'),
    bodyParser = require('body-parser'),
    cookieParser = require('cookie-parser'),
    methodOverride = require('method-override'),
    passport = require('passport'),
    TwitterStrategy = require('passport-twitter'),
    request = require('request');
 
 
// The Piano API request setup
var username = 'your@email.com';// TODO: Add your Piano username here
var apiKey = 'Cxense API KEY';  // TODO: Add your Piano API key here
var prefix = 'xyz';             // TODO: Add your Piano customer prefix here
 
function cxApiRequest(apiName, body, callback) {
    var date = new Date().toISOString(), hmac = crypto.createHmac('sha256', apiKey).update(date).digest('hex');
    console.log('Sending API request: ' + apiName + ', body: ' + JSON.stringify(body));
    request.post({
        url: 'https://api.cxense.com' + apiName,
        headers: {'X-cXense-Authentication': 'username=' + username + ' date=' + date + ' hmac-sha256-hex=' + hmac},
        body: body,
        json: true
    }, callback);
}
 
 
// The Twitter sign-in setup (using Passport and Express)
 
// Passport session setup.
//   To support persistent login sessions, Passport needs to be able to
//   serialize users into and deserialize users out of the session.  Typically,
//   this will be as simple as storing the user ID when serializing, and finding
//   the user by ID when deserializing.  However, since this example does not
//   have a database of user records, the complete Google profile is
//   serialized and deserialized.
passport.serializeUser(function(user, done) {
    done(null, user);
});
 
passport.deserializeUser(function(obj, done) {
    done(null, obj);
});
 
passport.use(new TwitterStrategy({
        consumerKey: 'Consumer Key (API Key)',          // TODO: Add your Twitter API key here
        consumerSecret: 'Consumer Secret (API Secret)', // TODO: Add your Twitter API secret here
        callbackURL: 'https://cxensebot.cxense.com/auth/twitter/callback' // TODO: 'your_url/auth/twitter/callback'
    },
    function(token, tokenSecret, profile, cb) {
        cb(null, profile);
    }
));
 
 
// Configure Express
var app = express();
var server = http.createServer(app);
app.set('port', 10520);
app.use(bodyParser.json());
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(methodOverride());
app.use(expressSession({ secret: 'funny figure', resave: false, saveUninitialized: false }));
 
// Initialize Passport!  Also use passport.session() middleware, to support persistent login sessions (recommended).
app.use(passport.initialize());
app.use(passport.session());
 
 
app.get('/auth/twitter', // TODO: call this end point as it'll redirect user to '/auth/twitter/callback' after authentication is successful
    passport.authenticate('twitter'));
 
app.get('/auth/twitter/callback',
    passport.authenticate('twitter', { failureRedirect: '/login.html' }),
    function(req, res) {
 
        // Successful authentication, link the user IDs and then redirect home.
        var cxenseId = req.cookies['cX_P'];
        var twitterId = req.user.id;
        console.log('Mapping user cxense ID: ' + cxenseId + ' and twitter ID: ' + twitterId);
 
        // The actual linking of IDs:
        cxApiRequest('/profile/user/external/link/update', { type: prefix, id: twitterId, cxid: cxenseId },
            function (error, response, body) {
                if (!error && response.statusCode === 200) {
                    console.log('Link update success!');
                } else {
                    console.log('Map error: ' + (error || response.statusCode))
                }
        });
 
        res.redirect('/');
    });
 
 
// Start server
server.listen(app.get('port'));
console.log('Listening on port ' + app.get('port'));

Tweets, likes, and follows

The Twitter integration enables recording a range of actions made with an embedded tweets/timelines or a tweet button. It can be used for audience segments and reporting, Also you can use Workspaces for better visualization of Twitter actions statistics.

 To hook into the event fired from embedded tweets/timelines or a tweet button, event handlers have to be added.

An event handler sends the event to Piano Audience as Performance event, using the cX.sendEvent(..) helper function.

  1. Make sure cx.js is deployed on your page.

  2. Set up Twitter's script (Set-up Twitter for Websites)

  3. Get HTML code of a tweet button/embedded tweet/timeline - use https://publish.twitter.com/ for it.

  4. Add an event handler according to the Twitter documentation (Scripting: Events). Use the following code when the twitter event happens:

cX.callQueue.push(['invoke', function() {
cX.setEventAttributes({ origin: 'cx-website', persistedQueryId: '1234' }); // TODO: Insert your origin and persisted query id here!
cX.sendEvent('Social', { action: 'tweet_twitter' }); // TODO: Insert a name of action you're tracking
}]);

Below is an example of the page which sends a social "tweet_twitter" event to Piano Insight after a click on the Tweet button.

<html>
   <head>
      <!-- Cxense script begin -->
      <script type="text/javascript">
         var cX = cX || {}; cX.callQueue = cX.callQueue || [];
         cX.callQueue.push(['setSiteId', '1141844407823976462']);
         cX.callQueue.push(['sendPageViewEvent']);
      </script>
      <script type="text/javascript">
         (function(d,s,e,t){e=d.createElement(s);e.type='text/java'+s;e.async='async';
         e.src='http'+('https:'===location.protocol?'s://s':'://')+'cdn.cxense.com/cx.js';
         t=d.getElementsByTagName(s)[0];t.parentNode.insertBefore(e,t);})(document,'script');
      </script>
      <!-- Cxense script end -->
   </head>
   <body>
      <!-- Twitter script begin -->
      <script>window.twttr = (function(d, s, id) {
         var js, fjs = d.getElementsByTagName(s)[0],
           t = window.twttr || {};
         if (d.getElementById(id)) return t;
         js = d.createElement(s);
         js.id = id;
         js.src = "https://platform.twitter.com/widgets.js";
         fjs.parentNode.insertBefore(js, fjs);
         t._e = [];
         t.ready = function(f) {
           t._e.push(f);
         };
         return t;
         }(document, "script", "twitter-wjs"));
      </script>
      <!-- Twitter script end -->
      <a href="https://twitter.com/share" class="twitter-share-button" data-via="cxense">Tweet</a>
      <script>
         function tweetIntentToAnalytics (intentEvent) {
           if (!intentEvent) return;
            cX.callQueue.push(['invoke', function() {
            cX.setEventAttributes({ origin: 'cx-website', persistedQueryId: '1234' }); // TODO: Insert your origin and persisted query id here!
            cX.sendEvent('Social', { action: 'tweet_twitter' }); // TODO: Insert a name of action you're tracking
          }]);
         }
         // Wait for the asynchronous resources to load
         twttr.ready(function (twttr) {
           // Now bind our custom intent events
           twttr.events.bind('tweet', tweetIntentToAnalytics);
         });
      </script>
   </body>
</html>

Insight widgets

You can create a widget in your Insight workspace to track social events. There are different types of widgets. Here you may find an instruction how to create 2 of them: breaking social events by action type (tweet, like, etc.) and unique users by pages.

Social events by action type

image2017-8-17-18-19-13.png

  1. Go to Workspace → Create Workspace/Select existing one → Add widget → Create Widget.

  2. Select Performance Parameters→ action on the lefthand panel.

  3. Select the Performance Events and Performance events: Unique Users metrics.

    • Type the Widget title.

    • Select a site group if needed.

    • Select any filter if needed.

  4. Click Add widget.

Unique users by page

22.png

  1. Go to Workspace Create Workspace/Select existing oneAdd widgetCreate Widget.

  2. Select the URL action on the lefthand panel.

  3. Select Display page title instead of URL.

    • Select Display the thumbnail for each URL.

    • Select the Unique users metric.

    • Type your Widget title.

    • Select a site group if necessary.

    • In the Filters section select Performance Parametersaction is and leave the last dropbox empty.

  4. Click Add widget.

Last updated: