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)

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="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%>">
                <%= 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-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: 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-3.3.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 (tbits-sdk.js)

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 (embedded.js)

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.


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