Core SDK

Download or Link: tbits-sdk.js

Embed Campaigns, Stream and Comments into your mobile app or other site. Want more customization? Build your own look.


Integrate social login or data from Stream with this Javascript API library. The required input is your account number and Stream key values.

Stream Method List

STR.init( streamKEY )

Initialize the Stream object and set the variables.


STR.records( opts, callback )

Fetch the records from the server according to the selected filter and options

Options:

  • limit - max number of records
  • networks - comma separated list of networks
  • label - return records only labelled with given label
  • is_graphic - return only records with non-empty image
  • min_time_key - return records with time_key greater than given value *
  • max_time_key - return records with time_key less than given value
  • q - text search for caption
  • start_latitude - GEO box for records with geo information
  • start_longitude - GEO box for records with geo information
  • end_latitude - GEO box for records with geo information
  • end_longitude - GEO box for records with geo information
* min_time_key will change the order from desc chronological to normal


STR.nextPage( callback )

Given the conditions set previously with the STR.records() call, this function will return the following records (i.e. with time_key greater than previous max time key).


STR.convertLinks( caption,network,props )

Utility function to identify and convert links in the caption


STR.prevPage( callback )

Given the conditions set previously with the STR.records() call, this function will return the previous records (i.e. with time_key less than previous min time key)


STR.summary( callback,options)

Return a summary view of the Stream. Result is a hash which includes:

  • approved_total
  • stream_name
  • stream_key
  • total
  • last_record_timestamp

Options is a json dict with following entities

  • data comma separated list of sections to include. Currently supports: words, labels, hashtags
  • label Character String with label name

STR.cube( callback, options)

Return a breakdown by given dimensions for analytics purposes. Supported options:

  • dimensions: comma separated list of 'gender', 'author', 'label_key', 'network', 'country', 'province'
  • label_key Provides summary specific to the label

STR.record( feed_record_id, callback )

Return a single record given then ID


STR.authors( limit, callback )

Get last N author records from the Stream. Display a Facebook Facepile with this call.

Structure:

  • author_id
  • network
  • user_key
  • name
  • image_url

STR.topAuthors( options, callback )

Get Top Authors in the stream according to label

Parameters:

  • sort_order in reach,vote_count
  • label
  • limit

Structure:

  • author_id
  • network
  • user_key
  • name
  • image_url
  • reach_count
  • posts

STR.reportBrokenRecord( feed_record_id )

If a post is removed or made private on a social network, this post will be broken in the Stream and can be reported with this call. You can also use this call to report broken image URLs. The most common usage is to include a call to STR.reportBrokenRecord() on an "onerror" event for the image.


STR.reportRecord( feed_record_id )

This call handles the "report" button for the public view of the Stream. Once reported, the post will be available in the moderation queue as reported by the user.


STR.connectSession( sessionUid, callback )

This call connects the session previously initialized with initSession call to the Stream. Once connected, the server returns a profile record for display.


STR.createRecord( caption, recordMediaUid, options, callback )

Use this call to create new record in the Stream. "caption" is the text associated with the record and recordMediaUid is a reference to the image uploaded with /upload_image call previously. See the examples below for more details.

Authenticated

When you call STR.connectSession previously and initialize the profile, createRecord will create a record tied to the profile using the social network information.

Not-Authenticated

When createRecord is called directly you need to supply the options: name and email. They will be associated with the record instead of the profile.

upload_image endpoint

upload_image endpoint is a HTTP url which can be used to upload binary images into the server for association with Stream records.
Full url is "https://tradablebits.com/upload_image" and the only required parameter is form_uid which is client side generated unique identifier for the media. End point supports CONTENT_RANGE options and will return json data with media_uid which can be used for record creation upon success.


STR.trackClick( feed_record_id )

Use this call to track when a user clicks a link inside a record. This allows you to track which posts are trending in Stream Stats. The most common usage is to include a call to STR.trackClick() on "onclick" events for a link.



Stream SDK example

Simple fetch for all records in the Stream "test"

<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.0.min.js" ></script>
<script type="text/javascript" src="https://tradablebits.com/static/js/libs/moment.min.js" ></script>
<script type="text/javascript" src="https://tradablebits.com/static/js/libs/underscore.js" ></script>
<script type="text/javascript" src="https://tradablebits.com/tbits-sdk.js" ></script>
<script type="text/javascript" >
    /** Example of STR usage. Note: You don't have to use underscore as template engine.
    Code below is provided for reference only **/
    function callback(res){
        console.log(res.meta);
        var recTemplate = $("#record-template").html();
        var $results = $("#results");
        for(var idx in res.data){
            /* This is where the rendering of the result is done. Modify to match your site */
            $results.append(_.template(recTemplate,res.data[idx]));
        }
    }

    /* Click Handler to track caption link clicks */
    $('body').on('click', '.item-caption a', function() {
        var feedRecordId = this.parentNode.dataset.feedRecordId;
        STR.trackClick(feedRecordId);
    });

    STR.init("test");
    /* pulling the records. Check the reference for additional options */
    STR.records({ is_graphic: true },callback);
</script>
<script type="text/template" id="record-template">
    <div class="item-record">
        <div style="width:24px;height:24px;color: #f5f5f5;background-color: #333;float: left;">
            <svg viewBox="-15 -15 110 110">
                <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://tradablebits.com/static/svg/sprites.svg#<%-network%>-path"></use>
            </svg>
        </div>
        <% if (image_url){ %>
            <div class="item-image">
                <img src="<%-image_url%>" onerror="return STR.reportBrokenRecord(<%= feed_record_id %>);" />
            </div>
        <% } %>
        <div class="item-profile">
            <div class="profile-image">
                <% if (author_image_url && profile_url){ %>
                    <a href="<%= profile_url %>" target="_blank" onclick="STR.trackClick(<%=feed_record_id %>)">
                        <img src="<%= author_image_url %>" alt="" onerror="$(this).hide();"/>
                    </a>
                <% }else{ %>
                    <img src="https://tradablebits.com/icons/author-placeholder.png"/>
                <% } %>
            </div>
            <div class="profile-name">
                <%-author_name %><br/>
                <% if(author_screen_name && network=="twitter"){ %>
                    @ <%-author_screen_name%>
                <% } %>
            </div>
            <% if (network == 'twitter') { %>
                <div style="text-align: right;width:100%;">
                    <div class="twitter-actions">
                        <a class="item-links" href="https://twitter.com/intent/tweet?in_reply_to=<%= record_key %>">
                        <span class="glyphicons reply"></span></a>
                        <a class="item-links" href="https://twitter.com/intent/retweet?tweet_id=<%= record_key %>">
                        <span class="glyphicons retweet"></span></a>
                        <a class="item-links" href="https://twitter.com/intent/favorite?tweet_id=<%= record_key %>">
                        <span class="glyphicons star"></span></a>
                    </div>
                </div>
            <% } %>
        </div>
        <div class="item-caption" data-feed-record-id="<%=feed_record_id%>">
            <%= STR.convertLinks(caption,network,props) %>
        </div>
        <hr/>
        <% if (record_url){ %>
            <a href="<%-record_url%>" target="_blank" class="blank-link">
                <div class="network-icon">
                    <svg viewBox="-5 -10 110 110">
                        <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="/static/svg/sprites.svg#<%- network %>-path"></use>
                    </svg>
                </div>
            </a>
        <% }else{ %>
            <div class="network-icon">
                <svg viewBox="-5 -10 110 110">
                    <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="/static/svg/sprites.svg#<%- network %>-path"></use>
                </svg>
            </div>
        <% } %>
        <br/>
        <p class="small creation-timestamp"><%= moment.unix(creation_timestamp).fromNow() %></p>
    </div>
</script>
<div id="results">
</div>
                    

Summary Stream SDK Example

Generate a summary call with breakdown by label and include top keywords

<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.0.min.js" ></script>
<script type="text/javascript" src="https://tradablebits.com/static/js/libs/moment.min.js" ></script>
<script type="text/javascript" src="https://tradablebits.com/tbits-sdk.js" ></script>
<script type="text/javascript" >
    /** Example of STR usage. Note: You don't have to use underscore as template engine.
    Code below is provided for reference only **/
    function callback(res){
        console.log(res.words);
        console.log(res.labels);
        console.log(res.total + " total records");
    }

    STR.init("test");
    /* pulling the records. Check the reference for additional options */
    STR.summary(callback,{data:"labels,words"});
</script>
                    

TBITS Method List

TBITS.init( ApiKey )

Initialize the new instance for TBITS handler using public API KEY


TBITS.getCounter( counterName,callBack )

Obtain the value of the counter


TBITS.checkCounter( counterName,callBack )

Check if user has voted previously and return counter together with status


TBITS.updateCounter( counterName,callBack )

Increment the value of the counter by 1


TBITS.getProps( counterName,callBack )

Get custom meta data associated with specific property


TBITS.updateProps( counterName,props, callBack )

Update meta data associated with property



<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.0.min.js" ></script>
<script type="text/javascript" src="https://tradablebits.com/tbits-sdk.js" ></script>
<script type="text/javascript" >
    /** Example of Counter usage. Note: You don't have to use underscore as
    template engine. Code below is provided for reference only **/
    function callback(res){
        var $counter = $("#counter");
        $counter.html(res);
    }
    $(document).ready(function(){
        TBITS.init('api key');
        TBITS.getCounter('test_counter',callback);
    });
    function upVote(){
        TBITS.updateCounter('testCounter',callback);
    }
</script>
<div id="counter"></div>
<a href="javascript:upVote()"> Vote </a>

            

TBITSAUTH Method List

TBITSAUTH.init( ApiKey, sessionUid )

Initialize the new instance for TBITSAUTH handler using public API KEY and session uid


TBITSAUTH.getIdols( callBack )

Get the idols for a given fan


TBITSAUTH.insertFanIdol( idolName,callBack )

Create idol-fan record for given idol name


TBITSAUTH.removeFanIdol( idolName,callBack )

Remove idol-fan record for given idol name



<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.0.min.js" ></script>
<script type="text/javascript" src="https://tradablebits.com/tbits-sdk.js" ></script>
<script type="text/javascript" >
    /** Example of Idols usage. Note: You don't have to use underscore as
    template engine. Code below is provided for reference only **/
    $(document).ready(function() {
    // Initialize session with Tradable Bits account id
        initSession(1, callback);
    });

    function callback(sessionUid) {
        console.log("Session Initialized, Session UID: " + sessionUid)
        // Initialize TBITSAUTH with public API key, and session uid
        TBITSAUTH.init('156b893f-9d7c-4685-bdeb-b48ce9a700f8', sessionUid);
    }

    function getIdols() {
        TBITSAUTH.getIdols(idolCallback);
    }

    function insertJohnDoe() {
        TBITSAUTH.insertFanIdol('John Doe', idolCallback);
    }

    function removeJohnDoe() {
        TBITSAUTH.removeFanIdol('John Doe', idolCallback);
    }

    function idolCallback(res) {
        console.log(res);
    }

</script>
<a href="javascript:getIdols()"> Get Idols </a>
<a href="javascript:insertJohnDoe()"> Insert John Doe Idol </a>
<a href="javascript:removeJohnDoe()"> Remove John Doe Idol </a>
            

APPS Method List

APPS.init( ApiKey, tab_id )

Initialize the new instance for APPS handler using public API KEY and page tab id.


APPS.getTabData( callback )

Get all props, images and campaign specific items for the page tab.

Passes a dictionary with the listed key to the callback function.

  • fields: a list of custom field objects
  • media: contains media_type objects that each contain a dictionary of media urls with the media_idx as the key
  • streamkey: string
  • description: string
  • rules: string
  • label: string
  • name_text: string
  • quiz_questions: object (for quiz like campaigns)
  • poll_options: object (for poll like campaigns)
  • tab_games: object (for bracket, tug of war)
  • tab_deals: object (for instantwin, coupons)
  • tab_items: object (contains tab images)

APPS.getFanDetails( callback )

Passes a list of fans that participated in the campaign to the callback.

Each fan is an object with keys:

  • fan_id: int
  • name: string
  • email: string

APPS.saveFanDetails( data, callback )

Saves the fan data and adds the fan to the list of fans that participated in the campaign.

Data:

  • name: string
  • email: string
  • is_subscribed: boolean
  • field_[crm_field_key]: string
  • phone: string
  • birthdate: string(year-month-day)

data is a javascript object with the listed keys. name, email and is_subscribed are mandatory fields. For multiselect fields, use the same field_[crm_field_key] for each selected option

Returns the saved fan.


APPS.fanAuth()

Authenticates the fan using Facebook. Authenticate the fan before saving the fan detail to link the fan to their Facebook account.


APPS.fanLogout()

Deletes the fan's cookie to allow the next fan data to be saved. Should be used after saving a new fan and before saving another fan.


APPS.trackShare( fan_network )

Call this each time the campaign is shared to track the shares to social networks by fans. fan_network should be a string. The share will only be recorded if the fan has authenticated using Facebook.



//An example usage of the APPS methods to collect and save fan input with and 
//without Facebook authentication

<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.0.min.js" ></script>
<script type="text/javascript" src="https://tradablebits.com/tbits-sdk.js" ></script>
<script type="text/javascript" >
    apiKey = "156b893f-9d7c-4685-bdeb-b48ce9a700f8";
    tab_id = "27";

    function callback(res){
        console.log(res);
        keys =_.map(res.fields, 
            function(field){
                return {key:field.crm_field_key,
                        title: field.title}
            })
        console.log(keys)
        var templateData = {
            fields: keys
        }

        var template = _.template(
            $("#fields_tmpl").html()
        );

        $("#custom-fields").after(
            template(templateData)
        );
    }

    function saveCallback(){
        console.log('Fan saved')
    }

    function getUserInput(){
        data = {}
        $('.core').each(
            function(){
                data[$(this).attr('name')] = $(this).val();
                if($(this).attr('type') == 'checkbox') data[$(this).attr('name')] = this.checked;
            })
        $('.custom-field').each(
            function(){
                data['field_'+$(this).attr('name')] = $(this).val();
            })
        return data
    }

    function AuthSubmit(){
        data = getUserInput()
        APPS.fanAuth();
        APPS.saveFanDetails(data, saveCallback)
    }

    function noAuthSubmit(){
        data = getUserInput()
        APPS.saveFanDetails(data, saveCallback)
        APPS.fanLogout()
    }

    $(function(){
        APPS.init(apiKey, tab_id);
        APPS.getTabData(callback);
    });

</script>

<div class='container'>
    <div class='form'>
        <h1>Example</h1>

        <h2> Core Fields </h2>
        <div class="form-group">
            <label for="name">Name</label>
            <input class="form-control core" type="text" name="name">
        </div>
        <div class="form-group">
            <label for="email">Email</label>
            <input class="form-control core" type="text" name="email">
        </div>

         <div class="checkbox">
            <label for='is_subscribed'>
              <input class="core" type="checkbox" name="is_subscribed"> Subscribe
            </label>
        </div>
        <h2 id='custom-fields'> Custom Fields </h2>

        <button class='btn btn-default' onclick="noAuthSubmit();">No Auth Submit</button>
        <button class='btn btn-default' onclick="AuthSubmit();">Auth Submit</button>
    </div>
</div>
            

Authentication

Method List

initSession( accountId, callback, options )

This call will open a popup window and handle the entire process of authentication. Upon success, the callback function will be called with the included session information. Callback function will be passed sessionUid value as input.

Arguments

  • accountId - Tradable Bits Account ID. The account must have a valid subscription.
  • callback - Callback function
  • options - Hash which may include following elements
    login_type: suggested login type: "facebook,twitter,google,etc"
  • loginType - Suggested login type: e.g. Facebook, Twitter, etc. If the network is not supported, it will be ignored.


closeSession()

Clears the session state locally on the browser side.


getSession( sessionUid, callback )

Fetch the session information given the session Uid.

Returned Structure

  • status - state of the session
  • fan_id - identifier for the user record
  • name - full name
  • network - network of the source



Authentication SDK example

Using Authentication with Stream upload
 /** example of STR usage **/
<script type="text/javascript" src="https://tradablebits.com/tbits-sdk.js" ></script>
<script type="text/javascript" >
    STR.init({stream_key:"test"});
    STR.records({ is_graphic: true },callback);

    function authCallback(sessionUid){
        STR.connectSession(sessionUid,function(profile){
            var caption = $("#caption").val();
            STR.createRecord(caption,null,{},function(){
                alert("Thank you for uploading");
            });
        });
    }

    $("#upload").on('click',function(){ initSession(12345,authCallback); return false; });
</script>
                    

Embedding Facebook Apps, Comments and Stream via iFrame

Download: embedded.js

Embed existing visuals into your website via iFrame with the embedded.js library. The resulting iFrame will automatically resize itself vertically, matching the content height.


Method List

loadTradablebitsApp( divId, pageTabId )

Render the application inside the div via given ID. PageTabId can be retrieved from the microsite URL. The first number is ID of the tab.


loadCommentsWidget( divId, accountId, options )

Render comments widget via the given ID of the div and threadUid. Thread UID again can be retrieved from the URL.


loadStream( divId, streamKey, label )

Render Stream inside the div. This div/iFrame will automatically resize with content and is intended to be used with infinite scroll. If that's not the intended behavior, it is recommended to embed the iFrame directly.


loadStreamWidget( divId, streamKey )

Embed Widget into the Div


loadStreamShop( divId, streamKey, label)

Render Stream in the form of shoppable feed ( iframe will extend as content grows)



Embedding Example

Simple embed of Stream widget
<!-- HTML Example for embed -->
<div id="sample-div"></div>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.0.min.js" ></script>
<script type="text/javascript" src="https://tradablebits.com/embedded.js" ></script>
<script type="text/javascript">
    $(document).ready(function(){
        loadStream("sample-div","test",null);
    });
</script>
                    

Introduction

API Access allows you to query Stream and user data using RESTful API, as well as register for push notification from our CRM system. API Reference is broken into sections by topic: Facebook Apps (Campaigns) Data, Stream Data, CRM Data.
Each Request must include api_key as parameter. You can generate an API key in the Manage Centre.

Console

API Access allows you to query Stream and user data using RESTful API, as well as register for push notification from our CRM system. API Reference is broken into sections by topic: Facebook Apps (Campaigns) Data, Stream Data, CRM Data.


Each Request must include api_key as parameter. You can generate an API key in the Manage Centre.
You may try most of our API calls here. Your API Key will be automatically appended if available.


Custom Campaign

The Custom Campaign endpoint helps you create your own custom engagement campaign visuals, while still using the Tradable Bits back end for managing and reporting on entries.

Custom

api/v1/apps/[ TAB_ID ]

GET Result Structure:
fields
[ {custom_field}, {custom_field}, ... ]
media
[ { media_type: { media_idx: media_url }, ... }, .. ]
streamkey
type: string
rules
type: string
name_Text
type: string
label
type: string
Custom Field:
crm_field_key
type: string
field_id
type: int
field_idx
type: int
field_options
type: [ string, ... ]
is_fan_field
type: boolean
is_mandatory
type: boolean
page_tab_id
type: int
title
type: string

Fan Details

api/v1/apps/[ TAB_ID ]/fan_details

GET Result Structure:
Array
[ {fan}, {fan}, ... ]

POST Parameters:
name
type: string
email
type: string
is_subscribed
type: boolean
phone
type: string
birth_date
type: string (year-month-day)
field_[ CRM_FIELD_KEY ]
type: string
tag_[ TAG_NAME ]
type: false or true
Fan Object
fan_id
type: int
name
type: string
email
type: string

Fan CRM

The Fan CRM endpoint covers the fan data and allows you to query for user information. All of the calls in this section require API Secret as a parameter.

Fans

Returns a list of fans, based on the number of GET parameters. for POST request method will create a new fan record and return it. Parameters for POST are similar to /fans/xxx call.

/api/v1/crm/fans

GET Parameters:
name
Case-insensitive portion of the name or e-mail
Type: string
Example: John, John@test.com
start_date
Start date of date range of creation date
Type: string
Example: 2013-01-01
end_date
End date of date range of creation date
Type: string
Example: 2013-12-31
last_update_timestamp
ISO formatted String
Type: string
Example: 2015-01-01T01:01:01
limit
Maximum number of records to be returned
Type: int
Example: 10
offset
Number of fans to skip
Type: int
Example: 25

GET Result Structure:
offset
[ {fan}, {fan} ]

Fan

Returns or updates information about a fan. A POST call will update the fan information and a DELETE call will delete the fan record.

/api/v1/crm/fans/[ FAN_ID ]

Result Structure
fan_id
Type: long
account_id
Type: int
name
Type: string
login_name
Type: string
email
Type: string
image_url
Type: string
creation_timestamp
Type: int
ip_address
Type: string
country
Type: string
city
Type: string
fields
Type: { "string" : "string", }
connected_fans
Type: [ long, long,... ]
networks
Type: [ struct, struct,... ]
last_update_timestamp
Type: int

Fan attributes can be modified via POST calls to the /api/v1/crm/fans/[ FAN_ID ] endpoint. The following arguments can be passed over to the request.

name
Type: string
email
Type: string
login_name
Type: string
image_url
Type: string
is_subscribed
Type: boolean
reset_uid
Specifying this parameter will initialize reset_uid for the fan which can be used to reset the password
Type: boolean
field_[ CRM_FIELD_KEY ]
Type: value
tag_[ TAG_NAME ]
type: false or true
password
Type: string
phone
Type: string
birth_date
Type: string

Merge Fan

Returns or updates information about a fan. A POST call will update the fan information and a DELETE call will delete the fan record.

/api/v1/crm/fans/[ FAN_ID ]/merge

Parameters

target_fan_id
Type: long

Fan Activities

Retrieve or create a new activity based on the title and list of attributes. When called as GET - the call will return a list of last N activities A GET call will retrieve the most recent interactions of a fan that have been created through this endpoint.

/api/v1/crm/fans/[ FAN_ID ]/activities

GET or POST Parameters:
limit
Maximum number of activities to be returned
Type: int
Example: 10
POST Parameters:
campaign_title
For POST requests only, specify the name of the campaign you wish to store the interaction.
Type: string
Example: My_Campaign_Title
field_[ FIELD_KEY ]
Key value pairs used to store any custom meta data for an interaction. Field must be registered as custom field in CRM config
Type: string
Example: "field_fav_colour":"blue"
GET Result Structure:
Array
[ {activity}, {activity}, ... ]
Activity Result Structure:
fan_id
Type: int
campaign_title
Type: string
creation_date
Type: string
creation_timestamp
Type: int
props
Type: { key:value, key:value, ... }

Fan Followings

Get list of person's interests from connected networks (instagram,spotify,twitter, facebook)

/api/v1/crm/fans/[ FAN_ID ]/followings

GET Result Structure:
Array
[ {following}, {following} ]
Following Result Structure:
network
Type: string
user_key
Type: string
username
Type: string
name
Type: string
follower_count
Type: long

Fan Idols

A GET call will retrieve a list of the idols for a given fan. A POST call will create a new idol-fan record for a given idol name. A DELETE call will delete a idol-fan record for a given idol name.

/api/v1/crm/fans/[ FAN_ID ]/idols

POST and DELETE Parameters:
idol_name
The name of the idol required to create/remove the idol-fan relationship
Type: string
Example: John Doe
GET, POST and DELETE Result Structure:
Array
[ {idol}, {idol}, ... ]
Idol Result Structure:
idol_uid
Type: uuid
account_id
Type: int
idol_name
Type: string
creation_timestamp
Type: int
facebook_id
Type: long
facebook_screen_name
Type: string
twitter_screen_name
Type: string
instagram_screen_name
Type: string
spotify_uid
Type: string

CRM Fields

This call will return an array of configured custom fields and their options

/api/v1/crm/fields

GET Result Structure:
Array
[ {field}, {field}, ... ]
Field Result Structure:
crm_field_key
Type: string
field_type
Type: string
is_mandatory
Type: bool
field_options
Type: [string, string, ...]
is_active
Type: bool
account_id
Type: int
creation_timestamp
Type: Unix time

CRM Activities

This call can be used to synchronize the data between your CRM and our platform. Upon request it will return incremental list of activities associated with all of campaigns and social logins. Call supports paging and ability to fetch incrementals

/api/v1/crm/activities

GET Parameters:
max_activity_id
Return Activities prior to given value
Type: long
Example: 12345
min_activity_id
Return Activities after to given value
Type: long
Example: 12345
limit
Max number of rows to be returned ( max: 200 )
Type: long
Example: 150
Result Structure:
Hash
{ meta: { max_activity_id: XXX, min_activity_id: XXX, count: XXX, order: desc/asc },
data: [ {activity}, {activity}, {activity} ]
}

{"meta": {"count": 2, "max_activity_id": 2, "order": "asc", "min_activity_id": 1},
 "data": [
            {"campaign_type": "page_tab", "page_tab_id": 4, "activity_id": 1,
                "app_type": "entryform", "account_id": 1, "stream_key": null,
                "is_subscribed": true, "creation_date": "2016-06-03",
                "campaign_title": "Test Facebook Page / Test Campaign",
                "fan": {"rating": null, "account_id": 1, "tags": [], "is_subscribed": false,
                        "phone": "", "fan_id": 3, "ip_address": "127.0.0.1", "city": "",
                        "name": "Joe Smith", "last_update_timestamp": 1464991884,
                        "gender": "male", "email": "joe@test.com",
                        "image_url": "https://graph.facebook.com/123/picture?type=large",
                        "fields": [{"crm_field_key": "test1", "value": "bvalue1"},
                                   {"crm_field_key": "tset2", "value": "value2"}],
                        "birth_date": null, "country": null, "creation_timestamp": 1464977289,
                        "login_name": "test@tradablebits.com",
                        "reset_uid": null},
                networks: [{"network": "facebook", "last_update_timestamp": 1465325817,
                            "user_key": "123", "fan_id": 3, "account_id": 1,
                            "access_token": "xxxxx",
                            "image_url": "https://graph.facebook.com/123/picture?type=large",
                            "props": {"min_age": 21},
                            "access_secret": null, "follower_count": 179, "creation_timestamp": 1464977289,
                            "email": "joe@test.com", "profile_url": "https://www.facebook.com/123",
                            "name": "Joe Smith"}],
                "details": [], "fan_id": 3, "crm_campaign_id": 1,
                "creation_timestamp": 1464977289},
            {"campaign_type": "page_tab", "page_tab_id": 1, "activity_id": 2, "app_type": "ecard",
                "account_id": 1, "stream_key": null, "is_subscribed": false,
                "creation_date": "2016-06-03",
                "campaign_title": "Free Welcome Pages / eCard",
                "fan": {"rating": null, "account_id": 1, "tags": [], "is_subscribed": false,
                        "phone": "", "fan_id": 3, "ip_address": "127.0.0.1", "city": "",
                        "name": "Joe Smith", "last_update_timestamp": 1464991884, "gender":
                        "male", "email": "joe@test.com",
                        "image_url": "https://graph.facebook.com/1234/picture?type=large",
                        "fields": [{"crm_field_key": "test1", "value": "bvalue1"},
                                   {"crm_field_key": "tset2", "value": "value2"}],
                        "birth_date": null, "country": null, "creation_timestamp": 1464977289,
                        "login_name": "test@tradablebits.com", "reset_uid": null},
                "networks": [],
                "details": [{"field_value": "97ceaebd-4b39-4ac5-b803-0440195a5aa4",
                            "field_name": "Default Title", "detail_type": "ecard"}],
                "fan_id": 3, "crm_campaign_id": 2, "creation_timestamp": 1464977289}
        ]
}
                
            

Stream API Reference

This API portion covers calls tied to Stream records. This API allows you to search and query for given records. Your STREAM_KEY is the subdomain you used to set up your Stream and can be found in the microsite URL (http://[ STREAM_KEY ].tbits.me) Please also see the SDK reference for javascript implementation.

Streams

List account streams, create or delete existing stream

/api/v1/streams

POST Parameters:
stream_key
Key to identify new stream. a-z and 0-9 are the only supported characters.
stream_name
Character Description of the stream
trust_level
Moderation level. 0 means manual approval, 1 is autoapproval, -1 is author pre-approval
source_stream_key
Key of existing streams to fetch authentication tokens from
action
create or delete

Result Structure:
array of records or boolean value for post

Identified Authors

Manage list of specially marked authors ( either for automatic approval or ban). GET call will return an active list of identified authors and POST call allows to add or remove the user

/api/v1/streams/[STREAM_KEY]/identified_authors

POST Parameters:
network
twitter or instagram
action
create or delete
status
verified, banned, troll
user_key
required for delete call. User_key is returned as part of structure on GET call
screen_name
required for create call.

Result Structure:
array of records or boolean value for post

Summary

Returns a list of record objects, based on a number of GET parameters, and creates a new record on POST request

/api/v1/streams/[ STREAM_KEY ]

GET Parameters:
data
Comma separated list of sections to include into the summary. Supported sections:
  • words - to keywords used in stream
  • labels - label stats breakdown
  • hashtags - for registered hashtags (via stream config) return breakdown

Type: string
Example: words,labels,hashtags
label
Limit Summary to posts with specific label name.
Type: string
Example: foo
label_key
Limit Summary to posts with specific label key.
Type: string
Example: bar

Result Structure:
hash
{ "total_stored": xxx, "stream_name": "xxx", "stream_key": "xxx", "reach": xxx, "approved_total": xxx .... }

Records

Returns a list of record objects, based on a number of GET parameters, and creates a new record on POST request

/api/v1/streams/[ STREAM_KEY ]/records

GET Parameters:
q
Query to search for records containing the word/phrase.
Type: string
Example: foo
networks
Comma separated list of network names to filter after records.
Type: string
Example: facebook,twitter,youtube
label
A single label name as stored in the database.
Type: string
Example: foo
label_key
A single label key as stored in the database.
Type: string
Example: bar
sku
Search by SKU numbers as specified on the label
Type: string
Example: SK124
max_time_key
Return the data with a time key less than given. Time Key combines unix timestamp with internal numeric key. Only one max_time_key or min_time_key may be specified.
Type: string
Example: 132311231_12314
min_time_key
Return the data with a time key greater than given. Time Key combines unix timestamp and internal numeric key. Only one max_time_key or min_time_key may be specified. Also, setting this parameter will change the sort order.
Type: string
Example: 132311231_12314
start_latitude
These parameters allow you to set GEO restrictions on the returned data
Type: float
Example: -122.13
end_latitude
These parameters allow you to set GEO restrictions on the returned data
Type: float
Example: -122.0
start_longitude
These parameters allow you to set GEO restrictions on the returned data
Type: float
Example: 49
end_longitude
These parameters allow you to set GEO restrictions on the returned data
Type: float
Example: 50
limit
Max number of records to be returned. Must be less than 100.
Type: int
Example: 25

Result Structure:
hash
{ "meta" : {}, "data" : [ {records} , {records} ] }


POST Parameters:
caption
Type: string
image_url
Type: string
latitude
Type: float
longitude
Type: float
email
Type: string
This parameter is optional
name
Type: string
This parameter is optional
fan_id
Type: string
Fan Id is optional, however if it's not specified, email must be supplied
props_*
Type: string
These set of parameters allow to add custom meta data into the record
labels*
Type: string
Comma separated list of labels

Record

GET call will return particular record details. It requires api_key as input parameter.
POST call allows to change moderation status and hide the record if needed.
POST will require both api_key and api_secret values submitted.

/api/v1/streams/[ STREAM_KEY ]/[ RECORD ID ]

POST Parameters
action
One of: label, unlabel, approve, remove
label
optional label name for label/unlabel calls
label_key
optional label key for label/unlabel calls
Result Structure
author_id
Type: long
author_user_key
Type: string
author_image_url
Type: string
author_name
Type: string
profile_url
Type: string
labels
Type: [ { label_id : int, label_key: string, sku: string } ]
time_key
Type: string
record_key
Type: string
record_url
Type: string
stream_key
Type: string
latitude
Type: float
longitude
Type: float
feed_record_id
Type: long
network
Type: string
author_id
Type: string
caption
Type: string
video_url
Type: string
image_url
Type: string
width
Type: int
height
Type: int
creation_timestamp
Type: int
last_update_timestamp
Type: int

HTTPS proxy for images

By default we return image_url as it is specified in the stream records. In certain cases you may need to shield the content with an https protected link. There is a proxy which provides a fully encrypted connection on http://localhost:8001//streams/[ STREAM_KEY ]/images/[ FEED_RECORD_ID ]

Report Broken Image

/api/v1/streams/[ STREAM_KEY ]/[ RECORD_ID ]/broken

The API has the ability to report back a broken image for verification. The result is simple a boolean True on success.

Calls below available only for accounts with explicitly granted privileges. Please contact us to get your account whitelisted

Proxy

This call allows to query remote network directly bypassing our Rules and Storage subsystem.

/api/v1/streams/[ STREAM_KEY ]/proxy

GET Parameters:
network
twitter, facebook, instagram, youtube
source_type
One of: facebook_topic instagram_grant instagram_like instagram_tag instagram_user twitter_tag twitter_user twitter_word youtube_user youtube_playlist youtube_channel
source_value
For all, but facebook_topic sources this value contains corresponding hashtag or username or keyword
source_name
For Facebook Topic, used as Topic Name. Otherwise can be omitted in the call.

Result Structure:
array of records
[]

Feeds

This call allows to create/delete/list feeds bypassing web interface. Support for API is limited to Twitter, Instagram and Facebook Networks

/api/v1/streams/[ STREAM_KEY ]/feeds

POST Parameters:
network
facebook, gnip, twitter, instagram
action
create or delete
source_value
For all but facebook_topic sources this value contains corresponding hashtag or username or keyword
source_name
For Facebook Topic, used as Topic Name. Otherwise can be omitted in the call.
source_type
One of facebook_topic, facebook_page, instagram_tag, instagram_user, twitter_tag, twitter_user, twitter_word, gnip_tag, gnip_user, youtube_user, youtube_playlist, youtube_channel
label_key
When creating a feed, this associates all posts in that feed with the given label key. If the given label key does not exist, it is created.

Result Structure:
For POST calls it's a boolean "true" to confirm creation. For GET call it's a list of existing feeds


# List Existing Feeds
curl "https://tradablebits.com/api/v1/streams/test/feeds?api_secret=XXXXXXXX-XXXX-XXXX-XXXXXXXXXXXX"
# Create New Feed with hashtag #starwars
curl -F action=create \
     -F network=twitter\
     -F source_type=twitter_tag\
     -F source_value=starwars "https://tradablebits.com/api/v1/streams/test/feeds?api_secret=XXXXXXXX-XXXX-XXXX-XXXXXXXXXXXX"


            

Session Access

This section relies on api_key and session_uid for most of the calls.

Session

Obtain the structure for a valid session (session_uid is returned as part of the authentication call via the Javascript SDK)

/api/v1/sessions/[ SESSION_UID ]

Result Structure:
session_uid
Type: uuid
fan_id
Type: long
account_id
Type: int
expiration_timestamp
Type: long
props
Type: json structure with connection specific props

Fan Information

Retrieve or update information for the fan based on the session UID. Response and parameters are similar to the /crm/fan/ call.

/api/v1/sessions/[ SESSION_UID ]/fan

Fan Activities

Retrieve or create meta data for a fan interaction. Response and parameters are similar to the
/crm/fans/[ FAN_ID ]/activities call.

/api/v1/sessions/[ SESSION_UID ]/activities

Fan Network(s)

Fetch and/or update network membership for the fan record. On GET this endpoint will return a list of connected networks to the fan profile on POST with two params: network and user_key the call will remove corresponding network from fan profile.

/api/v1/sessions/[ SESSION_UID ]/networks

Initialize New Connection

Initiate a new connection and new session.

/api/v1/sessions/connect

Parameters:
network
Type: email|register|facebook|twitter|google|etc
access_token
Type: string
access_secret
Type: string
email
Type: string
name
Type: string
password
Type: string

Fan Idols

A GET call will retrieve a list of the idols for a given fan. A POST call will create a new idol-fan record for a given idol name. A DELETE call will delete a idol-fan record for a given idol name.

/api/v1/sessions/[ SESSION_UID ]/session_idols

Misc Calls

Some miscellaneous calls covering getting the status of the account and related.

Status

Get Current Account Id (this call can simply be used to verify api key)

/api/v1/status

Apps

Obtain list of apps for authentication options.

/api/v1/account_apps

CSS Stream Customization

Override default class values and hide elements to perfect your branded Stream.

Standalone Visual most commonly overridden classes

class description
.stream-wrap Entire body of the page excluding navigation
.navbar-stream Navigation Bar
.filter-network Network filter buttons in the navigation
.item-wrap Container for each post
.modal-wrapper Wrapper for the modal (new post and post details)

Widget Visual most commonly overridden classes

class description
.widget-body Entire body of the widget visual
.player-body Entire body of the single player visual
.record-tile Each of the tiles in the widget display

Background for Stream

Example: Changes Stream background to red

.stream-wrapper {
background-color: red;
}

Default Posts Colours

Example: Changes Stream posts to green, text to white

.item-wrap {
background-color: green;
color: white;
}

Custom Posts

Custom Posts can be configured directly from Stream Moderate (under the Custom Posts tab). They do not display author info or timestamp, and can include HTML inside the post.

Example: Changes Custom Posts to a blue background with white text

.custom-item .item-wrap{
background: blue;
color: white;
}
            

Labelled Posts

Example: Changes posts with a specific label to light green background

.label-[YOUR-LABEL-NAME] .item-wrap { /*change [YOUR-LABEL NAME] to the specific label */
background: lightgreen;
}
            

Pinned Posts

Posts can be pinned from Stream Moderate by clicking on the pin icon on hover over an image or text post.

Example: Changes Custom Posts to a gray background

.pinned .item-wrap{
background: #999;
}
            

Stream Navigation

Example: Changes Stream top navigation bar to a white background

.navbar {
background: #fff;
}
                

Social Icon Colour

Example: Changes Stream social icons to yellow icons in black box

.navbar-stream a.pressable {
color: yellow;
background-color: black;
}
                

Looking for more? Please contact us and we'll be happy to help you to customize your Stream.

Social Apps Campaign Customization

Personalize your campaigns with custom CSS! Easily edit the look of our 28+ social campaign options to suit your brand aesthetic. Social campaign CSS can be edited from the Campaign Setup under 'Additional Settings'. Here are some examples of simple changes to get you started.



Custom CSS is available for Plus clients only. Upgrade now to personalize the platform.

Container Background Colour

Example: Changes Campaign container background to grey

.standalone-content {
    background-color: #E7E7E7;
}
                    

Button Colour

Any buttons shown in an app, such as voting apps, can be styled. Remember to include a hover state when styling buttons.

Example: Changes default button background to purple and text to white

.btn-default {
color: #FFFFFF;
background-color: #8229A5;
border-color: #000000;
}

.btn-default:hover {
background-color: #63207E;
}
                    

Voting Containers

For voting apps, the default gray boxes that contain the item name and number of votes can be styled.

Example: Changes to name area to light blue and the voting area to green

.photopoll-view {
background-color: lightblue;
}

.photopoll-vote {
background-color: green;
}
                    

Javascript Events

Campaigns fire custom javascript events at certain points during fan interaction, use jQuery to listen in on those events.

Events:
tbits.load

Triggers when the entry forms or options are loaded.


tbits.selectOption

Triggers when the fan selects an option.


tbits.submit

Triggers when the fan submits their entry form.


tbits.submitSuccess

Triggers when the ajax call to submit the form succeeds.

Example: Listen in on when the fan selects an option or submits their form


$(document).on('tbits.selectoOption', function(){
    alert('User selected an option')
});

                
Please contact us and we'll be happy to help you to customize your Social Apps.

Authentication

Easily integrate authentication and analytics into your website with the Tradable Bits Social Login Widget. Discover, track and communicate with your true fans without needing to write your own code from scratch.

You can get social authentication on your website using either our Javascript Login Widget or through our OAuth Provider

Javascript SDK Widget

Simply embed an authentication button without requiring a server or any additional code. Users will see a clean popup with various login options to choose from. Deploy our library and call initSession function to receive user session IDs (information about the session and the user) - and we'll handle the rest. Upon completion, a valid sesionUid will be returned as a result which can be used to identify the user.


Social Login Widget


<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.0.min.js" ></script>
<script type="text/javascript" src="https://tradablebits.com/tbits-sdk.js" ></script>
<script type="text/javascript" >
function sessionInfo(session){
console.log(session);
}

function callback(sessionUid){
if(sessionUid){
getSession(sessionUid,sessionInfo);
}
}

$(".login-btn").on('click',function(){ initSession(12345,callback); });
</script>
<a class="login-btn";> Login </a>
            

OAuth Endpoint

Provide an endpoint on your side that can accept the redirect from our authentication server and retrieve the session information via the backend call to API. This option is great for clients who have their own server and want more control over their user data storage.

We support OAUTH 1.0 authentication endpoint.

Redirect Example


<a href="https://tradablebits.com/crm/oauth?account_id=1234&redirect_url=http://test.com/callback">
Login
</a>
            
  • account_id Tradable Bits Account ID. This argument is mandatory.
  • login_type Selected network to login
  • redirect_url Redirect URL to send user to upon successful authentication.This argument is mandatory.

Callback Handler Example (Python/Django)


function callback(request):
    code = request.POST.get('code')
    api_key = "12345"
    account_id = "12345"
    redirect_url = "http://test.com/callback"
    parms = {"code":code,"api_key":api_key,"account_id":account_id,"redirect_url":redirect_url}
    token_url = "https://tradablebits.com/crm/access_token?%s" % urllib.urlencode(parms)
    with contextlib.closing(urllib2.urlopen(token_url, timeout=10)) as r:
        res = r.read()
        session = json.loads(res)
...
  • account_id Tradable Bits Account ID.
  • redirect_url Redirect URL to send user to upon successful authentication.
  • api_key Secret Key as configured on the manage centre page.
  • code Url request will include "code" query argument which can be used to retrieve session object.

Password Reset

When your clients forget their passwords, we've got you covered. Our system will send out a standard email that will allow them to resolve the issue. However, you may want to override our default "Reset Password" email and widget with your own branding or user flow. Here's how:

  • Find the user's email and look them up via the CRM API.
  • For fan update endpoint set the reset_uid to true. Upon success, the call will return unique GUID as part of the fan structure.
  • Generate an email that links to OAUTH endpoint with additional parameters: email and reset_uid.
  • Widget will open reset form and guide the user through the process.

<a href="https://tradablebits.com/crm/oauth?account_id=1234&email=test@test.com&reset_uid=5a4d7c07-cbf6-4aed-b1ea-a6ff609d561a&redirect_url=http://test.com/callback">
Reset Password
</a>
            

Tableau Integration

Whether dealing with millions of posts or thousands of fan profiles, the wealth of data you collect on our platform can feel overwhelming. Although we provide extensive analytics on our platform, our integration with Tableau can make in-depth reporting, visualizing and sharing your data much easier. All it takes is simply sending Tradable Bits data through Tableau's desktop Web Data Connector interface. If you don't yet have a Tableau account, please contact us for more information about how to access this powerful tool.

The steps for integrating Tradable Bits into Tableau are as follows:

  1. Generate API Keys in Profile Settings
  2. You need to be logged in into Tradable Bits in order to see API Keys
  3. Choose Corresponding endpoint:
  4. Stream

    CRM

    Campaigns

    Ticket Data
  5. Add the source into Tableau Desktop and new web data connector

Tradable Bits Documentation

Here you will find reference documentation for our developer tools.

Guarantee constant fresh content with Stream, campaigns and comments. Combine your enterprise data and Fan CRM via RESTful API for cohesive organization of your fans, interactions and CRM. Integrate you Tradable Bits data into other reporting systems like Tableau and more!

SDK

Build your own visual for Stream or integrate social login.

Authentication

Add social authentication into your website with our Auth API.

RESTful API

Get data on the backend or build your own integration from your app.

Custom CSS

Override classes and components for a fully branded look.

Analytics

Integrate your Tradable Bits data with reporting programs like Tableau.

Need help?

Questions about integrating? Contact our support team.