NAV Navbar
JavaScript cURL JSON XML PHP
  • Introduction
  • JavaScript API
  • Integration API
  • Provisioning API
  • Visitor Chat API
  • Logs API
  • Glossary
  • Introduction

    Snapengage Logo

    JavaScript API

    The JavaScript API offers many different methods which you can use to customize the live chat look and functionality for your visitors. These methods may be used inside the SnapEngage code snippet where it says /* Place your SnapEngage JS API code below */ which will cause the API method to run after the SnapEngage code is fully loaded. In some cases, some API methods may be used as an event handler on an element on the page. For example, you can set a link's onclick attribute to SnapEngage.startLink() which will open up the chat if someone clicks that link.

    Authentication for JavaScript API

    An authentication key is not needed to use the Javascript API.

    Just be sure to place your function calls inside your SnapEngage code snippet where it says "Place your SnapEngage JS API code below"

    API Placement and Availability

    Since the SnapEngage code snippet loads asynchronously, there are certain limitations on when you can use, and/or have access to our Javascript API.

    Unlike a non-asynchronous include, you cannot be sure that the SnapEngage functions will be available when the document is otherwise ready.

    Use our API inside the SnapEngage JavaScript Code Snippet

    <!-- begin SnapEngage code -->
    <script type="text/javascript">
      (function() {
        var se = document.createElement('script'); se.type = 'text/javascript'; se.async = true;
        se.src = '//storage.googleapis.com/code.snapengage.com/js/...';
        var done = false;
        se.onload = se.onreadystatechange = function() {
          if (!done&&(!this.readyState||this.readyState==='loaded'||this.readyState==='complete')) {
            done = true;
            /* Place your SnapEngage JS API code below */
            /* Example JS API: Enable sounds for Visitors. */
            var allow = true;
            SnapEngage.allowChatSound(allow);
          }
        };
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(se, s);
      })();
    </script>
    <!-- end SnapEngage code -->
    

    This code snippet has a built in safety net, so to speak, for our Javascript API availability. As long as you place all of your custom Javascript API inside this code block, you can be sure that SnapEngage functions will be available. Be sure to place your function calls after the comment /* Place your SnapEngage JS API code below */.

    We recommend that you call API exclusively inside this block. But if you insist on going all cowboy on us...

    Using it elsewhere can be tricky

    Our chat code is well optimized and loads quickly, but we also defer to your local page first (by design). So if you have a hang or a snag or even just a slow-loading image on your page, it might mean a slight additional delay to the SnapEngage code’s availability.

    So what are you to do if you want, say, a hard-coded link on your page that fires onclick="SnapEngage.startLink();" but you want to make sure that function exists before a Visitor clicks it?

    One option would be hiding the element until SnapEngage finishes loading, then reveal the element. This is relatively painless to achieve with jQuery or something like it, and only slightly less painless with vanilla Javascript.

    JavaScript Events

    At some point, you may need to hook your custom code into JavaScript events, or you may want to instruct Google Analytics to track certain events. In this article you will find all of SnapEngage's JavaScript Events, and a few example uses.

    Close Event

    SnapEngage.setCallback('Close', function (type, status) {
        console.log('type: ' + type);
        console.log('status: ' + status);
    });
    

    The Close event is fired when a close button is clicked.

    This callback can return two pieces of info: type of window that was closed, and widget status when the close event was fired.

    Parameter values

    Parameter Type Description
    Anonymous Function Function This callback function accepts two optional parameters: type and status. Inside the anonymous function, you can check the returned value of the type and status parameters.
    type String The type of window that was closed (see table of values below).
    status String The widget status when the close event was fired (see table of values below).

    Return values of type parameter

    SnapEngage.setCallback('Close', function (type, status) {
        console.log('A visitor just closed the ' + type + ' window.');
    });
    
    // The callback above returns this
    // when the visitor closes a chat window
    'A visitor just closed the chat window.'
    
    Type Value Description
    String 'form' The visitor closed a prechat or offline form.
    String 'chat' The visitor closed a chat window.
    String 'proactive' The visitor closed a proactive chat window.

    Return values of status parameter

    SnapEngage.setCallback('Close', function (type, status) {
        console.log('A visitor closed a ' + type +
         ' and the widget is ' + status + '.');
    })
    
    // The callback above returns this
    // when the visitor closes a form
    'A visitor closed a form and the widget is offline.'
    
    Type Value Description
    String 'online' The visitor closed a window when the widget was online.
    String 'offline' The visitor closed a window when the widget
    was offline.

    ChatMessageReceived Event

    SnapEngage.setCallback('ChatMessageReceived', function (agent, msg) {
        console.log('agent: ' + agent);
        console.log('msg: ' + msg);
    });
    

    The ChatMessageReceived event is fired when a message from the agent is received by the visitor.

    This callback can return two pieces of info: name of the agent that sent the message, and the msg that was sent.

    Parameter values

    Parameter Type Description
    Anonymous Function Function This callback function accepts two optional parameters: agent and message. Inside the anonymous function, you can check the returned value of the agent and message parameters.
    agent String The agent alias.
    msg String The message that was received by the visitor.

    Return values

    SnapEngage.setCallback('ChatMessageReceived', function (agent, msg) {
        console.log('A visitor received a chat message from ' + agent);
        console.log('And the msg was: ' + msg);
    });
    
    // The callback above returns this
    // when the visitor receives a chat message
    'A visitor received a chat message from Samantha';
    'And the msg was: hello ';
    

    Example return values of agent and msg are inside the code example.

    ChatMessageSent Event

    SnapEngage.setCallback('ChatMessageSent', function (msg) {
        console.log('msg: ' + msg);
    });
    

    The ChatMessageSent event is fired when the visitor submits a chat message while in the chat session.

    This callback can return one piece of info: the msg that was sent by the visitor.

    Parameter values

    Parameter Type Description
    Anonymous Function Function This callback function accepts one optional parameter: msg. Inside the anonymous function, you can check the returned value of the msg parameter.
    msg String The message that was sent by the visitor.

    Return values

    SnapEngage.setCallback('ChatMessageSent', function (msg) {
        console.log('A visitor sent this chat message: ' + msg);
    });
    
    // The callback above returns this
    // when a visitor sends a chat message
    'A visitor sent this chat message: What does SnapEngage integrate with?';
    

    An example return value of msg is inside the code example.

    MessageSubmit Event

    SnapEngage.setCallback('MessageSubmit', function (email, msg) {
        console.log('email: ' + email);
        console.log('msg: ' + msg);
    });
    

    The MessageSubmit event is fired when the visitor submits an offline message (not a chat message).

    This callback can return two pieces of info: the visitor's email, and the msg that was sent.

    Parameter values

    Parameter Type Description
    Anonymous Function Function This callback function accepts two optional parameters: email and msg. Inside the anonymous function, you can check the returned value of the email and msg parameters.
    email String The visitor's email address.
    msg String The message.

    Return values

    SnapEngage.setCallback('MessageSubmit', function (email, msg) {
        console.log(email + ' just submitted an offline message.');
        console.log('The message was: ' + msg);
    });
    
    // The callback above returns this
    // when an offline message is submitted
    'sam@test.com just submitted an offline message.'
    'The message was: hello!';
    

    Example return values of email and msg are inside the code example.

    Minimize Event

    NOTE: This API is only available for Design Studio widgets. Please consider upgrading to get the most current functionality.

    SnapEngage.setCallback('Minimize', function(isMinimized, chatType, boxType) {
        // Handle results.
        console.log('Chatbox is' + (isMinimized ? '' : ' not') + ' minimized');
        console.log('Chat Type is: ' + chatType);
        console.log('Chat Box is: ' + boxType);
    });
    

    The Minimize event is triggered when the visitor clicks the minimize icon in the chat box, or during live and active chats when they click on the minimized 'button' to maximize the chat box.

    Parameter values

    Parameter Type Description
    Anonymous Function Function This callback function accepts three optional parameters: isMinimized, chatType and boxType. Inside the anonymous function, you can handle the returned values of isMinimized, chatType and boxType arguments.
    isMinimized Boolean The state of the chat box AFTER the visitor has clicked.
    chatType String The type of chat the visitor is using.
    boxType String The type of the chat box the visitor sees.

    Return values of isMinimized parameter

    SnapEngage.setCallback('Minimize', function(isMinimized, chatType, boxType) {
        // Handle results.
        console.log('Chatbox is' + (isMinimized ? '' : ' not') + ' minimized');
        console.log('Chat Type is: ' + chatType);
        console.log('Chat Box is: ' + boxType);
    });
    
    // The callback above returns this
    // when a visitor has minimized a manual live chat:
    'Chatbox is minimized'
    'Chat Type is manual'
    'Chat Box is chatManual'
    
    Type Value Description
    Boolean true The chat box is minimized.
    Boolean false The chat box is not minimized (maximized).

    Return values of chatType parameter

    Type Value Description
    String 'manual' The visitor started a manual chat.
    String 'proactive' The visitor started a proactive chat.

    Return values of boxType parameter

    Type Value Description
    String 'chatManual' The box is an ongoing live chat box initiated by the vistitor.
    String 'intelliPrechat' The box is a Intelligent Prechat form
    String 'offline' The box is an Offline form
    String 'prechat' The box is a Prechat form
    String 'proactive' The box is an ongoing live chat box initiated by the proactive rules.
    String 'proactiveInvite' The box is displaying the proactive invite, awaiting response by the visitor

    Open Event

    SnapEngage.setCallback('Open', function (status) {
        console.log('status: ' + status);
    });
    

    The Open event is fired when the chat form is opened. The form may be opened by the user directly (button click), or as the result of an API call.

    This callback can return one piece of info: the widget status when the event was fired.

    Parameter values

    Parameter Type Description
    Anonymous Function Function This callback function accepts an optional parameter: status. Inside the anonymous function, you can check the returned value of the status parameters.
    status String The widget status at the time the event was fired.

    Return values of status parameter

    SnapEngage.setCallback('Open', function (status) {
        console.log('A form just opened and the widget status is: ' + status);
    });
    
    // The callback above returns this
    // when a form is opened and the widget is offline
    'A form just opened and the widget status is: offline'
    
    Type Value Description
    String 'online' The widget is online.
    String 'offline' The widget is offline.

    OpenProactive Event

    SnapEngage.setCallback('OpenProactive', function (agent, msg) {
        console.log('agent: ' + agent);
        console.log('msg: ' + msg);
    });
    

    The OpenProactive event is fired when the proactive chat is displayed to a visitor. (Note, when the visitor replies, the StartChat event fires.)

    This callback can return two pieces of info: the name of the agent used in the proactive message, and the proactive msg itself.

    Parameter values

    Parameter Type Description
    Anonymous Function Function This callback function accepts two optional parameters: agent and msg. Inside the anonymous function, you can check the returned value of the agent and msg parameters.
    agent String The agent alias.
    msg String The proactive prompt message.

    Return values

    SnapEngage.setCallback('OpenProactive', function (agent, msg) {
        console.log('A proactive message just popped up. The agent shown is ' +
         agent + '.');
        console.log('The proactive message used is: ' + msg);
    });
    
    // The callback above returns this
    // when a proactive prompt opens
    'A proactive message just popped up. The agent shown is Samantha.';
    'The proactive message used is: You know nothing, Jon Snow.';
    

    Example return values of agent and msg are inside the code example.

    StartChat Event

    SnapEngage.setCallback('StartChat', function (email, msg, type) {
        console.log('email: ' + email);
        console.log('msg: ' + msg);
        console.log('type: ' + type);
    });
    

    The StartChat event is fired when the visitor starts a chat, or responds to a proactive invitation.

    This callback can return three pieces of info: the visitor's email, the visitor's first msg, and the type of chat (manual or proactive).

    Parameter values

    Parameter Type Description
    Anonymous Function Function This callback function accepts three optional parameters: email, msg, and type. Inside the anonymous function, you can check the returned value of the email, msg, and type parameters.
    email String The visitor's email address.
    msg String The visitor's first message.
    type String The type of chat.

    Return values

    SnapEngage.setCallback('StartChat', function (email, msg, type) {
        console.log(email + ' just started a ' + type + ' chat.');
        console.log('The message was: ' + msg);
    
    });
    
    // The callback above returns this
    // when the visitor starts a manual chat
    'sam@test.com just started a manual chat.';
    'The message was: The King in the North!';
    

    Example return values of email, msg, and type are inside the code example.

    Return values of type parameter

    Type Value Description
    String 'manual' The visitor started a manual chat.
    String 'proactive' The visitor started a proactive chat.

    StartCallme Event

    SnapEngage.setCallback('StartCallme', function (phone) {
        console.log('phone: ' + phone);
    });
    

    The StartCallMe event is fired when the visitor starts a call-me.

    This callback can return one piece of info: the visitor's phone number.

    Parameter values

    Parameter Type Description
    Anonymous Function Function This callback function accepts one optional parameter: phone. Inside the anonymous function, you can check the returned value of the phone parameters.
    phone String The visitor's phone number.

    Return values

    SnapEngage.setCallback('StartCallMe', function (phone) {
        console.log('A visitor just started a callme request.');
        console.log('Their phone number is ' + phone);
    });
    
    // The callback above returns this
    // when the visitor starts a callme request
    'A visitor just started a callme request.'
    'Their phone number is 555-1234';
    

    Example return values of phone are inside the code example.

    SwitchWidget Event

    NOTE: This API is only available for Design Studio widgets. Please consider upgrading to get the most current functionality.

    SnapEngage.setCallback('SwitchWidget', function(newWidgetId) {
        // Handle results.
        console.log('I just switched to widget ID: ' + newWidgetId);
    });
    

    You must have the widget selector enabled in your Design Studio prechat &/or offline form to utilize this event callback functionality. The switchWidget event is triggered when the visitor has selected a value from the available dropdown list options. It will return the value of the newWidgetId.

    Parameter values

    Parameter Type Description
    Anonymous Function Function This callback function accepts one optional parameter: newWidgetId. Inside the anonymous function, you can handle the returned value of the newWidgetId argument.
    newWidgetId String The widgetId of the selected option.

    Return values of newWidgetId parameter

    SnapEngage.setCallback('SwitchWidget', function(newWidgetId) {
        // Handle results.
        console.log('I just switched to widget ID: ' + newWidgetId);
    });
    
    // The callback above returns this
    // when a visitor has selected an option:
    'I just switched to widget ID: 123-abc'
    
    Type Value Description
    String varies This value will vary and will match a widgetID within your organization. Examples of newWidgetId are inside the sample code.

    API Methods

    .allowChatSound()

    var allow = true;
    SnapEngage.allowChatSound(allow);
    

    Enable or disable all sounds produced by SnapEngage for chat visitors.

    Parameters

    Parameter Type Description
    allow boolean If set to true, chat sounds will play for the visitor e.g. when the a message is received. If set to false, chat sounds will not play.

    .allowPageChangeNotification()

    var allow = true;
    SnapEngage.allowPageChangeNotification(allow);
    

    Deprecated. We are not supporting this API at present. Instead, please use this setting inside your Admin Dashboard as described here.

    Should the Chat notify the agent when the visitor navigates to a new page? The notification will include a url to the page in question.

    Parameters

    Parameter Type Description
    allow boolean If set to true, your agent will be notified of page changes. This feature is enabled by default, but can be turned off by calling this method with the value false.

    .allowProactiveChat()

    var allow = true;
    SnapEngage.allowProactiveChat(allow);
    

    Should proactive chat invitations be allowed to fire? You can use this to disable (or re-enable) proactive chat wherever it might be necessary.

    This option can also be easily configured in the Admin Dashboard. The API call exists primarily for special circumstances, where you want to enable or disable use of proactive chat on specific pages.

    Parameters

    Parameter Type Description
    allow boolean If set to true, proactive chat invitations are enabled. If set to false, there will be no proactive chat invitations.

    .allowScreenshot()

    var allow = true;
    SnapEngage.allowScreenshot(allow);
    

    Deprecated. We are not supporting the screenshot option at present.

    Should the Pre-Chat and Offline forms include the Screenshot option? (The screenshot lets visitors send a screenshot of the current page to the agent.)

    Parameters

    Parameter Type Description
    allow boolean If set to true, legacy prechat and offline forms will include an option for visitors to send a screenshot. If set to false, the forms will not include the screenshot option.

    .clearAllCookies()

    SnapEngage.clearAllCookies();
    

    Clear and delete all cookies set by SnapEngage for the current visitor.

    No Parameters

    .disableLightbox()

    SnapEngage.disableLighbox();
    

    Disable the "Lightbox" effect for the prechat form. That is: the greyed-out background when the prechat form comes up.

    No Parameters

    .getAgentStatusAsync()

    SnapEngage.getAgentStatusAsync(function (online) {
        if (online) {
            console.log('chat is online/available');
        } else {
            console.log('chat is offline');
        }
    });
    

    Check whether or not you have agents online and your live chat is available.

    Parameters

    Parameter Type Description
    Anonymous Function Function This callback function uses a required parameter "online" which is a boolean. Inside the function, you can check the value of the "online" parameter, which will evaluate to true if agents are online and chat is available, or false if no agents are online and/or chat is not available.

    Common reasons for chat being unavailable include: All agents are paused, or it is outside of the widget's configured "Hours of Operation".

    Example getAgentStatusAsync() Usage

    Hide the chat button if chat is unavailable
    SnapEngage.getAgentStatusAsync(function (online) {
        if (!online) {
            SnapEngage.hideButton();
        }
    });
    

    Hide the SnapEngage button when your agents are offline/unavailable.

    Hide a custom inline button if chat is unavailable
    // Using Javascript
    SnapEngage.getAgentStatusAsync(function (online) {
        if (!online) {
            document.getElementById('myInlineButtonId').style.display = 'none';
        }
    });
    
    // Using jQuery
    SnapEngage.getAgentStatusAsync(function (online) {
        if (!online) {
            $('#myInlineButtonId').hide();
        }
    });
    

    If you have a custom button image that you've embedded into your site, you may want to show or hide it if the widget is online or offline. This is how you would do that.

    Check agent status every three minutes
    var threeMinutes = 3 * 60 * 1000;
    var tid = setTimeout(checkChatStatus, threeMinutes);
    
    // Check the widget status every three minutes
    function checkAgentStatus() {
        SnapEngage.getAgentStatusAsync(function(online) {
            if (online) {
                SnapEngage.showButton();
            } else {
                SnapEngage.hideButton();
            }
        });
    
        // Recursive call
        clearTimeout(tid);
    
        // Set another three minute time out
        tid = setTimeout(checkAgentStatus, threeMinutes);
    }
    

    As you may have guessed, you can call .getAgentStatusAsync() asynchronously.

    .getWidgetId()

    SnapEngage.getWidgetId();
    

    Sometimes it will be helpful to know the ID of the currently-active widget, especially if you use .setWidgetId() to change the active widget on the fly.

    No Parameters

    Returns

    // An example widget ID is returned from the call above
    '1z1z1z1z1-y2y2-x3x3-w4w4-v5v5v5v5v5v'
    
    Type Description
    String Returns a String that is the full widget ID of the currently active widget. (Alphanumeric plus dashes.)

    An example return value of is inside the code example.

    Example getWidgetId() Usage

    Send a system message to the agent based on the widget ID
    SnapEngage.setCallback('StartChat', function(email, msg, type) {
        var success = false;
        var tid;
    
        function sendWidgetName() {
            var currWidget = SnapEngage.getWidgetId();
    
            // For each different widget ID, send a message to the agent with that widget's name
            switch (currWidget) {
                case 'xxxxx-xxxx-xxxx-xxxx' :
                    success = SnapEngage.sendTextToChat('A Widget\'s Name');
                    break;
                case 'yyyyyy-yyyy-yyyy-yyyyy' :
                    success = SnapEngage.sendTextToChat('Other Widget\'s Name');
                    break;
                default :
                    success = SnapEngage.sendTextToChat('Error fetching Widget Name');
                    break;
            }
        }
    
        // Call the function above
        sendWidgetName();
    
        if (!success) {
            clearTimeout(tid);
    
            // Try again every two seconds until success.
            tid = setTimeout(sendWidgetName, 2000);
        }
    });
    

    Send a message to the agent that changes for each different widget ID. This code sample uses getWidgetId() along with the StartChat JavaScript event and sendTextToChat().

    .hideButton()

    SnapEngage.hideButton();
    

    Immediately hide the floating online/offline button.

    No Parameters

    .openProactiveChat()

    // Do not open proactive chat if the user has recently
    // closed a proactive invite
    var forced = false;
    
    // Do not open the offline box if the widget is not online
    var offlineFallback = false;
    
    // Do not open the offline box if the widget is not online
    var message = 'Hey there! How can I help you today?';
    
    // Call the API with the above parameters
    SnapEngage.openProactiveChat(forced, offlineFallback, message);
    

    Manually open a proactive message.

    Parameters

    Parameter Type Description
    forced boolean Should SnapEngage disregard whether or not the visitor has recently closed a chat window? (See here for more info on The 30-minute Proactive Chat Delay Cookie.) And should SnapEngage disregard whether or not you have "Enable Proactive Chat" checked in your Admin Dashboard Proactive Settings tab? For example, if you're hooking this function to the onclick event of an tag, you'll want this set to true because you can assume someone clicking a link does want to chat.
    offlineFallback boolean Should this function fallback to the offline form if live chat is currently unavailable? For example, if you’re hooking this function to the onclick event of an tag, you'll want this set to true because you can assume someone clicking a link does want to get in touch with you, and if you’re offline this will give them the option of filling out the offline form. Alternatively: Be careful using true here, a poor implementation of the .openProactiveChat() function with offlineFallback set to true can be very jarring for your visitors!
    message String When calling .openProactiveChat() manually, you must manually set a first-message for the Proactive Chat. This message will appear to come from your agent, and will show up wherever you call this manually. So in most cases, the best option is to define a very generic message such as, "Thanks for visiting. How can I help you?"

    .sendTextToChat()

    // You MUST use sendTextToChat() inside the ChatMessageReceived callback
    // which ensures that there is an active chat before the message is sent.
    SnapEngage.setCallback('ChatMessageReceived', function (agent, msg) {
    
        // Send a message to the agent
        var text = 'Remember to mention the current promotion!';
        SnapEngage.sendTextToChat(text);
    
        // Now clear the ChatMessageReceived callback since you
        // just sent the message. (Otherwise, this callback will
        // send the message every time ChatMessageReceived fires)
        SnapEngage.setCallback('ChatMessageReceived', '');
    
    });
    

    Send a message to the active chat agent without showing it to the visitor. Optionally, add a second parameter of 'visitor' to send this message to the visitor.

    Parameters

    // You MUST use sendTextToChat() inside the ChatMessageReceived callback
    // which ensures that there is an active chat before the message is sent.
    SnapEngage.setCallback('ChatMessageReceived', function (agent, msg) {
    
        // Send a message to the visitor
        var text = 'Thanks for chatting! Here is a 10% off coupon code: TENOFF';
        SnapEngage.sendTextToChat(text, 'visitor');
    
        // Now clear the ChatMessageReceived callback since you
        // just sent the message. (Otherwise, this callback will
        // send the message every time ChatMessageReceived fires)
        SnapEngage.setCallback('ChatMessageReceived', '');
    
    });
    
    Parameter Type Description
    text String The text content of a message to be sent to the currently-active agent. When fired, the message will be sent to the agent but not to the visitor.
    to String Enter this optional parameter if you would like to send a message to the currently-active visitor and not to the agent.

    Parameter values

    to value
    the visitor, not the agent 'visitor'

    Return values

    // if the call above returns 'false', it means
    // there is an active chat and the message was
    // sent to the visitor.
    false
    
    Type Description
    boolean If true, there is an active chat and the message was sent to the agent. If false, there is an active chat and the message was sent to the visitor. Or, there is no active chat.

    .setButtonEffect()

    var negativePixels = '-4px';
    SnapEngage.setButtonEffect(negativePixels);
    

    Deprecated. This API method is not supported in the Design Studio. (If you are a legacy Style tab user, this API is supported).

    Set the non-hover button position for your button. (Direction is set automatically by your button’s position.)

    Parameters

    Parameter Type Description
    negativePixels String If you are a legacy Style tab user using a custom button image, and you would like to hide more of the button when it is not being hovered over, you can use this function to override the default positioning (which is '-4px'). The direction of the positioning is determined by your Admin Dashboard Style tab. (On-hover, the button’s position changes to ‘0px’).

    .setChatFormPosition()

    // Set the legacy chatbox to pop up in the 'tl' (top left)
    // corner of the browser window
    var position = 'tl';
    SnapEngage.setChatFormPosition(position);
    

    Deprecated. This API method is not supported in the Design Studio. Design Studio users may change the position of the chat form by going to Chat Box -> Global Box Settings -> In-page Popup. (If you are a legacy Style tab user, this API is still supported).

    Manually set the position where you would like the chat window to appear. (Will not reposition an already-visible chat box.)

    This option can also be easily set in the legacy Style tab of the Admin Dashboard without the need for an API call. But you can use this function if you need to reposition the chat box in a special circumstance.

    Parameters

    Parameter Type Description
    position String A string representing the desired position of the legacy chat window. Requires specific values that are case-sensitive, see the table below of "Parameter Values".

    Parameter Values

    Position Value
    Bottom Right 'br'
    Bottom Left 'bl'
    Top Right 'tr'
    Top Left 'tl'
    Center 'c'

    .setCustomField()

    var fieldName = 'Company';
    var fieldValue = 'Vandelay Industries';
    
    SnapEngage.setCustomField(fieldName, fieldValue);
    

    Pre-populate any field on your prechat or offline form. (The field is still editable by the visitor.)

    For Design Studio users only. Legacy chat users may instead use the .setDescription(), .setUserEmail(), or .setUserName() API methods to pre-populate their non-custom form fields. Custom form users will be able to pre-populate any custom fields on their forms by simply using JavaScript, for example, document.getElementById("myFavoriteColor").value = "blue".

    Parameters

    Parameter Type Description
    fieldName String The field’s name attribute can be found by inspecting the DOM and looking for the input element’s name attribute. In general the name of a field is the field’s label with no spaces, and case-sensitive. For example, if you have a field with a label 'Favorite Color', the name attribute is 'FavoriteColor'.
    fieldValue String Provide a value for this field. You can hardcode the value, or pass it as a parameter using JavaScript or server-side scripting.

    .setDescription()

    var description = 'Hello! I need help!';
    SnapEngage.setDescription(description);
    

    Pre-populate the 'Description' field on the prechat form. (The description is still editable by the visitor.)

    Parameters

    Parameter Type Description
    description String The message you would like to pre-populate the description field with. The description will still be fully editable by your visitor, but this might make it easier for your agents to know what your visitors are asking after, since many visitors may not bother to enter a problem description or request in the first place.

    .setLocale()

    var languageCode = 'de';
    SnapEngage.setLocale(languageCode);
    

    Allows you to set the visitor chat to use a different language than the one you have set up in your Admin Dashboard. See table of Paramter Values for potential locales.

    Parameters

    Parameter Type Description
    languageCode String Set the locale manually using one of the available languages listed in the table below. Requires specific values that are case-sensitive, see the table below of "Parameter Values".

    Parameter values

    Language Value
    Arabic 'ar'
    Azerbaijini 'az'
    Chinese (Simplified) 'zh'
    Chinese (Traditional) 'zh_TW'
    Czech 'cs'
    Danish 'da'
    Dutch 'nl'
    English 'en'
    Estonian 'et'
    Finnish 'fi'
    French 'fr'
    French (Canadian) 'fr_CA'
    German 'de'
    Hebrew 'rw'
    Hungarian 'hu'
    Icelandic 'is'
    Italian 'it'v
    Japanese 'ja'
    Korean 'ko'
    Latvian 'lv'
    Lithuanian 'lt'
    Norwegian Bokmaal 'nb'
    Norwegian Nynorsk 'nn'
    Polish 'pl'
    Portuguese 'pt'
    Russian 'ru'
    Romanian 'ro'
    Slovak 'sk'
    Spanish 'es'
    Swedish 'sv'
    Turkish 'tr'

    .setNoProactiveChatDelay()

    // Delay the proactive invitation for 10 minutes
    var delayInMinutes = 10;
    SnapEngage.setNoProactiveChatDelay(delayInMinutes);
    

    Disable or alter the amount of time that proactive invitations remain disabled for any visitor who closes a chat window. The default proactive invitation delay (without using this API) is 30 minutes.

    Parameters

    Parameter Type Description
    delayInMinutes Integer By default, we think that if a visitor closes a chat window, they are either not interested in chatting or done chatting. In order to avoid bombarding them with proactive invitations we set a cookie to disable proactive invitations for that visitor for 30 minutes by default. You can alter that amount of time with this function. (To use a session cookie, set to 0.)

    .setProactiveAutoCloseDelay()

    // Autoclose the proactive invitation after 5 minutes of inactivity
    var minutes = 5;
    SnapEngage.setProactiveAutocloseDelay(minutes);
    

    Adjust the time before the proactive invitation disappears. The default proactive autoclose delay is 2 minutes.

    By default, the proactive chat window is set to close after 2 minutes of inactivity, that is: if a visitor does not respond for a couple minutes, we generally assume that they are not interested in chatting. If you never want the proactive invitation to disappear, set the parameter to 0.

    Parameters

    Parameter Type Description
    minutes Integer Number (in minutes) until auto-close. This can be a whole number or decimal (eg. 0.5 can be used for a delay of 30 seconds).

    .setUserEmail()

    var email = 'johnsnow@thenorth.com';
    
    // Set the email field
    SnapEngage.setUserEmail(email);
    
    // Do the same as above AND make the email field read-only
    // i.e. not editable for the visitor
    SnapEngage.setUserEmail(email, true);
    

    Provide a visitor's email address to SnapEngage.

    This will do two things: First, it pre-populates the 'email' field on your prechat or offline form.

    Second, even if you are not using a prechat form, this will still provide a visitor’s email address to an agent who takes the chat. (The email gets stored in the case and will be passed to your integration at the close of the case).

    Parameters

    Parameter Type Description
    email String A non-encoded email address, for example, 'someone@example.com'. You will need to use your local environment to deliver the email address to this function, either through server-side scripting or JavaScript.
    locked boolean An optional parameter. If set to true, the email field will be locked i.e. read-only and the visitor will not be able to edit the field. If set to false, the email field will not be read-only and the visitor will be able to edit the field (this is the default).

    .setUserName()

    var name = 'Arya Stark';
    SnapEngage.setUserName(name);
    

    Provide a visitor's name to SnapEngage. This will provide a Visitor’s name to an Agent who takes the chat.

    Parameters

    Parameter Type Description
    name String A non-encoded name, for example, someone@example.com. You will need to use your local environment to deliver the name to this function, either through server-side scripting or JavaScript.

    .setWidgetId()

    DEPRECATED as of March 12th 2018. See switchWidget() for improved functionality.

    var widgetId = '1234-5678-91011-1213-1415'
    SnapEngage.setWidgetId(widgetId);
    

    Manually set the currently-active widget. A common use case would be offering chat buttons which are linked to separate widgets on a single page; for instance, creating one link that goes to your Help Desk widget, and another that goes to your Sales Team widget. Learn how to set that up right here.

    Parameters

    Parameter Type Description
    widgetId String The widget ID that you would like to dynamically set as the active widget on your website. You can find your widget ID inside the Admin Dashboard's Settings, by clicking the Get the Code tab. Scroll to the '(Advanced) Widget ID' section.

    .showButton()

    SnapEngage.showButton();
    

    Show the floating online or offline button defined in your Design Studio theme (or for legacy users, the button set up in your Style tab).

    No Parameters

    .startChat()

    var msg = 'Hey there, do you need help learning about' +
    ' The Invigaron System?';
    SnapEngage.startChat(msg);
    

    Start a chat session and send a manually defined message to the visitor.

    Parameters

    Parameter Type Description
    msg String A string containing the first chat message to be sent to the visitor when this function fires.
    SnapEngage.startLink();
    
    // You can also use this JavaScript method inside the onclick attribute
    // of an <a> tag on your page. When a visitor clicks this link, it will fire
    // SnapEngage.startLink() and open the chat box.
    <a href="#" onclick="SnapEngage.startLink();">Chat with us!</a>
    

    The default method for starting a chat from an on-page <a> link's onclick event.

    No Parameters

    .switchWidget()

    var newWidgetId = '1234-5678-91011-1213-1415';
    var switchCallback = function() {
        // do something
    };
    
    SnapEngage.switchWidget(newWidgetId, switchCallback);
    

    Enable switching between two widgets.

    We have deprecated the setWidgetId() API to provide a better solution for switching between two widgets and returning a more accurate status to help with your business needs. Additionally, we now offer an optional callback parameter so you can do more when the new status is returned. Here we do not differentiate between online and offline status, however, you can use the getAgentStatusAsync API to call different methods based on the new status.

    Parameters

    Parameter Type Description
    newWidgetId String Must be a valid SnapEngage Widget ID (‘xxxx-xxxx-xxxx-xxx-xxxx’). The new WidgetID you would like to activate. Learn how to set that up here.
    switchCallback Anonymous Function (OPTIONAL) A predefined function that will get called after our system completes checking the newWidgetId status.

    Returns

    Type Description
    Boolean Will return false with console warning ONLY if the newWidgetId parameter is not provided. Otherwise no return value provided.

    Example switchWidget() Usage

    // Setup required parameters
    var newWidgetId = '1234-5678-91011-1213-1415';
    var switchCallback = function() {
        SnapEngage.getAgentStatusAsync(function (online) {
            if(online) {
                console.log('Chat available');
            } else {
                console.log('Chat offline');
            }
        });
    };
    
    // Now call the API
    SnapEngage.switchWidget(newWidgetId, switchCallback);
    

    Integration API

    The SnapEngage Integration API allows developers to easily interface SnapEngage with third-party applications like CRM and helpdesk solutions.

    Using the API, SnapEngage can automatically POST events to an external URL when new requests are received (either offline or live chat). This transaction provides detailed information pertaining to the request and allows developers to recreate the request in the destination system.

    Authentication for Integration API

    An authentication key is not needed to use the Integration API.

    How to activate the Integration API

    In the SnapEngage Admin Dashboard, under the "Integrations" tab, select "Integration API" and enter the URL of where you want to receive the POST message when a new offline request or live chat is processed by SnapEngage. Once you are done making changes, just make sure to click the "Save" button.

    Integration API Authentication

    Integration API Details (JSON and XML)

    This page will go over all of the possible fields that may be included within a POST of a support request. If a field does not have data associated with it, then it will not show up within the data.

    The data will be returned in JSON for all new consumers of the Integration API. If XML is needed, please contact SnapEngage support.

    Retries: The target system needs to respond with and HTTP 200 to confirm that the event has been received and processed. In the absence of a successful HTTP response, SnapEngage will retry the HTTP POST automatically for approximately 2 hours before sending it through email and flagging the event as sent.

    Using PHP: The content is a stream in JSON or XML format. You can not access this stream in the $_* variables of PHP. Please use this instead (see PHP tab to the right).

    $json = fopen("php://input","r");
    

    Return Data Fields

    {
        "id": "8b7c3b3b-f5d7-4e58-96d8",
        "widget_id": "e8175843-d381-4d7c-aa9f-0da1610ad1b",
        "url": "https://www.snapengage.com/viewcase?c=8b7c3b3b-f5d7-4e58-96d8",
        "snapshot_image_url": "https://www.snapengage.com/snapabug/ServiceImage?c=8b7c3b3b-f5d7-4e58-96d8",
        "type": "chat",
        "requested_by": "test@test.com",
        "requester_details":
          {
            "name": "Jim Tester",
            "emails": ["test@example.com"],
            "name_profile_link": "http://facebook.com/jimtester",
            "phones": ["555-555-1010"],
            "address": "111 2nd Ave.",
            "address_2": "",
            "city": "Boulder",
            "state": "CO",
            "zip": "80303",
            "country": "US",
            "company_name": "SnapEngage",
            "company_profile_link": "http://facebook.com/snapengage",
            "employees": "Abe,Betty,Charlie",
            "revenue": "100",
            "title": "CEO",
            "website": "www.snapengage.com",
            "social_profile_links": ["www.facebook.com/jimatsnapengage","www.twitter.com/jimtesteratsnap"],
            "gender": "Male",
            "age": 44,
            "influencer_score": "88.8",
            "notes": "This is just for testing",
            "industry": "Tech",
            "avatars": ["http://www.avatars.com/jimtester"],
            "other_data": []
          },
        "description": "Testing the Integration API...",
        "created_at_date": "Oct 3, 2014 2:14:31 PM",
        "created_at_seconds": 1412367271,
        "created_at_milliseconds": 268,
        "proactive_chat": false,
        "page_url": "http://www.snapengage.com/demo/integrationapi.html",
        "referrer_url": "http://www.comingfromurl.com",
        "entry_url": "http://www.yoursite.com",
        "ip_address": "67.174.108.196",
        "user_agent": "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US) AppleWebKit/532.0 (KHTML, like Gecko) Chrome/3.0.195.27 Safari/532.0,gzip(gfe)",
        "browser": "Chrome (3.0.195.27)",
        "os": "Microsoft Windows Vista",
        "country_code": "US",
        "country": "United States",
        "region": "16",
        "city": "Boulder",
        "latitude": 39.914700,
        "longitude": -105.080902,
        "source_id": 2,
        "chat_waittime": 2,
        "chat_duration": 15,
        "language_code": "en-US,en;q=0.8",
        "transcripts": [
          {
            "id": "",
            "date": "Oct 3, 2014 2:14:31 PM",
            "date_seconds": 1412367271,
            "date_milliseconds": 154,
            "alias": "visitor",
            "message": "Hello, "
          },
          {
            "id": "jerome@snapengage.com",
            "date": "Oct 3, 2014 2:14:31 PM",
            "date_seconds": 1412367271,
            "date_milliseconds": 456,
            "alias": "test",
            "message": "Hi, "
          },
          {
            "id": "",
            "date": "Oct 3, 2014 2:14:31 PM",
            "date_seconds": 1412367271,
            "date_milliseconds": 835,
            "alias": "visitor",
            "message": "This is a test."
          }
        ],
        "plugins": [
          {
            "name": "Java",
            "value": "1.2.3"
          }, {
            "name": "Flash",
            "value": "3.4.5"
        }],
        "javascript_variables": [{
            "name": "variable1",
            "value": "v1_1234"
        }, {
            "name": "variable2",
            "value": "v2_123456789"
        }],
        "operator_variables": [{
            "name": "note",
            "value": "this is a note entered by the agent"
        }, {
            "name": "customerTemp",
            "value": "Very Happy"
        }],
        "labels": [{
            "name": "note",
            "value": "this is a note entered by the agent"
        }, {
            "name": "customerTemp",
            "value": "Very Happy"
        }]
    }
    
    <?xml version="1.0" encoding="UTF-8"?>
    <case>
    
      <id><![CDATA[8b7c3b3b-f5d7-4e58-96d8]]></id>
      <url>http://www.snapengage.com/viewcase?c=8b7c3b3b-f5d7-4e58-96d8</url>
      <snapshot_image_url>http://www.snapengage.com/snapabug/ServiceImage?c=8b7c3b3b-f5d7-4e58-96d8</snapshot_image_url>
      <requested_by><![CDATA[test@test.com]]></requested_by>
      <description><![CDATA[Testing the Integration API...]]></description>
      <created_at type="datetime">2010-10-18T01:48:18.623Z</created_at>
      <page_url>http://www.snapengage.com/demo/integrationapi.html></page_url>
      <ip_address>67.174.108.196</ip_address>
      <browser>Chrome (6.0.472.63)</browser>
      <os>Microsoft Windows 7</os>
      <country_code>US</country_code>
      <country>United States</country>
      <region>CO</region>
      <city><![CDATA[Boulder]]></city>
      <latitude>39.914700</latitude>
      <longitude>-105.080902</longitude>
      <source_id type="integer">2</source_id>
    
      <languages type="array">
        <language>
          <name><![CDATA[English]]></name>
    <![CDATA[en-US]]>
        </language>
        <language>
          <name><![CDATA[German]]></name>
    <![CDATA[de-DE]]>
        </language>
      </languages>
    
      <plugins type="array">
        <plugin>
          <name>Flash</name>
          <value>10.0.45</value>
        </plugin>
        <plugin>
          <name>Java</name>
          <value>1.6</value>
        </plugin>
      </plugins>
    
      <javascript_variables type="array">
        <javascript_variable>
          <name><![CDATA[userid]]></name>
          <value><![CDATA[ab123456789]]></value>
        </javascript_variable>
      </javascript_variables>
    
      <operator_variables type="array">
       <operator_variable>
         <name><![CDATA[note]]></name>
         <value><![CDATA[this is a note entered by the agent]]></value>
        </operator_variable>
      </operator_variables>
    
      <labels type="array">
       <label>
         <name><![CDATA[note]]></name>
         <value><![CDATA[this is a note entered by the agent]]></value>
       </label>
     </labels>
    
      <transcripts type="array">
        <transcript>
          <id>jerome@snapengage.com</id>
          <date type="datetime">Mon Oct 18 01:48:27 UTC 2010</date>
          <alias>test</alias>
          <message>Hello, </message>
        </transcript>
        <transcript>
          <id></id>
          <date type="datetime">Mon Oct 18 01:48:32 UTC 2010</date>
          <alias>visitor</alias>
          <message>Hi,</message>
        </transcript>
        <transcript>
          <id></id>
          <date type="datetime">Mon Oct 18 01:48:41 UTC 2010</date>
          <alias>visitor</alias>
          <message>This is a test.</message>
        </transcript>
        <transcript>
          <id>jerome@snapengage.com</id>
          <date type="datetime">Mon Oct 18 01:48:49 UTC 2010</date>
          <alias>test</alias>
          <message>ok. thank's for testing. </message>
        </transcript>
      </transcripts>
    
      <chat_waittime type="integer">2</chat_waittime>
      <chat_duration type="integer">15</chat_duration>
      <referrer_url><![CDATA[http://refering.url/]]></referrer_url>
      <entry_url><![CDATA[http://entry.url/]]></entry_url>
    
     </case>
    
    Data Type Description
    id String Internal id created by SnapEngage and can be used to reference the specific support request
    widget_id String The ID of the widget in which the chat took place
    url String URL pointing to the details of the support request
    snapshot_image_url String URL pointing to the snapshot that is associated with the service request, if one was created
    type String Will either be ‘chat’ or ‘offline’, depending on the nature of the service request
    requested_by String Email of the person who requested the chat
    requestor_details String These are details we have gathered about the requester through various online systems.
    ↳ name String (requestor_details) The full name of the requester
    ↳ emails Array of Strings (requestor_details) An array of email address associated with the requester
    ↳ name_profile_link String (requestor_details) A string containing links to contact profiles associated with the requester
    ↳ phones Array of Strings (requestor_details) An array of phone numbers associated with the requester
    ↳ address String (requestor_details) Address associated with the requester
    ↳ address_2 String (requestor_details) Second address associated with the requester
    ↳ city String (requestor_details) City associated with the requester
    ↳ state String (requestor_details) State associated with the requester
    ↳ zip String (requestor_details) Zip code associated with the requester
    ↳ country String (requestor_details) Country associated with the requester
    ↳ company_name String (requestor_details) Name of the company associated with the requester
    ↳ company_profile_link String (requestor_details) Link to the company profile associated with the requester
    ↳ employees String (requestor_details) A comma separated list of employees associated with the requester
    ↳ revenue String (requestor_details) Company revenue associated with the requester
    ↳ title String (requestor_details) Professional title associated with the requester
    ↳ website String (requestor_details) Website associated with the requester
    ↳ social_profile_links Array of Strings (requestor_details) An array of links to social profiles associated with the requester (ie. Twitter, Facebook, LinkedIn, etc)
    ↳ gender String (requestor_details) Gender of requester
    ↳ age Integer (requestor_details) Age of requester
    ↳ influencer_score String (requestor_details) Influencer score associated with the requester
    ↳ notes String (requestor_details) Notes gathered on requester
    ↳ industry String (requestor_details) Industry associated with the requester
    ↳ avatars Array of Strings (requestor_details) An array of links to avatars associated with the requester
    ↳ other_data Array (requestor_details) An array containing any other relevant data associated with the requester
    description String The entered description for the support request
    created_at_date Date Date the support request was created in “MMM d, yyyy h:mm:ss a” format (ie, Oct 3, 2014 2:14:31 PM). Given in GMT.
    created_at_seconds Long Date the support request was created in seconds since January 1, 1970, 00:00:00 GMT
    created_at_milliseconds Integer The milliseconds of the second that the support request was created. If the creation time was 13:43:25.268 then this value would be 268
    proactive_chat Boolean This will either be true or false, depending on if the chat was initiated as a proactive or not
    page_url String Specific URL where the support request originated from
    referrer_url String URL of the website that the user came from to get to the current site
    entry_url String URL of the specific entry point the user came to on the current site
    ip_address String IP address of the person initiating the support request
    user_agent String Details about the initiating person’s user agent
    browser String Specific browser and version information from the support request initiator
    os String Specific operating system information from the support request initiator
    country_code String Two digit country code for the support request initiator
    country String Country for the support request initiator
    region String FIPS region code for the support request initiator
    city String City name for the support request initiator
    latitude Float Latitude, is decimal degrees, for the support request initiator
    longitude Float Longitude, is decimal degrees, for the support request initiator
    source_id Integer Value of 1 when the SnapEngage interaction was an offline message, value of 2 when it was a manual chat, or value of 3 if it was a proactive chat.
    chat_waittime Long Wait time, in seconds, between when the support request was initiated and when an agent responded
    chat_duration Long Duration of the entire support request, in seconds
    language_code String Language codes from the support request initiators browser settings
    transcripts JSON Object An array of transcript objects which are described as:
    ↳ id String (transcripts) Id of the person who created the message. In the case of the visitor, this will be blank
    ↳ date Date (transcripts) Date the message was created in “MMM d, yyyy h:mm:ss a” format (ie, Oct 3, 2014 2:14:31 PM)
    ↳ date_seconds Long (transcripts) Date the message was created in the number of seconds since January 1, 1970, 00:00:00 GMT
    ↳ date_milliseconds Integer (transcripts) The milliseconds of the second that the transcript was created. If the creation time was 13:43:25.268 then this value would be 268
    ↳ alias String (transcripts) Alias of the person who created the message
    ↳ message String (transcripts) Contents of the message
    plugins JSON Object An array of plugin objects which detail any installed plugins within the initiators browser. The plugin data is described as:
    ↳ name String (plugins) Name of the plugin
    ↳ value String (plugins) Value of the plugin
    javascript_variables JSON Object An array of javascript variable objects which detail any defined javascript variables within the support request session. The javascript variable data is described as:
    ↳ name String (javascript_variables) Name of the javascript variable
    ↳ value String (javascript_variables) Value of the javascript variable
    operator_variables JSON Object An array of operator variable objects which detail any defined operator variables within the support request session. The operator variable data is described as:
    ↳ name String (operator_variables) Name of the operator variable
    ↳ value String (operator_variables) Value of the operator variable
    labels JSON Object An array of label objects which detail any defined extra variables within the support request session. The label data is described as:
    ↳ name String (labels) Name of the operator variable
    ↳ value String (labels) Value of the operator variable

    Provisioning API

    The SnapEngage Provisioning REST API provides a method for 3rd parties to perform the following:

    Users
    Widgets

    Authentication for Provisioning API

    A valid API token is required to use the Provisioning REST API. Please email support@snapengage.com if you need to obtain an API key for the Provisioning API.

    Users

    The Provisioning REST API allows you to create a SnapEngage user, get user account details, update, and delete users.

    User request data format

    This API accepts requests in both JSON and XML formats. To specify, use the appropriate format: json or xml. See code examples to the side. To learn more about account types, see our pricing page.

    "https://www.snapengage.com/api/v1/user.json"
    
    {
        "email" : "value",
        "name" : "value",
        "password" : "value",
        "phone" : "value",
        "accountType" : "value"
    }
    
    "https://www.snapengage.com/api/v1/user.xml"
    
    &lt;!--?xml version='1.0' encoding='UTF-8'?--&gt;
        value
        value
        value
        value
        value
    

    Create a new user account

    To create a new user account, you may PUT to the endpoint with your API key as a parameter.

    Method: PUT
    URL: https://www.snapengage.com/api/v1/user.format?api_key=key
    Request Header: "Content-Type:application/json" or "Content-Type:application/xml"
    Request Data: See "Data fields" table below.
    Success: 201 Created
    Returns: User data in specified format

    Data fields

    Data Type Description
    email String Required. A valid email address less than 100 characters.
    name String A valid name less than 100 characters.
    accountType String Requires specific values that are case-sensitive, see the table below of "accountType values".
    password String A valid password between 5 and 100 characters.
    phone String A valid telephone number.

    accountType values

    accountType Value
    Free Trial 'trial'
    Business 'biz'
    Plus 'entr'
    Premier 'prem'
    Enterprise 'enterprise'

    Get user account details or check if user exists

    Get existing user account details if created with same api key, otherwise a check if user exists.

    Method: GET
    URL: https://www.snapengage.com/api/v1/user.format?api_key=key&email=email
    URL Parameters: See "Data fields" table below.
    Success: 200 OK
    Returns: User data in specified format

    Data fields

    Data Type Description
    email String Required. A valid email address less than 100 characters.

    Update an existing user account

    Method: POST
    URL: https://www.snapengage.com/api/v1/user.format?api_key=key
    Request Header: "Content-Type:application/json" or "Content-Type:application/xml"
    Request Data: See "Data fields" table below.
    Success: 200 OK
    Returns: User data in specified format

    Data fields

    Data Type Description
    email String Required. A valid email address less than 100 characters.
    name String A valid name less than 100 characters.
    accountType String Requires specific values that are case-sensitive, see the table below of "accountType values".
    password String A valid password between 5 and 100 characters.
    phone String A valid telephone number.

    accountType values

    accountType Value
    Free Trial 'trial'
    Business 'biz'
    Plus 'entr'
    Premier 'prem'
    Enterprise 'enterprise'

    Delete an existing user account

    Method: DELETE
    URL: https://www.snapengage.com/api/v1/user.format?api_key=key&email=email
    URL Parameters: See "Data fields" table below.
    Success: 200 OK

    Data fields

    Data Type Description
    email String Required. A valid email address less than 100 characters.

    Widgets

    The Provisioning REST API allows you to create a SnapEngage user, get user account details, update, and delete users.

    Widget request data format

    This API accepts requests in both JSON and XML formats. To specify, use the appropriate format: JSON or XML.

    JSON widget format

    See the JSON code example to the right.

    "https://www.snapengage.com/api/v1/widget.json"
    
    {
       "email": "account email address",
       "destinationEmail": "email where transcripts are sent",
       "name": "widget name",
       "agents":[
          {
             "agentId": "agent id",
             "agentAlias": "agent displayed name",
             "agentAvatar": "link to agent image - 53x53px is recommended size",
             "agentType": "either google, skype, or webclient"
          }
       ],
       "onlineButtonUrl": "link to online button",
       "offlineButtonUrl": "link to offline button",
       "enableProactiveChat": "true/false",
       "proactiveSettings":[
          {
             "delayInSec": "time in sec - 45 is default",
             "enableSound": "true/false - default is true",
             "urlRule": "url rule - default is http*://*, matching all pages",
             "message": "proactive message - default is Hello, How can I assist you today?"
          }
       ]
    }
    
    Code sample coming soon.
    

    Create a new widget

    Method: PUT
    URL: https://www.snapengage.com/api/v1/widget.format?api_key=key
    Request Header: "Content-Type:application/json" or "Content-Type:application/xml"
    Request Data: See "Data fields" table below.
    Success: 201 Created
    Returns: Widget data in specified format, including UUID

    Data fields

    Data Type Description
    email String Required. An existing user account email address.
    name String A valid widget name less than 100 characters.
    destinationEmail String The email where transcripts are sent
    agents String Required. At least one agent is required. Each agent must contain the below fields (agentId, agentAlias, agentAvatar, agentType).
    agentId String Required. The agent ID.
    agentAlias String Required. The agent displayed name.
    agentAvatar String Required. Link to an agent image.
    agentType String Required. See table of "agentType values" below.
    onlineButtonUrl String Link to an online button image.
    offlineButtonUrl String Link to an offline button image.
    enableProactiveChat String If true proactive chat is enabled for the widget. If false it is not.
    proactiveSettings String May contain the below fields (delayInSec, message).
    delayInSec String The time in seconds to delay a proactive invitation. Default is 45.
    message String The proactive message to display.

    agentType values

    accountType Value
    Chat Portal User 'webclient'
    GChat User (deprecated) 'google'
    Skype User (deprecated) 'skype'

    Get widget details

    Method: GET
    URL: https://www.snapengage.com/api/v1/widget.format?api_key=key&uuid=uuid&email=email
    URL Parameters: See "Data fields" table below.
    Success: 200 OK
    Returns: Widget data in specified format

    Data fields

    Data Type Description
    uuid String Required. The widget public Id.
    email String Required. The user email associated with this widget.

    Update an existing widget

    Method: POST
    URL: https://www.snapengage.com/api/v1/widget.format?api_key=key
    Request Header: "Content-Type:application/json" or "Content-Type:application/xml"
    Request Data: See "Data fields" table below.
    Success: 200 OK
    Returns: Widget data in specified format

    Data fields

    Data Type Description
    email String Required. An existing user account email address.
    name String A valid widget name less than 100 characters.
    destinationEmail String The email where transcripts are sent
    agents String Required. At least one agent is required. Each agent must contain the below fields (agentId, agentAlias, agentAvatar, agentType).
    agentId String Required. The agent ID.
    agentAlias String Required. The agent displayed name.
    agentAvatar String Required. Link to an agent image.
    agentType String Required. See table of "agentType values" below.
    onlineButtonUrl String Link to an online button image.
    offlineButtonUrl String Link to an offline button image.
    enableProactiveChat String If true proactive chat is enabled for the widget. If false it is not.
    proactiveSettings String May contain the below fields (delayInSec, message).
    delayInSec String The time in seconds to delay a proactive invitation. Default is 45.
    message String The proactive message to display.

    Delete an existing widget

    Method: DELETE
    URL: https://www.snapengage.com/api/v1/widget.format?api_key=key&uuid=uuid&email=email
    URL Parameters: See "Data fields" table below.
    Success: 200 OK

    Data fields

    Data Type Description
    uuid String Required. The widget public Id.
    email String Required. The user email associated with this widget.

    Visitor Chat API

    Check widget availability

    Overview

    Check if chat is currently online for this widget. Please see the cURL tab to the right for an example.

    GET /api/v1/chat/{widgetId}
    

    Request Parameters

    Data Type Description
    widgetId String Unique identifier of chat widget

    Sample Request

    Please see the cURL tab to the right for an example.

    curl -i -H 'X-Api-Key:4a9fecdd4c344f279a59d9446157636e' 'https://www.snapengage.com/api/v1/chat/204557b4-f777-46be-b31b-e660d721364d'
    

    Response Parameters

    Data Type Description
    emailRequired Boolean An email address is required when starting a new chat.
    messageRequired Boolean The initial message is required when starting a new chat.
    online Boolean This chat widget is available to start a chat.
    screenshotRequired Boolean This chat widget requires a screenshot.
    widgetId String Widget UUID from request.

    Success Response 200 OK

    {
       "emailRequired":"true",
       "messageRequired":"true",
       "online":"false",
       "screenshotRequired":"false",
       "widgetId":"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
    }
    

    Start new chat

    Overview

    Create a new Chat session. Please see the cURL tab to the right for an example.

    POST /api/v1/chat
    

    Request Parameters

    Data Type Description
    widgetId String Unique identifier of chat widget.
    email String (Required if emailRequired is true for chat widget) Visitor’s email address.
    phone String (Optional) Visitor’s phone number.
    userAgent String (Optional) Similar to web browser user agent string.
    locale String (Optional) Locale of this chat session. Example could be “en” or “en-GB”.
    isOffline Boolean (Optional, default false) true/false – Open chat session or send message directly to email (offline).
    appVersionName String (Optional) Name/Version of your application.
    visitorMessage String (Required if messageRequired is true for chat widget) Initial visitor chat message.

    Sample Request

    Please see the cURL tab to the right for an example.

    curl -i -H 'X-Api-Key:4a9fecdd4c344f279a59d9446157636e' -X POST \
    -d "widgetId=204557b4-f777-46be-b31b-e660d721364d&email=user@example.com&phone=(555) 867-5309&userAgent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1309.0 Safari/537.17&locale=en-US&isOffline=false&appVersionName=My Mobile App v0.1&visitorMessage=Hello" \
    https://www.snapengage.com/api/v1/chat
    

    Response Parameters

    Data Type Description
    caseId String Unique identifier of chat session.
    widgetId String Unique identifier of chat widget.

    Success Response

    200 OK

    Please see the json tab to the right for an example.

    {
        "caseId":"44843c55-527c-4f03-a779-e0ce655219f7",
        "widgetId":"204557b4-f777-46be-b31b-e660d721364d"
    }
    

    Send chat message

    Overview

    Update the Chat conversation with a new message or end the Chat session. Please see the cURL tab to the right for an example.

    PUT /api/v1/chat
    

    Request Parameters

    Data Type Description
    caseId Sting Unique identifier of chat session. (Obtained from Start New Chat API response: POST /api/v1/chat)
    messageType Integer Use 1 for normal message, 2 to close chat session.
    messageBody String Text of chat message. (utf-8 URL encoded is recommended)

    Sample Request

    Please see the cURL tab to the right for an example.

    curl -i -H 'X-Api-Key:4a9fecdd4c344f279a59d9446157636e' \
    -X PUT \
    -d 'caseId=44843c55-527c-4f03-a779-e0ce655219f7&messageType=1&messageBody=A new chat message' \
    'https://www.snapengage.com/api/v1/chat'
    

    Response Parameters

    Data Type Description
    caseId String Unique identifier of chat session. (Obtained from Start New Chat API response: POST /api/v1/chat)
    messageType Integer Use 1 for normal message, 2 to close chat session.
    messageBody String Text of chat message. (utf-8 URL encoded is recommended)

    Success Response

    200 OK

    Please see the json tab to the right for an example.

    {
        "caseId":"44843c55-527c-4f03-a779-e0ce655219f7",
        "messageType":1,
        "messageBody":"A new chat message"
    }
    

    Poll for new chat message

    Overview

    Check for new chat messages, recommend interval no more than 1-2 seconds. Please see the cURL tab to the right for an example.

    GET /api/v1/chat/poll/{caseId}
    

    Request Parameters

    Data Type Description
    caseId String Unique identifier of chat session. (Obtained from Start New Chat API response: POST /api/v1/chat)
    index Integer (Optional, default 0) The start index of chats to return.
    isTyping Boolean (Optional, default false) Is the visitor currently typing a message?

    Sample Request

    Please see the cURL tab to the right for an example.

    curl -i -H 'X-Api-Key:4a9fecdd4c344f279a59d9446157636e' 'https://www.snapengage.com/api/v1/chat/poll/44843c55-527c-4f03-a779-e0ce655219f7?index=1&isTyping=false'
    

    Response Parameters

    Data Type Description
    caseId String Unique identifier of chat session.
    agentTyping Boolean true if the agent is currently typing a message.
    messageList Array array of messages.
    ↳index Integer Index of the chat message in the transcript.
    ↳type String Either “agent” or “system”.
    ↳author String Id of the message author (agent or visitor).
    ↳text String Chat message text.

    Success Response

    200 OK

    Please see the json tab to the right for an example.

    {
      "caseId":"44843c55-527c-4f03-a779-e0ce655219f7",
      "agentTyping":false,
      "messageList":[
        {
          "index":0,
          "type":"agent",
          "author":"Joe Agent",
          "text":"Hello how are you?"
        }
      ]
    }
    

    Error responses

    400 Bad Request

    Invalid or missing parameter

    // 400 Bad Request
    {
       "message":"Missing xxx parameter",
       "type":"invalid_parameters"
    }
    

    401 Unauthorized

    Invalid or no X-Api-Key set

    // 401 Unauthorized
    {
       "message":"Unauthorized",
       "type":"authentication_error"
    }
    

    404 Not Found

    Widget or Chat object not found (Empty response)

    500 Server Error

    Contact SnapEngage support if you continue to see this Response.

    // 500 Server Error
    {
       "message":"Server Error",
       "type":"server_error"
    }
    

    Logs API

    The SnapEngage Logs API allows developers to batch-export the logs for a particular widget. This API provides a good way to customize your own reporting, and send this data to third-party applications.

    Authentication for Logs API

    Logs API user authentication is token based. You can generate an API token to use by logging in to the Admin Dashboard and going to My Account -> API Token.

    Each request expects for the API token to be included in all API requests to the server in a header that looks like the code sample to the right:

    // NOTE: Make sure to replace the "api_token" below with your API token!
    "Authorization: api_token"
    

    Organization ID

    You can find your orgId in the Admin Dashboard, on the My Account -> Api Token page, after you have generated an API token. Many API calls use this orgId as a URL parameter.

    Get All Logs

    GET /api/v2/{orgId}/logs

    This endpoint retrieves all logs for the widget specified by the users, or all logs for all widgets the user has access to, if no widget is specified.

    HTTP Request

    This is what an HTTP request looks like. Scroll down more for an actual code example.

    GET https://www.snapengage.com/api/v2/{orgId}/logs

    Parameters

    Parameter Type Description
    orgId String Required. You can find your orgId in the Admin Dashboard, on the My Account -> Api Token page, after you have generated an API token.
    widgetId String A single widget ID, or the list of all widget IDS to return logs for. If not specified, all widgets the user has access to will be returned.
    timezone String The timezone requested. If not specified, "Etc/UTC" will be used as the default.
    start String Required. The ISO8601 date to start returning logs from.
    end String Required. The ISO8601 date to stop returning logs from.
    next String If more than 100 results are returned, a value for linkToNextSetOfResults will be returned that can be used to access the next set of results. Otherwise, this parameter is not specified. Note that this capability only works when specifying a single widgetId, multiple widgetIds are not currently supported!

    Example Logs API Usage

    curl "https://www.snapengage.com/api/v2/{orgId}/logs?widgetId={widgetId}&start=2017-04-20&end=2017-04-28" -H "Authorization: api_token"
    

    In the sample cURL command to the right, replace {orgId} with your orgId. Replace {widgetId} with your widgetId. Replace api_token with your own API token.

    Copy your edited string into your command line interface, then submit the command.

    Returns

    {
      "cases": [{
        "id": "a7e91ae8-d4f4-4990-9da6-3b41fe072cc9",
        "url": "https://www.snapengage.com/viewcase?c=a7e91ae8-d4f4-4990-9da6-3b41fe072cc9",
        "type": "chat",
        "requested_by": "george@gmail.com",
        "requester_details": {
          "name": "George",
          "emails": ["george@gmail.com"],
          "phones": [],
          "social_profile_links": ["twitter,bloooppppppp,425240992,https://twitter.com/bloooppppppp"],
          "age": 0,
          "notes": "",
          "avatars": [],
          "other_data": []
        },
        "description": "hey",
        "created_at_date": 1493286277463,
        "created_at_seconds": 1493286277,
        "created_at_milliseconds": 463,
        "proactive_chat": false,
        "page_url": "http://localhost:2000/",
        "referrer_url": "",
        "entry_url": "http://localhost:2000/",
        "ip_address": "93.219.34.218",
        "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36",
        "browser": "Chrome (57.0.2987.133)",
        "os": "Apple OS X 10.10.5",
        "country_code": "DE",
        "country": "Germany",
        "region": "BE",
        "city": "Berlin",
        "latitude": 52.520008,
        "longitude": 13.404954,
        "source_id": 2,
        "chat_waittime": 2,
        "chat_duration": 3,
        "chat_agent_id": "wc:samantha+test@snapengage.com",
        "chat_agent_alias": "Michael Cera!",
        "survey_score": 100,
        "survey_comments": "He was a good guy.",
        "language_code": "en,en-US;q=0.8,pt;q=0.6",
        "transcripts": [{
          "id": "",
          "date": 1493286278592,
          "date_seconds": 1493286278,
          "date_milliseconds": 592,
          "alias": "",
          "message": "hey"
        }, {
          "id": "wc:samantha+test@snapengage.com",
          "date": 1493286280821,
          "date_seconds": 1493286280,
          "date_milliseconds": 821,
          "alias": "Michael Cera!",
          "message": "hi"
        }],
        "javascript_variables": [{
          "name": "productName",
          "value": "Der Blahster"
        }, {
          "name": "productPrice",
          "value": "$3.99"
        }],
        "operator_variables":[{  
          "name":"Label",
          "value":"Labellabellabel"
        }],
        "labels":[{  
          "name":"Label",
          "value":"Labellabellabel"
        }],
        "destination_url": "mailto:samantha+test@snapengage.com"
      }],
      "linkToNextSetOfResults": ""
    }
    

    The cURL command above returns JSON data of one chat case.

    Special Notes about Return Data

    Most of the returned data is pretty self-explanatory. However some of the data may need some additional explanation, which is below.

    survey_score and survey_comments You will see a survey score for a chat case if a widget has the survey enabled, and if the visitor has chosen to rate the agent at the end of the chat. When a chat ends, we wait 5 minutes before storing the survey data, and the survey actually may stay open on the visitor’s browser for any extended amount of time, which means that the survey score and comments may be stored to the case long after the end time of the chat. This is important because if you are querying the Logs API to return survey data for your chat agents, you should wait a minimum of 5 minutes after the close of a chat before expecting to see survey data for that chat.

    Errors

    Error Code Description
    400 Bad request – Incorrect or malformed request data
    401 Unauthorized – Invalid API token
    403 Forbidden – API Token not allowed to access this
    404 Not Found – Resource not found
    429 Too Many Requests – Exceeded the API rate limit
    500 Internal Server Error – Something wrong on the server side. Try again later.
    503 Service Unavailable – API endpoint is down. Try again later.
    504 Gateway Timeout – Request took too long to execute

    Glossary

    Some of the SnapEngage terminology may take some explanation and getting used to! Here are some definitions of the terminology we use within the different APIs.

    Advanced Code Snippet

    Early in 2014, we removed the basic/advanced versions of the code. All customers now have the “Advanced” code snippet by default. If your code snippet does not look like the ones pictured below, you may want to re-install your SnapEngage code.

    Overview

    For most of our users, the “Basic” version of the SnapEngage Code Snippet will suffice.

    But for advanced users and Web Developers, the “Advanced” version of the Code Snippet is designed to provide much more flexibility. It provides a framework for for hand-coding customizations to your Live Chat, using SnapEngage’s JavaScript API.

    Since our code loads asynchronously, you need to use the Advanced Code Snippet so that your calls to SnapEngage’s Javascript API do not occur before those functions are available.

    So here’s where to get it

    First, log into your trusty Admin Dashboard, and navigate to the “Get the Code” tab.

    Then just open up the “Advanced” section by clicking on the word.

    That’s it. You now have access to the Advanced code snippet, use this power wisely.

    Agent

    Agent: The person logged into the SnapEngage Chat Portal; the person who chats with the Visitors and (hopefully) provides great customer service for said Visitors.

    Do I need an API Key?

    The term “API” can be confusing, so all this talk of an “API Key” can be equally confusing.

    The short answer is: 99% of our clients will not need an API Key.

    Some common points of confusion:

    What is an API Key and what would I need it for?

    An API Key provides access to our:

    "SnapABug"

    Way way back, in the before times–- in the long, long ago–- SnapEngage went by a different name. It was a simpler time, but a darker time. That which you have come to know as SnapEngage was a mere glimmer of its current, shining self. The promise of greatness was there, to be sure, but it was... a larval state, if you will.

    SnapABug evolved into SnapEngage.

    We have updated the vast majority of our documentation to replace "SnapABug" with "SnapEngage". But, alas, in some of the help articles you come across, you may find a function call hooked onto SnapABug.functionName(); rather than SnapEngage.functionName(); — “SnapABug” is still supported for legacy purposes, and the two can technically be used interchangeably, but all documentation henceforth will use the newer, better, faster, stronger, “SnapEngage.”

    We highly recommend and request you do the same.

    Visitor

    There are many words you might use for the people who visit your website: client, user, Jeff, customer, etc. Since things like documentation can get confusing without a common lexicon, please make a note of this definition:

    Visitor: The person who is viewing your website, and may or may not be chatting with one of your Agents.

    Widget ID

    SnapEngage lets you define multiple instances of your chat with different settings depending on the context in which each will be used. Only one Widget can be active on a page at any given time; the active Widget can be manipulated with the .setWidgetId() function.

    For example, you might have one Widget for your Support staff, and another Widget for your Sales Team; you might make one Widget for English speakers, and another for Spanish speakers.

    What is my Widget ID?

    Each of these instances is given its own Widget ID, a unique string of alphanumeric characters. You can see the Widget ID of each of your widgets by first logging in to your Admin Dashboard then click on Settings > Get the Code and scroll down to (Advanced) Widget ID.

    SnapEngage.getWidgetId();
    
    // Calling the above will return the widget ID currently active on the website
    '1z1z1z1z1-y2y2-x3x3-w4w4-v5v5v5v5v5v'
    
    
    
    

    To get the widget ID using the JavaScript API, you can call SnapEngage.getWidgetId() as shown to the right.

    See the .getWidgetId() documentation.

    // You can set a different widget ID if you'd like:
    SnapEngage.setWidgetId('32423f-3213sfvd-2123sdv-2312');
    
    

    To set a different widget ID, you can use the setWidgetID() JavaScript API, as shown to the right.

    See the .setWidgetId() documentation.