Developers

Our platform was built to be flexible and intuitive for developers like you. You own all the data you collect with Tradable Bits. Our API and SDK are designed to make it easy to access your fan data, tickets and campaigns at any time, on your terms. Customize the front end of any of your campaigns with the help of our documentation, complete with examples. Our RESTful API helps you access, send or receive fan data from our system to your endpoints quickly and securely. Enrich your Fan CRM and Tickets Analytics with data from other CRM systems through our many integrations. Have any questions about our developers platform? Our support team is happy to help.

Javascript SDK (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.

Download: tbits-sdk.js

Or link via script tag:

<script type="text/javascript" src="https://tradablebits.com/tbits-sdk.js"></script>

Initialization

TBITS.init(apiKey)

Initialize the TBITS SDK. Required for most other TBITS methods.

Parameters

  • apiKey String

Streams

new TBITS.Stream(streamKey)

Stream object constructor. The stream object contains all the calls relevant to the stream key.

Parameters

  • streamKey String
Show Example

Stream SDK example

Simple fetch for all records in the Stream "mystream"

<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="https://static.tradablebits.com/static/js/libs/moment.min.js"></script>
<script type="text/javascript" src="https://static.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 TBITS.Stream usage.
    // Note: jQuery, moment.js, and underscore.js are optional.
    // Code below is provided for reference only.

    let stream;
    $(document).ready(function() {
        // Create an instance of the Stream object, passing it a stream key.
        stream = new TBITS.Stream('mystream');

        // Pull the records. This returns a Promise (like all Stream methods), so use then() and catch() for processing.
        // Check the reference for additional options.
        stream.getRecords({ is_graphic: true })
            .then(recordsCallback)
            .catch(err => {
                console.error(err);
            });
    });

    function recordsCallback(res) {
        console.log(res.meta);
        let recTemplate = $("#record-template").html();
        let $results = $("#results");
        for (let record of res.data) {
            // Render the results. Modify to match your site.
            $results.append(_.template(recTemplate)(record));
        }
    }

    // Click Handler to track caption link clicks
    $('body').on('click', '.item-caption a', () => {
        let feedRecordId = this.parentNode.dataset.feedRecordId;
        stream.trackClick(feedRecordId);
    });
</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 stream.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="stream.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="reply"></span></a>
                        <a class="item-links" href="https://twitter.com/intent/retweet?tweet_id=<%= record_key %>">
                        <span class="retweet"></span></a>
                        <a class="item-links" href="https://twitter.com/intent/favorite?tweet_id=<%= record_key %>">
                        <span class="star"></span></a>
                    </div>
                </div>
            <% } %>
        </div>
        <div class="item-caption" data-feed-record-id="<%=feed_record_id%>">
            <%= TBITS.Stream.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>

stream.getRecords(options)

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

Parameters

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

Returns

Object
  • meta Object
  • data [Object] - records that match the given options

stream.nextPage()

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

Returns

Object
  • meta Object
  • data [Object] - records that match the given options

stream.prevPage()

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

Returns

Object
  • meta Object
  • data [Object] - records that match the given options

stream.summary(options)

Return a summary view of the Stream.

Parameters

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

Returns

Object
  • approved_total
  • stream_name
  • stream_key
  • total
  • last_record_timestamp
Show Example

Stream Summary Example

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

<script type="text/javascript" src="https://tradablebits.com/tbits-sdk.js"></script>
<script type="text/javascript">
    // Example of TBITS.Stream usage.
    // Code below is provided for reference only.

    let stream;
    $(document).ready(function() {
        stream = new TBITS.Stream('mystream');
        stream.summary({data:"labels,words"}) // See reference for other available options.
            .then(summaryCallback)
            .catch(err => {
                console.error(err);
            });
    });

    function summaryCallback(res){
        console.log('words', res.words);
        console.log('labels', res.labels);
        console.log(res.total + " total records");
    }
</script>
                        

stream.cube(options)

Return a breakdown by given dimensions for analytics purposes.

Parameters

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

Returns

Object
  • data [Object]
  • meta Object

stream.getRecord(feedRecordId)

Return a single record given then ID

Parameters

  • feedRecordId Number - ID of record to get.

Returns

Object

stream.authors(limit)

Get author records from the Stream. Display a Meta Facepile with this call.

Parameters

  • limit Number - max number of authors (max 50)

Returns

[Object]
  • author_id Number
  • network String - e.g. 'facebook'
  • user_key String
  • name String
  • image_url String

stream.topAuthors(options)

Get Top Authors in the stream according to label

Parameters

  • limit Number
  • sort_order String - 'reach' or 'vote_count'
  • label String

Returns:

[Object]
  • author_id Number
  • network String
  • user_key String
  • name String
  • image_url String
  • reach_count Number
  • posts Number

stream.reportBrokenRecord(feedRecordId)

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 reportBrokenRecord() on an "onerror" event for the image.

Parameters

  • feedRecordId Number - ID of record to report.

Returns

Boolean

stream.reportRecord(feedRecordId)

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.

Parameters

  • feedRecordId Number - ID of record to report.

Returns

Boolean

stream.createRecord(caption, recordMediaUid, options)

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_media call previously. See the examples below for more details.

Authenticated

When you call TBITS.getSession() 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_media" 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.

Parameters

  • caption String
  • recordMediaUid String - uid of media uploaded to upload_image endpoint
  • options Object - include name, email, etc here.

Returns

Number - the created record ID.

stream.trackClick(feedRecordId)

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 trackClick() on "onclick" events for a link.

Parameters

    feedRecordId Number

Returns

Boolean

TBITS.Stream.convertLinks(caption, network, props)

Utility function to identify and convert links in the caption

Campaigns (Apps)

Requires TBITS.init()

new TBITS.Campaign(apiKey, pageTabId)

Initialize the Campaign object using public API KEY and page tab id.

Note: You must also call init() to fetch the required details.

Parameters

  • apiKey String - Public API Key
  • pageTabId Number - the id of the campaign to work with

campaign.init()

Additional step required to initialize the Campaign object. Sets the internal structure of the campaign object in order for other methods to work.

Returns

Object
  • fields [Object] - a list of custom field objects
  • media [Object] - 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)

campaign.getFanDetails()

Returns

Object
  • fan_id Number
  • first_name String
  • last_name String
  • email String

campaign.saveFanDetails(data)

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

Parameters

  • first_name String
  • last_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

Object
  • fan_id Number
  • first_name String
  • last_name String
  • email String

campaign.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.

Returns

Boolean

campaign.trackShare(shareNetwork)

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. See fanAuth()

Parameters

  • shareNetwork String - e.g. 'facebook'

Returns

Boolean


<script async defer src="https://connect.facebook.net/en_US/sdk.js"></script>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.0.min.js" ></script>
<script type="text/javascript" src="https://static.tradablebits.com/static/js/libs/underscore.js"></script>
<script type="text/javascript" src="https://tradablebits.com/tbits-sdk.js" ></script>
<script type="text/javascript" >
    //An example usage of the APPS methods to collect and save fan input with and
    //without Facebook authentication
    let apiKey = "b9a18588-dfd3-4a20-94ef-16c70d571be4";
    let pageTabId = 11;
    let campaign;

    $(document).ready(function () {
        // Create the campaign object
        campaign = new TBITS.Campaign(apiKey, pageTabId);
        // Call init to finish setting up the campaign object. This returns a Promise.
        campaign.init()
            .then(initCallback)
            .catch(err => console.error(err));
    });

    function initCallback(campaignData){
        console.log(campaignData);
        let templateData = { fields: campaignData.crm_fields };
        let templateHtml = $("#fields_template").html();
        $("#custom-fields").after(_.template(templateHtml)(templateData));
    }

    function getUserInput(){
        let 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 noAuthSubmit(){
        let data = getUserInput();
        campaign.saveFanDetails(data).then(fanDetails => {
            saveCallback(fanDetails);
            campaign.fanLogout();
        });
    }

    function saveCallback(fanDetails) {
        console.log("Fan saved.", fanDetails);
    }

</script>

<script type="text/template" id="fields_template">
    <% for (let field of fields) { %>
        <div class="form-group">
            <label for="<%-field.crm_field_key%>"><%-field.title%></label>
            <input type="text" name="<%-field.crm_field_key%>" class="form-control custom-field">
        </div>
    <% } %>
</script>

<div class='container'>
    <div class='form'>
        <h2> Core Fields </h2>
        <div class="form-group">
            <label for="first_name">First Name</label>
            <input class="form-control core" type="text" name="first_name">
        </div>
        <div class="form-group">
            <label for="last_name">Last Name</label>
            <input class="form-control core" type="text" name="last_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>
    </div>
</div>
                

Counters

Requires TBITS.init()

TBITS.getCounter(counterName)

Obtain the value of the counter

Parameters

  • counterName String

Returns

Number - The counter value

TBITS.updateCounter(counterName)

Increment the value of the counter by 1

Parameters

  • counterName String

Returns

Number - The updated counter value

TBITS.checkCounter(counterName)

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

Parameters

  • counterName String

Returns

Object
  • voted Boolean
  • counter Number - The counter value

Counter Example

Simple fetch for all records in the Stream "mystream"

<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: jQuery is optional.
    // 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')
            .then(callback)
            .catch(err => {
                // optionally handle errors
                console.log(err);
            });
    });
    function upVote(){
        TBITS.updateCounter('testCounter')
            .then(callback)
            .catch(err => {
                console.log(err);
            });
    }
</script>
<div id="counter"></div>
<a href="javascript:upVote()"> Vote </a>
                

Props

Requires TBITS.init()

TBITS.getProps(counterName)

Get custom meta data associated with specific property


TBITS.updateProps(counterName, props)

Update meta data associated with property


Idols

Requires a fan session from TBITS.initSession() and TBITS.getSession()
TBITS.getIdols()

Get the idols for the fan given the current session

Returns

[Object]

insertFanIdol(idolName)

Create idol-fan record for given idol name

Returns

[Object]

TBITS.removeFanIdol(idolName)

Remove idol-fan record for given idol name

Returns

[Object]


<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.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: jQuery is optional.
    // Code below is provided for reference only
    // Code implies previous use of TBITS.initSession(1) and this page is redirect back after authentication

    $(document).ready(function() {
        // Initialize TBITS with public API key.
        TBITS.init('[apiKey]');
        // Initialize session with Tradable Bits account id
        let accountId = 1;
        let code = location.hash.substr(1);
        let callbackUrl = location.href;
        TBITS.getSession(1,code,callbackUrl).then(res => {
            console.log("Session Initialized, Session: ", res);
        });
    });

    function getIdols() {
        TBITS.getIdols()
            .then(idolCallback)
            .catch(err => console.error(err));
    }

    function insertJohnDoe() {
        TBITS.insertFanIdol('John Doe')
            .then(idolCallback)
            .catch(err => console.error(err));
    }

    function removeJohnDoe() {
        TBITS.removeFanIdol('John Doe')
            .then(idolCallback)
            .catch(err => console.error(err));
    }

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

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

Authentication

TBITS.initSession(accountId, loginType)

This call will redirect the browser to authentication page. loginType can be left blank, at which point email authentication will be used. Upon successful authentication, we will redirect back to callback url as per CRM configuration. Resulting redirect will have a hashcode, which can be replaced for sessionUid via getSession call.

Arguments

  • accountId - Tradable Bits Account ID. The account must have a valid subscription.
  • loginType - Suggested login type: e.g. facebook, X, etc.

TBITS.closeSession()

Clears the session state locally on the browser side.

Returns

Boolean

TBITS.getSession(accountId, code, redirectUrl)

Upon successful authentication, we will redirect back to preconfigured redirect page. Hashcode will contain temporary code, which can be exchanged for session_uid via this call.

Returns

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

TBITS.optInFan(options)

Parameters

options Object
  • first_name String
  • last_name String
  • email String
  • is_subscribed Boolean
  • phone String
  • display_name String
  • postal_code String
  • country_code String
  • city String
  • province String
  • field_* String - custom field values, e.g. field_favourite_colour
  • campaign_name String
  • tag_name String
  • device_id String
  • device_network String
  • is_unique_activity Boolean
  • ip_address String

Returns

Object
  • fan_id - identifier for the user record