NAV
JavaScript cURL JSON XML PHP Java Python Swift
  • Introduction
  • Agent Status API
  • Bot API
  • Conversation Events API
  • Hub SDK
  • Integration API
  • JavaScript API
  • Logs API
  • Mobile SDK
  • Provisioning API
  • Visitor Chat API
  • Widget Availability API
  • Glossary
  • Introduction

    Snapengage Logo

    Agent Status API

    The SnapEngage Agent Status API is a two-way API that allows developers send agent status changes to SnapEngage, or receive updates of agent status changes from SnapEngage.

    Authentication for Agent Status API

    An API Token generated in the Admin Dashboard is required to POST an agent status to SnapEngage. The API Token must be generated by the Admin user inside the Admin Dashboard. In the Admin Dashboard, click "My Account" on the left menu. In the sub-menus at the top of the page, select "API", and then select "API Token". Generate an API Token and click "Copy to Clipboard". You will use this API Token in your POST request as an Authorization Header. See POST agent status to SnapEngage for more details.

    An Authorization Token is an optional field that can be received along with agent status changes from SnapEngage. If authentication is desired, simply enter your own custom API token inside the "Authentication Token" field of the Agent Status API settings in the Admin Dashboard. (See below for navigation instructions). This token will then be delivered as a Header in the POST request data. You will need to use this same API token inside the endpoint where you receive agent status updates from SnapEngage. See Receive agent status from SnapEngage for more details.

    How to activate the Agent Status API

    In the SnapEngage Admin Dashboard, click "My Account" on the left menu. In the sub-menus at the top of the page, select "API", and then select "Agent Status API".

    Once you are done making changes, make sure to click the "Save" button.

    Agent Status API Authentication

    POST agent status to SnapEngage

    Send a POST request with an agent status and optional sub-status to SnapEngage for a particular agent. Sending this agent status to SnapEngage will update this agent's status inside SnapEngage.

    POST /api/v2/agentstatus
    

    Request Parameters

    Data Type Description
    agent_id String Required. The agent email address.
    status String Required. The agent status. Status must be either "online" or "pause". There is no mechanism to set the agent status to offline.
    sub_status String Additional info about the agent's status (ex) "Gone to lunch")

    Sample Request

    To view an example request, see the cURL tab or Java tab to the right.

    // NOTE: Make sure to replace the "{api_token}" below with your API token!
    
      curl \
      -H "Content-Type: application/json" \
      -H "Authorization: {api_token}" \
      -X POST \
      -d '{"agent_id":"{user_email}", "status":"pause", "sub_status":"Gone to lunch"}' \
      https://www.snapengage.com/api/v2/agentstatus
    
    package com.snapengage.samples.agentstatus;
    
    import javax.ws.rs.client.ClientBuilder;
    import javax.ws.rs.client.Entity;
    import javax.ws.rs.client.WebTarget;
    import javax.ws.rs.core.HttpHeaders;
    import javax.ws.rs.core.Response;
    
    public class Example {
    
      private static final String apiKey = "{api_token}";
    
      public static void main(String[] args) {
        WebTarget webTarget = ClientBuilder.newBuilder().build()
            .target("https://www.snapengage.com/api/v2/agentstatus");
    
        SnapEngageAgentStatus snapEngageAgentStatus =
            new SnapEngageAgentStatus("{user_email}", "online", "Totally ready to chat");
    
        Response response = webTarget.request().header(HttpHeaders.AUTHORIZATION, apiKey)
            .post(Entity.json(snapEngageAgentStatus));
    
        System.out.println("Response: " + response.getStatus());
      }
    }
    
    // Note: This object is used in all of the Java code samples for the Agent Status API
    package com.snapengage.samples.agentstatus;
    
    public class SnapEngageAgentStatus {
    
      private String agent_id;
      private String status;
      private String sub_status;
      private Long org;
      private Long timestamp;
    
      private SnapEngageAgentStatus() {
        // no-args constructor required for json serialization/de-serialization
      }
    
      public SnapEngageAgentStatus(String agent_id, String status, String sub_status) {
        this.agent_id = agent_id;
        this.status = status;
        this.sub_status = sub_status;
      }
    
      public SnapEngageAgentStatus(String agent_id, String status, String sub_status, Long org, Long timestamp) {
        this(agent_id, status, sub_status);
        this.org = org;
        this.timestamp = timestamp;
      }
    
      public String getAgent_id() {
        return agent_id;
      }
    
      public void setAgent_id(String agent_id) {
        this.agent_id = agent_id;
      }
    
      public String getStatus() {
        return status;
      }
    
      public void setStatus(String status) {
        this.status = status;
      }
    
      public String getSub_status() {
        return sub_status;
      }
    
      public void setSub_status(String sub_status) {
        this.sub_status = sub_status;
      }
    
      public Long getOrg() {
        return org;
      }
    
      public void setOrg(Long org) {
        this.org = org;
      }
    
      public Long getTimestamp() {
        return timestamp;
      }
    
      public void setTimestamp(Long timestamp) {
        this.timestamp = timestamp;
      }
    }
    

    Success Response

    200 OK

    Receive agent status changes from SnapEngage

    On change of an agent status, SnapEngage will send a POST request to the developer's endpoint URL. For information on where to enter the endpoint, and how to optionally authenticate, please see How to activate the Agent Status API.

    Response Parameters

    Data Type Description
    org Long The SnapEngage organization ID which this agent is part of.
    agent_id String The agent email address, which is prepended with "wc:".
    status String The agent status. Status can be of type "online", "pause", or "offline".
    sub_status String Additional info about the agent's status change, sent only when available. (ex) "Gone to lunch")
    timestamp Long The timestamp which this agent status change occurred. Timestamp is a unix epoch.

    Sample Response

    Click the JSON tab to the right to view a sample JSON response.

    {
        "org": 5406213,
        "agent_id": "wc:[email protected]",
        "status": "pause",
        "sub_status": "Gone to lunch",
        "timestamp": 1551461879355
    }
    

    Sample Endpoint

    Click the Java tab to the right to view a sample endpoint. The endpoint has been written using JAX-RS.

    package com.snapengage.samples.agentstatus;
    
    import static com.snapengage.samples.agentstatus.AgentStatusResource.RESOURCE_URL;
    
    import java.util.logging.Logger;
    
    import javax.inject.Singleton;
    import javax.servlet.http.HttpServletRequest;
    import javax.ws.rs.POST;
    import javax.ws.rs.Path;
    import javax.ws.rs.Produces;
    import javax.ws.rs.core.Context;
    import javax.ws.rs.core.HttpHeaders;
    import javax.ws.rs.core.MediaType;
    import javax.ws.rs.core.Response;
    
    import com.google.common.base.Strings;
    
    @Singleton
    @Path(RESOURCE_URL)
    public class AgentStatusResource {
    
      public static final String RESOURCE_URL = "/snapengage/agentstatus";
    
      static final String apiToken = "{api_token}";
    
      @POST
      @Produces(MediaType.APPLICATION_JSON)
      public static Response receiveAgentStatus(SnapEngageAgentStatus snapengageAgentStatus,
          @Context HttpServletRequest request) {
    
        // Optional check of incoming API token
        String headerApiToken = request.getHeader(HttpHeaders.AUTHORIZATION);
        if (Strings.isNullOrEmpty(headerApiToken) || !headerApiToken.equals(apiToken)) {
          log.severe("Incoming API token is empty or does not match our API token.");
          return Response.status(Response.Status.UNAUTHORIZED).build();
        }
    
        System.out.println("agentId: " + snapengageAgentStatus.getAgent_id());
        System.out.println("status: " + snapengageAgentStatus.getStatus());
        System.out.println("sub_status: " + snapengageAgentStatus.getSub_status());
        System.out.println("org: " + snapengageAgentStatus.getOrg());
        System.out.println("timestamp: " + snapengageAgentStatus.getTimestamp());
    
        return Response.ok().build();
      }
    }
    

    Success Response

    2xx Success

    Error Response

    400 Bad Request

    {
        "code": 400,
        "message": "Detailed message"
    }
    

    Bot API

    The SnapEngage Bot API allows developers to create your own chat bot or build a connection with 3rd party bot providers. Through the API a bot agent can take chats just as a human agent can and perform operations such as sending messages and issuing various commands such as transfers, bans and goto (co-browsing).

    Authentication for the Bot API

    An Authorization Token is an optional field that can be received along with bot webhooks from SnapEngage. If authentication is desired, simply enter your own custom API token inside the "Authentication Token" field of the API Bot Details dialog in the Admin Dashboard. (See below for navigation instructions). This token will then be delivered as a Header in the POST request data. You will need to use this same API token inside the endpoint where you receive the webhooks from SnapEngage. See Receive bot webhooks from SnapEngage for more details.

    How to activate the Bot API

    In the SnapEngage Admin Dashboard, after selecting the appropriate widget, click "Settings" on the left menu. In the sub-menus at the top of the page, select "Agent Settings", "Chat Agents", and then click on the "Add Custom API Bot" tile.

    Once you are done making changes, make sure to click the "Save" button.

    Bot API Selection Bot API Dialog

    Receive bot webhooks from SnapEngage

    In the event of chat starting, ending, or a visitor or system message SnapEngage will send a POST request to the developer's endpoint URL. For information on where to enter the endpoint, and how to optionally authenticate, please see How to activate the Bot API.

    Chat Started Parameters

    Data Type Description
    widget_id String The id of the widget that the conversation event occurred on.
    case_id String The id of the conversation that the event occurred on.
    timestamp Long The timestamp which this event occurred. Timestamp is a unix epoch.
    event String "chatStarted"
    email String The email provided by the visitor.
    proactive_message String The message that was displayed to the visitor as part of the proactive prompt. If it was a non-proactive chat then the element would not be included.
    description String The first message sent by the visitor.
    tags String The tags supplied at the start of the chat.
    geo Object city, region, and country_code of the visitor.
    user_agent String The User-Agent of the visitor.
    entry_url String The first page on your website where a visitor landed.
    referrer_url String The URL from which a visitor arrived on your site.
    page_url String The page the visitor started the chat on.
    ip_address String IP address of the visitor.
    jsVariables String Comma separated list of the javascript variables and their values.
    hmacVerificationResult Object To allow the bot to verify the identity of a visitor and to prevent impersonation, you can enable the Visitor Identity Verification in the Admin Dashboard. For more details you can visit here

    Note: Not all elements will be available for every chat. As such, users of this API will need to implement appropriate condition handling when elements are not present or contain empty values.

    Success Response

    Sample Chat Started JSON

    Click the JSON tab to the right to view a sample JSON response.

    2xx Success if the Visitor Identity Verification is enabled in the Admin Dashboard
    {
      "widget_id":"ff7b3314-24de-4a4c-b48b-1cf38d19acf0",
      "case_id":"ab992c69-7de8-46cc-9aaa-329d336bc182",
      "timestamp":1554321077338,
      "event":"chatStarted",
      "text":"Greetings!",
      "user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36",
      "entry_url":"https://example.com/",
      "page_url":"https://example.com/contact",
      "ip_address":"71.56.219.144",
      "geo":{
        "city":"Boulder",
        "region":"CO",
        "country_code":"US"
      }, 
      "hmacVerificationResult":{
        "verificationProperty":{
          "property":"CaseEmail"
        },
        "content":"[email protected]",
        "status":"VERIFIED"
      }
    }
    
    2xx Success if the Visitor Identity Verification is disabled in the Admin Dashboard
    {
      "widget_id":"ff7b3314-24de-4a4c-b48b-1cf38d19acf0",
      "case_id":"ab992c69-7de8-46cc-9aaa-329d336bc182",
      "timestamp":1554321077338,
      "event":"chatStarted",
      "text":"Greetings!",
      "user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36",
      "entry_url":"https://example.com/",
      "page_url":"https://example.com/contact",
      "ip_address":"71.56.219.144",
      "geo":{
        "city":"Boulder",
        "region":"CO",
        "country_code":"US"
      }
    }
    

    Chat Closed Parameters

    Data Type Description
    widget_id String The id of the widget that the conversation event occurred on.
    case_id String The id of the conversation that the event occurred on.
    timestamp Long The timestamp which this event occurred. Timestamp is a unix epoch.
    event String "chatClosed"

    Sample Chat Closed JSON

    Click the JSON tab to the right to view a sample JSON response.

    {
      "widget_id":"ff7b3314-24de-4a4c-b48b-1cf38d19acf0",
      "case_id":"ab992c69-7de8-46cc-9aaa-329d336bc182",
      "timestamp":1554321266626,
      "event":"chatClosed"
    }
    

    Message Parameters

    Data Type Description
    widget_id String The id of the widget that the conversation event occurred on.
    case_id String The id of the conversation that the event occurred on.
    event String message
    from String visitor
    text String The content of message.
    id (optional) String The id of the clicked display response.

    Sample Visitor Message JSON

    Click the JSON tab to the right to view a sample JSON response.

    {
      "widget_id":"ff7b3314-24de-4a4c-b48b-1cf38d19acf0",
      "case_id":"ab992c69-7de8-46cc-9aaa-329d336bc182",
      "timestamp":1554321848997,
      "event":"message",
      "from":"visitor",
      "text":"What is your most flexible plan?"
    }
    

    Message Response Parameters

    Endpoints can respond to chat started or message webhooks with messages, or commands, or both.

    Data Type Description
    widget_id String The id of the widget that the conversation event occurred on.
    case_id String The id of the conversation that the event occurred on.
    context_id String if set, this id will be sent back with the subsequent request
    content Array An array of messages, or commands, or both, to be sent to the visitor.

    "context_id" is an optional on a per request id that can be used for tracking requests and responses. If set on a response, we send it back with the subsequent request and delete it afterwards.

    Sample Bot Messages Response JSON

    Note: This sample includes the optional "display_responses" which results in the visitor seeing "Yes" or "No" buttons. An optional id field can be defined for each button and it would be returned with the message response when the button is clicked.

    {
      "widget_id":"XXX-XXX-XXX-XXX",
      "case_id":"XXX-XXX-XXX-XXX",
      "content":[
        {
          "type":"message",
          "text":"I need to ask you a few questions..."
        },
        {
          "type":"message",
          "text":"Are you willing to travel during the week?",
          "display_responses":[
            {
              "text":"Yes",
              "id": "btn-123"
            },
            {
              "text":"No"
            }
          ]
        }
      ]
    }
    

    Sample Bot Message and Command Response JSON

    {
      "widget_id":"XXX-XXX-XXX-XXX",
      "case_id":"XXX-XXX-XXX-XXX",
      "content":[
        {
          "type":"message",
          "text":"Let me show you our pricing page..."
        },
        {
          "type":"command",
          "operation":"GOTO",
          "parameters":"https://example.com/pricing"
        }
      ]
    }
    

    Sample Bot Command Response JSON

    {
      "widget_id":"XXX-XXX-XXX-XXX",
      "case_id":"XXX-XXX-XXX-XXX",
      "content":[
        {
          "type":"command",
          "operation":"BYE"
        }
      ]
    }
    

    Sample Bot Message and Command Card Response JSON

    Note: This sample includes both a message and command response. The command card layout can be set to either VERTICAL or HORIZONTAL. Example of what the visitor will see when the VERTICAL layout is used:

    Command Card VERTICAL

    {
      "widget_id":"XXX-XXX-XXX-XXX",
      "case_id":"XXX-XXX-XXX-XXX",
      "content":[
        {
          "text":"Which is better?",
          "type":"message"
        },
        {
          "operation":"CARDS",
          "parameters":{
            "type":"cards",
            "layout":"VERTICAL",
            "cards":[
              {
                "title":"5 Reasons Life Is Better For Cat People",
                "excerpt":"But science tells us there are some unique benefits that come with cats.",
                "link":"https://www.businessinsider.com/why-cats-are-better-than-dogs-2015-1"
              },
              {
                "title":"11 Scientific Reasons Dogs Are Better Than Cats",
                "excerpt":"I can recognize the vast benefits of owning a dog over a litter-trained furball",
                "link":"https://www.businessinsider.com/11-reasons-dogs-are-better-than-cats-2014-4"
              }
            ]
          },
          "type":"command"
        }
      ]
    }
    

    Sample TAG_TRANSFER Command Response JSON

    {
      "widget_id":"XXX-XXX-XXX-XXX",
      "case_id":"XXX-XXX-XXX-XXX",
      "content":[
        {
          "type":"command",
          "operation":"TAG_TRANSFER",
          "parameters":"ZZZZ-ZZZZ-ZZZZ-ZZZZ [\"TAG1\", \"TAG2\"]"
        }
      ]
    }
    

    Sample LABEL Command Response JSON

    {
      "widget_id":"XXX-XXX-XXX-XXX",
      "case_id":"XXX-XXX-XXX-XXX",
      "content":[
        {
          "type":"command",
          "operation":"LABEL",
          "parameters":"[{\"labelName1\": [\"labelValue1\"]},{\"labelName2\": [\"labelValue1\",\"labelValue2\"]}]"
        }
      ]
    }
    

    Available Bot Commands

    Command Parameters Description
    BAN none Temporarily bans the visitor.
    BAN_IP none Permanently bans the visitor.
    BYE none Ends the chat.
    GOTO url Redirects the visitor to a different URL.
    TRANSFER Agent Email Transfers chat to a specific agent.
    HUMAN_TRANSFER none Transfers chat to any human agent on the same widget.
    LABEL A map of label names to one or more label values Sets the label for the current chat
    TAG_TRANSFER Widget ID and an array of tags Transfers chat to a group of agents (including bots) to which the corresponding tags are assigned.
    WIDGET_TRANSFER Widget ID Transfers chat to a different widget.
    WIDGET_HUMAN_TRANSFER Widget ID Transfers chat a human on a different widget.

    Command Execution Result

    When a transfer command fails, SnapEngage will send a POST request with a command execution result payload to the developer's endpoint.

    Sample Command Execution Result Payload

    {
      "widget_id": "XXX-XXX-XXX-XXX",
      "case_id": "XXX-XXX-XXX-XXX",
      "timestamp": 1573467739035,
      "event": "commandResult",
      "failedCommands": [
        {
          "operation": "WIDGET_TRANSFER",
          "params": "XXX-XXX-XXX-XXX",
          "error": "NO_AGENTS_AVAILABLE"
        }
      ]
    }
    

    List Of Errors

    Error Description
    MISSING_PARAM Command parameter is missing.
    WIDGET_NOT_FOUND Destination widget of transfer is not found.
    TRANSFER_NOT_ALLOWED Transfer to the destination widget is not allowed.
    NO_AGENTS_AVAILABLE Destination widget of transfer is offline.

    Conversation Events API

    The SnapEngage Conversation Events API allows developers to be notified of below conversation events from SnapEngage.

    1. Conversation Responded
    2. Conversation Closed
    3. Conversation Queued
    4. Conversation Assigned
    5. Conversation Broad Casted
    6. Conversation Labeled
    7. Conversation Transferred
    8. Conversation Surveyed

    Authentication for Conversation Events API

    An Authorization Token is an optional field that can be received along with conversation events from SnapEngage. If authentication is desired, simply enter your own custom API token inside the "Authentication Token" field of the Conversation Events API settings in the Admin Dashboard. (See below for navigation instructions). This token will then be delivered as a Header in the POST request data. You will need to use this same API token inside the endpoint where you receive conversation events from SnapEngage. See Receive conversation events from SnapEngage for more details.

    How to activate the Conversation Events API

    In the SnapEngage Admin Dashboard, after selecting the appropriate widget, click "Settings" on the left menu. In the sub-menus at the top of the page, select "Integrations", and then select "Conversation Events API".

    Once you are done making changes, make sure to click the "Save" button.

    Agent Status API Authentication

    How to get different conversation events

    In snapengage admin dashboard, after enabling and configuring the conversation events api you can get notified on different events.

    Different conversation events

    Receive conversation events from SnapEngage

    In the event of a conversation (case) being responded to by an agent or closed, SnapEngage will send a POST request to the developer's endpoint URL. For information on where to enter the endpoint, and how to optionally authenticate, please see How to activate the Conversation Events API.

    Response Parameters

    Data Type Description
    widget_id String The id of the widget that the conversation event occurred on.
    case_id String The id of the conversation that the event occurred on.
    widget_name String The name of the widget that the case event occurred.
    agent_email String The id of the conversation that the event occurred on. Sent with events: "caseResponded" , "caseClosed", "caseAssigned", "caseBroadcasted", "caseLabeled", "caseTransferred", "caseSurveyed"
    agent_alias String The agent alias (name). Sent with Events: "caseResponded" , "caseClosed", "caseAssigned", "caseBroadcasted", "caseLabeled", "caseTransferred", "caseSurveyed"
    agent_id String The agent email address, which is prepended with "wc:".
    event String "caseResponded", "caseClosed", "caseQueued", "caseAssigned", "caseBroadcasted", "caseLabeled", "caseTransferred", "caseSurveyed".
    timestamp Long The timestamp which this event occurred. Timestamp is a unix epoch.
    label Object The label category and label value applied. Only sent on "caseLabeled" event.
    survey_score Integer The score that visitor left on agent survey. Only sent on "caseSurveyed" event.
    survey_comment String The comment that visitor left on agent survey. Only sent on "caseSurveyed" event.

    Sample Response JSON

    Click the JSON tab to the right to view a sample JSON response.

    {
        "widget_id": "beaa0150-5a54-4a58-96e1-cc7971239d75",
        "widget_name": "Paddy's Irish Pub",
        "case_id": "2e3362fc-b537-4a16-bd0b-4b5d4108c53d",
        "agent_id": "wc:[email protected]",
        "agent_email": "[email protected]",
        "agent_alias": "Charlie Boy",
        "event": "caseLabeled",
        "timestamp": 1551461879355,
        "label": {
            "value": "new chat",
            "name": "chatType"
        },
        "survey_score": 75,
        "survey_comment": "really helpful"
    }
    

    Success Response

    2xx Success

    Hub SDK

    The Hub SDK is a resource allowing the exchange of messages between the Hub and a customized application in an iframe embedded on Messaging’s Hub. With this SDK, developers can integrate applications into Agent Hub.

    With the Hub SDK, developers will find two-way communication means between the Agent Hub and external applications, providing information about the visitor and the conversation and sending conversation lines directly from the Hub.

    1. Introduction to Hub
    2. Chat Agent Actions: Transfer, Ban, and End Chat
    3. Auto-Translate
    4. Request email transcript

    How to activate Hub SDK

    In order to start using the HUB SDK, a new agent link needs to be added. To do this login to Admin Dashboard, navigate to Options tab and enable the option Display links to Chat Agents when chat starts

    Add a new persistent agent link with an URL, this URL would be used to communicate with the HUB.

    Add a new agent "persistant" link

    Read more here:

    1. CSP: frame-ancestors

    2. X-Frame-Options

    Send Events

    The Hub Software Development Kit (SDK) is a collection of front-End tools provided by TeamSupport Messaging product. It facilitates the communication between an iframe and the HUB through send and receive events.

    We are using window.postMessage()to send data to the iframe. On the iframe URL, an event listener on message should be configured.

    For attaching the listener on the window object you can use window.addEventListener().

    For more information read this window.addEventListener()

    window.addEventListener(
        "message",
        (event) => {
            if (event.origin !== "https://www.snapengage.com") return;
            console.log(event.data);
            // ...
            // Events are present inside event.data
            // You can use data inside event.data by assigning a variable
            // e.g.: let eventPayload = event.data
        },
        false
    );
    
    {
        origin:"https://snapengage.com",
        isTrusted: true,
        ....
        data: {
            "type": <conversation_event_type>
            "conversationId": <string>
            ....
        },
    };
    
    

    List of Send Events

    Click the JSON tab to the right to view a sample.

    {
      "type": conversation_started,
      "conversationId": string,
      "agentEmail": string,
      "data": {
         "type": "Text",
         "text": data.message,
         },
    }
    
    
    Event Description
    conversation_started A new conversation started. This explicitly looks at conversations started by visitors to agents. An event with the type "conversation_started" is sent. Limitation: The event does not trigger with bot started conversations - i.e. a site visitor interaction with a welcome message.
    {
      "type": name_captured,
      "conversationId": string,
      "agentEmail": string,
       "data": {
          "name": visitor_name
       }
    }
    
    Event Description
    name_captured Visitor’s name was captured. This is triggered when agent types ‘/name=visitor’s_name’. The name is sent in the event.
    {
      "type": agent_message_received,
      "conversationId": string,
      "agentEmail": string,
       "data": {
          message¹
       }
    }
    
    Event Description
    agent_message_received A new agent message was received by TeamSupport back-end. The message is sent in the event.
    {
      "type":  visitor_message_received,
      "conversationId": string,
      "agentEmail": string,
       "data": {
          message¹
       }
    }
    
    Event Description
    visitor_message_received A new visitor message was received by TeamSupport back-end. The message is sent in the event.
    {
      "type":  visitor_typing,
      "conversationId": string,
      "agentEmail": string,
       "data": {
          message¹
       }
    }
    
    Event Description
    visitor_typing A visitor is typing. If the “Sneak Peek” widget configuration is enabled, the event sends real-time typing (ie. the letters the visitor is typing). An event with the type “visitor_typing” is sent.
    {
      "type":  visitor_page_update,
      "conversationId": string,
      "agentEmail": string,
       "data": {
          "page": new URL
       }
    }
    
    Event Description
    visitor_page_update Visitor reloaded page or navigated to another page. The event sends reloaded or visited URL.
    {
      "type": conversation_closed_by_visitor,
      "conversationId": string,
    }
    
    Event Description
    conversation_closed_by_visitor Visitor disconnected conversation.
    {
      "type": phone_captured,
      "conversationId": string,
      "agentEmail": string,
       "data": {
          "phone": visitor_phone
       }
    }
    
    
    Event Description
    phone_captured A phone number was captured in a conversation. This is triggered when agent types ‘/phone=visitor’s_phone_number’. The phone number is sent in the event. Note: There is no validation on the phone number.
    {
      "type": email_captured,
      "conversationId": string,
      "agentEmail": string,
       "data": {
          "phone": visitor_email
       }
    }
    
    Event Description
    email_captured An email address was captured in a conversation. This is triggered when agent types ‘/email=visitor’s_email_address’. The email address is sent in the event.
    {
      "type": reclaim_transfer_request,
      "conversationId": string,
      "agentEmail": string,
    }
    
    Event Description
    reclaim_transfer_request The agent is reclaiming a conversation previously transferred to another agent or widget.
    {
      "type": request_file,
      "conversationId": string,
      "agentEmail": string,
    }
    
    Event Description
    request_file File from a visitor is requested.
    {
      "type": request_secure_data,
      "conversationId": string,
      "agentEmail": string,
       "data": {
          "secure_data_type": SSN|Credit Card|Secure Note
       }
    }
    
    
    Event Description
    request_secure_data Agent requests transfer of secured data. The event sends the type of secured data (SSN, Credit Card details and Secured Note). The secured data is not sent in the event.
    {
      "type": ban_user,
      "conversationId": string,
      "agentEmail": string,
    }
    
    
    Event Description
    ban_user The visitor was banned, this includes both commands \ban and \banip. This is an ACK payload.
    {
      "type": call_me,
      "conversationId": string,
      "agentEmail": string,
    }
    
    Event Description
    call_me Visitor requested a phone call.
    {
      "type": visitor_transcript_request,
      "conversationId": string,
      "agentEmail": string,
    }
    
    
    Event Description
    visitor_transcript_request Visitor requested the transcript.
    {
      "type": widget_changed,
      "conversationId": string,
      "agentEmail": string,
       "data": {
          "changed_widget": widget_name
       }
    }
    
    Event Description
    widget_changed Agent switched his active widget. The event sends the name of new widget.
    {
      "type": ignore,
      "conversationId": string,
      "agentEmail": string,
    }
    
    
    Event Description
    ignore An event with the type is sent stating that the transcript will not be sent to the CRM system. The default status is defined at widget settings
    {
      "type": record,
      "conversationId": string,
      "agentEmail": string,
    }
    
    
    Event Description
    record An event with the type is sent stating that the transcript will be sent to the CRM system. The default status is defined at widget settings.
    {
      "type": auto_translate_enabled,
      "conversationId": string,
      "agentEmail": string,
    }
    
    Event Description
    auto_translate_enabled Agent has turned on the Auto translate functionality.
    {
      "type": auto_translate_disabled,
      "conversationId": string,
      "agentEmail": string,
    }
    
    Event Description
    auto_translate_disabled Agent has turned off the Auto translate functionality.
    {
      "type": auto_translate_language_changed,
      "conversationId": string,
      "agentEmail": string,
    }
    
    
    Event Description
    auto_translate_language_changed Agent has changed the auto translation language.
    {
      "type": weather_info_captured,
      "conversationId": string,
      "agentEmail": string,
       "data": {
          "temperature_celsius":  °C,
          "temperature_fahrenheit":  °F,
          "description": weather description
       }
    }
    
    Event Description
    weather_info_captured After conversation starts, weather info is captured. The event sends temperature (C/F) and a short description.

    Sample JSON Response:

    Click the JSON tab to the right to view a sample.

    1.Text message
    "message": {
        "type": "text",
        "text": "some text",
    }
    
    2. File message
    "message": {
        "type": "File",
        "mimeType": "depending upon the configured type",
        "fileName": "file name",
        "url": "file uploaded URL",
        "mimeTypeUrl": "mimeType specification",
    }
    

    Receive Events

    Receive events are those going from the iframe to the Messaging Hub. Using the receive events you would be able to send the data to the Hub. This data can also contain the messages which can be send to visitor through Hub.

    We send data to the HUB by using the window.postMessage() javascript function.

    For more information upon window.postMessage. Please read the below documentation Window.postMessage() - Web APIs | MDN

    {
      let message =  {
      type: "agent_message_received",
      conversationId: "bce21499-50e4-4728-b5f8-6ed57e490bf2&d",
      agent: <email address of the signed in agent into the Hub>,
      data: {
          "message": "message from agent",
    },
       },
    
      // after having the message structure, finally you can make a call to send
      // the data to Hub
    
      window.parent.postMessage(message, "*");
    }
    
    1. message: This is a json / object which composes of the different details which needs to be passed to Hub.
    2. type: Type of event, you can find the different types of event in the below list.
    3. conversationId: conversationId which you have received from the send events. This conversationId is of a conversation which should be ongoing.
    4. agent: Agent email address. This email address is of the agent who is currently logged in into Hub. For e.g.: [email protected]
    5. data: This a json/object which has different components depending upon the event type.

    List of Receive Events

    Click the JSON tab to the right to view a sample.

    {
      "type": agent_message_received,
      "conversationId": string,
      "agent": "email address",
      "data": {
         "text": message_to_send
      }
    }
    
    Event Description
    agent_message_received Send a message on behalf of the Agent to the visitor.
    {
      "type": conversation_closed_by_agent,
      "conversationId": string,
      "agent": "email address",
    }
    
    
    Event Description
    conversation_closed_by_agent End the conversation on behalf of the Agent.
    {
      "type": label_added,
      "conversationId": string,
      "agent": "email address",
      "data": {
        "labelName": string,
        "freeForm": boolean,
        "value": string,
        }
    }
    
    Event Description
    label_added Add a label to conversation on behalf of the agent. A flag indicating if the label is of freeform type should be added
    {
      "type": label_removed,
      "conversationId": string,
      "agent": "email address",
       "data": {
          "labelName": string,
          "freeForm": boolean,
          "value": string,
       }
    }
    
    Event Description
    label_removed Remove a label to conversation on behalf of the agent. A flag indicating if the label is of freeform type should be added
    {
      "type": transfer_request,
      "conversationId": string,
      "agent": "email address",
       "data": {
          "widgetId": widget public Id to which the conversation should be transfered
       }
    }
    
    
    Event Description
    transfer_request Transfer the chat to another widget based on widget ID.
    {
      "type": reclaim_transfer_request,
      "conversationId": string,
      "agent": "email address",
    }
    
    Event Description
    reclaim_transfer_request Reclaim the chat back to the agent
    {
      "type": request_file,
      "conversationId": string,
      "agent": "email address",
    }
    
    Event Description
    request_file Request file from the visitor on behalf of the agent.
    {
      "type": request_secure_data,
      "conversationId": string,
      "agent": "email address",
       "data": {
          "secure_data_type": SSN|Credit Card|Secure Note
       }
    }
    
    
    Event Description
    request_secure_data Request secure data from the visitor on behalf of the agent.
    {
      "type": ban_user,
      "conversationId": string,
      "agent": "email address",
      "data": {
       "type": "cookie" or "IP",
     }
    }
    
    Event Description
    ban_user Ban the user on the behalf of the agent.Type says that we want to ban the users by either cookie or IP.
    {
      "type": populate_text,
      "conversationId": string,
      "agent": "email address",
      "data": {
       "message": "text to send",
     }
    }
    
    Event Description
    populate_text Populate the text area (agent composer) from a message in the iframe.

    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 Authorization Token is an optional field that can be received along with chat data from SnapEngage. If authentication is desired, simply enter your own custom API token inside the "Authentication Token" field of the setup page in the Admin Dashboard. (See below for navigation instructions). This token will then be delivered as a Header in the POST request data.

    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. Optionally, add an Authentication Token. If set the token will be included in "Authorization" the header. 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 2xx Success 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");
    

    Data Fields

    Click the JSON tab to the right to view sample response JSON.

    {
        "id": "8b7c3b3b-f5d7-4e58-96d8",
        "widget_id": "e8175843-d381-4d7c-aa9f-0da1610ad1b",
        "url": "https://www.snapengage.com/viewcase?c=8b7c3b3b-f5d7-4e58-96d8",
        "type": "chat",
        "requested_by": "[email protected]",
        "requester_details":
          {
            "name": "Jim Tester",
            "emails": ["[email protected]"],
            "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,
        "chat_ended_by": "agent",
        "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": "Hola, ",
            "translations": {
              "en": "Hello,"
            },
            "sender": "VISITOR"
          },
          {
            "id": "[email protected]",
            "date": "Oct 3, 2014 2:14:31 PM",
            "date_seconds": 1412367271,
            "date_milliseconds": 456,
            "alias": "test",
            "message": "Good day",
            "translations": {
              "es": "Buen día"
            },
            "sender": "AGENT"
          },
          {
            "id": "",
            "date": "Oct 3, 2014 2:14:31 PM",
            "date_seconds": 1412367271,
            "date_milliseconds": 835,
            "alias": "visitor",
            "message": "Esto es una prueba.",
             "translations": {
              "en": "This is a test."
            },
            "sender": "VISITOR"
          }
        ],
        "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>
      <requested_by><![CDATA[[email protected]]]></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>[email protected]</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>[email protected]</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 Deprecated URL pointing to the snapshot that is associated with the service request, if one was created. This is no longer a SnapEngage feature and is no longer returned as part of this API return data.
    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
    requester_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
    chat_ended_by String How the chat ended. Will either be "agent", "visitor", "timed_out" if the chat timed out due to no activity, or "no_agents_found" if no agents were available to respond to the chat. Note: This data is only available in the JSON return data.
    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
    ↳ translations JSON Object (transcripts) A map of message translations.
    ↳ sender String (transcripts) Types: "SYSTEM", "AGENT", "BOT", or "VISITOR". Note: This field is only available with the JSON integration.
    ↳↳ "{language_code}" String (translations) An ISO-639-1 language identifier.
    ↳↳ "{message_translation}" String (translations) Translation for message.
    plugins JSON Object Deprecated An array of plugin objects which detail any installed plugins within the initiators browser. This information is no longer collected and stored by SnapEngage, and is no longer returned as part of this API return data.
    ↳ name String Deprecated (plugins) Name of the plugin
    ↳ value String Deprecated (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

    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
    '[email protected] 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
    '[email protected] 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'
    

    Button Event

    The InlineButtonClicked event is fired when the visitor clicks on messages that are buttons.

    SnapEngage.setCallback('InlineButtonClicked', function(options) {
        console.log('A visitor clicked on a bot button sent from ' + options.botName);
        console.log('And the button label was: ' + options.buttonLabel);
        console.log('And the button value was: ' + options.buttonValue);
    });
    

    Parameter values

    Parameter Type Description
    options object Object containing information about the button that got clicked

    Options object

    Property name Type Description
    botName string Bot name (alias) that sent button message
    buttonLabel string Label of the button
    buttonValue string Value of the button

    ChatEnded Event

    The ChatEnded event fires when the chat ends. If your widget has chat survey enabled or any other post chat feature, this event is fired at the same time the post chat flow starts.

    SnapEngage.setCallback(SnapEngage.callbacks.CHAT_ENDED, function(options) {
        console.log('Who has ended the chat?');
        console.log(options.endedByUser ? "Visitor" : "Agent or the System");
    });
    

    Parameter values

    Parameter Type Description
    options object An object containing options

    Options object

    Property Type Description
    endedByUser boolean Whether the user has ended the chat or not

    Rating Prompt Clicked Event

    SnapEngage.setCallback('RatingPromptClicked', function (botAlias, scaleType, selectedOption) {
        console.log('botAlias: ' + botAlias);
        console.log('scaleType: ' + scaleType);
        console.log('selectedOption: ' + selectedOption);
    });
    

    The RatingPromptClicked event is fired when the rating prompt is clicked on the visitor side.

    This callback can return three pieces of info: botAlias of agent the visitor is interacting with, the scaleType of the rating, and the selectedOption as a number.

    Parameter values

    Parameter Type Description
    Function Function This callback function accepts two optional parameters: botAlias, scaleType, and selectedOption. Inside the anonymous function, you can check the returned value of the botAlias, scaleType, and selectedOption parameters.
    botAlias String The agent alias the visitor is interacting with.
    scaleType String The scale type, NUMBER or STAR.
    selectedOption Number The rate selected by the visitor.

    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()

    DEPRECATEDThis API has been deprecated as of Oct 8th, 2019.

    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?';
    
    // Regular chat box
    var minimizedView = false; 
    
    // Call the API with the above parameters
    SnapEngage.openProactiveChat(forced, offlineFallback, message, minimizedView);
    

    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 can also set a first message for the Proactive Chat. Otherwise the Proactive Chat message will fall back to the first available message from the Proactive Chat configuration of the widget. 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?"
    minimizedView boolean Should the visitor be prompted with the minimized Proactive Chat invite? See here for more info on minimized Proactive Chat. When no programmatic message is set in this prompt, the previous parameter should be set to 'undefined'.

    .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 = '[email protected]';
    
    // 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);
    

    This API will do three things:

    First, it pre-populates the 'email' field on your prechat or offline form (if this field exists).

    Second, this API will provide a visitor’s email address to an agent who takes the chat. The email gets stored on the conversation (case) and will be passed to your integration at the close of the case.

    Third, on submit of a prechat or offline form, a cookie will be stored in the visitor's browser called 'SnapABugUserEmail' to repeat this same behavior on future chats. Read more about the SnapABugUserEmail cookie here.

    Parameters

    Parameter Type Description
    email String A non-encoded email address, for example, '[email protected]'. 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);
    

    This API will do four things:

    First, it pre-populates the 'name' field on your prechat or offline form (if this field exists).

    Second, it updates the visitor alias that is displayed in the chatbox chat transcript.

    Third, this API will provide the visitor’s name to the agent who takes the chat. If the user's email is known, SnapEngage will update the database contact with this name (note: see green box below).

    Fourth, this API stores a cookie in the visitor's browser called 'SnapABugUserAlias'1 to repeat this same behavior on future chats. Read more about the SnapABugUserAlias cookie here.

    1 This cookie was previously known as the 'SnapABugUserName' cookie which is now deprecated.

    Parameters

    Parameter Type Description
    name String A non-encoded name, for example, Arya Stark. 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 Required. 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 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);
    

    .endChat()

    var options = { closeChatBox: true };
    SnapEngage.endChat(options);
    

    Forces chat to end.

    Parameters

    Parameter Type Description
    options object An object containing options

    Options object

    property Type Description
    closeChatBox boolean Whether to close or not chat box

    Returns

    Type Description
    void this method doesn't return anything

    Example endChat() Usage

    Force chat box to close when a chat ends.

    var event = SnapEngage.callbacks.CHAT_ENDED;
    function callback() {
      SnapEngage.endChat({ closeChatBox: true });
    }
    SnapEngage.setCallback(event, callback);
    

    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.

    Sample API response

    Click the JSON tab to the right to view sample response JSON.

    {
        "cases": [
            {
                "id": "a7e91ae8-d4f4-4990-9da6-3b41fe072cc9",
                "url": "https://www.snapengage.com/viewcase?c=a7e91ae8-d4f4-4990-9da6-3b41fe072cc9",
                "type": "chat",
                "requested_by": "[email protected]",
                "requester_details": {
                    "name": "George",
                    "emails": ["[email protected]"],
                    "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_responded": true,
                "chat_agent_id": "wc:[email protected]",
                "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:[email protected]",
                        "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:[email protected]",
                "visitor_transcript_email": "[email protected]"
            }
        ],
        "linkToNextSetOfResults": ""
    }
    

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

    visitor_transcript_email You will see this field returned if a widget has the visitor email transcript feature enabled, and if the visitor has chosen to submit an email address to receive an email copy of their chat transcript.

    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

    Mobile SDK

    SnapEngage mobile SDK for Android and iOS.

    Please see the below code samples and links to our github repository.

    Mobile Android SDK

    To explore Android SDK and to see the examples you can go to our android-sdk github repository

    Install the Android SDK using Gradle Package manager, by copying the following line into the app module’s build.gradle file:

    implementation "com.chat:sdk:0.4"

    Use the following until final release

    implementation project(path: ':library')

    To see the code samples please click the JAVA tab to the right

    Instantiate a ChatView from code or layout XML file
    ChatView chatView = new ChatView(context, null);
    
    Configure the ChatView

    Create a Chat.Configuration object with your parameters. The constructor supports an optional parameter called customVariables.

    String provider = "SnapEngage”;
    String jsUrl = "https://yourdomain.com/yourjslocation.js";
    String entryPageUrl = "https://yourdomain.com/";
    CustomVariables customVariables = CustomVariables()
        .put("accountNumber", 123456)
        .put("customerSince", "December 1, 2016");
    Chat.Configuration config = new Chat.Configuration(
    provider, jsUrl, entryPageUrl, customVariables);
    
    
    Set up the chatView with the configuration:
    chatView.setConfiguration(config)
    
    Register callbacks

    You can observe several events of the SnapEngage chat by adding a listener to your chatView. You can add several listeners to the same event. for example:

    CloseEventListener closeListener = new CloseEventListener() {
      @Override
      public void onClose(@Nullable String type, @Nullable String status) {
           Log.d("ChatView", "onCloseEvent triggered");
       }
    });
    chatView.addCloseListener(closeListener);
    
    You can also remove a listener:
    chatView.removeCloseListener(closeListener);
    

    To explore more click here

    Mobile iOS SDK

    To explore SDK and also to see the examples you can go to our ios-sdk github repository

    To see the code samples please click the SWIFT tab to the right

    Install the SDK using CocoaPods, by copying the following line in the Podfile:
    pod 'SnapEngageSDK'
    
    To install the SDK with Carthage, add the following line to your Cartfile.
    github "SnapEngage/mobilesdk-ios" ~> 1.0 
    
    Import the SnapEngageSDK to your swift file:
    import SnapEngageSDK
    
    Instantiate a ChatView from code or StoryBoard:
    let SnapEngageChat = ChatView()
    
    Configure the ChatView

    Create a ChatConfiguration object with your parameters. The constructor supports an optional parameter called customVariables.

    SnapEngageChat.setConfiguration(
        ChatConfiguration(
            widgetId: "8e01c706-fb83-42b6-a96e-ec03bf2cab5c", 
            baseJsUrl: URL(string: "https://storage.googleapis.com/code.snapengage.com/js")!, 
            provider: "SnapEngage", 
            entryPageUrl: URL(string: "https://example.com")!, 
            baseInstanceUrl: URL(string: "https://www.snapengage.com/public/api/v2/chat")!, 
            customVariables: [
                "name" : "Kerim"
            ]
        )
     )
    
    Register callbacks

    You can observe several events of the SnapEngage chat by adding a listener to your chatView. You can add several listeners to the same event. for example:

    SnapEngageChat.add(closeListener: self)
    extension MyViewController: CloseEventListener {
        func onClose(type: String?, status: String?) {
            print("Chat closed")
        }
    }
    
    You can also remove a listener:
    SnapEngageChat.remove(closeListener: self)
    

    To explore more click here

    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 key is required to use the Provisioning REST API. This key must be obtained by emailing [email protected].

    Users

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

    Create a new user account

    To create a new user account, PUT to the endpoint with your API key as a parameter and the request payload below. You can also create account from existing account template.

    PUT /api/v1/user.json?api_key={api_key}
    

    Request Parameters

    To view sample request JSON, see the JSON tab to the right.

    {
        "email": "[email protected]",
        "name": "Jimbo Something",
        "password": "12345",
        "phone": "555-617-8980",
        "accountType": "enterprise"
    }
    
    Data Type Description
    email String Required. A valid email address less than 100 characters. All characters will be converted to lowercase which is how the user will need to log in.
    name String Required. A valid name less than 100 characters.
    accountType String Required. Requires specific values that are case-sensitive, see the table below of "accountType values".
    password String Required. A valid password that is 5-99 characters.
    phone String A valid phone number.
    templateId String You can create a new account from existing account. If you pass the template id then accountType won't be considered and account type from the template account will be used.

    accountType values

    To learn more about account types, see our pricing page.

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

    Sample Request

    To view an example request, click one of the language tabs on the right.

    curl -X PUT \
      'https://www.snapengage.com/api/v1/user.json?api_key={api_key}' \
      -H 'Content-Type: application/json' \
      -d '{
        "email" : "{user_email}",
        "name" : "Jimbo Something",
        "password" : "12345",
        "phone" : "555-617-8980",
        "accountType" : "enterprise"
        }'
    
    package com.snapengage.samples;
    
    import javax.ws.rs.client.ClientBuilder;
    import javax.ws.rs.client.Entity;
    import javax.ws.rs.client.WebTarget;
    import javax.ws.rs.core.MediaType;
    import javax.ws.rs.core.Response;
    
    public class Example {
    
      private static final String apiKey = "{api_key}";
    
      public static void main(String[] args) {
        SnapEngageUser snapEngageUser = new SnapEngageUser("{user_email}", "Jimbo Something",
            "enterprise", "12345", "555-617-8980");
    
        WebTarget webTarget = ClientBuilder.newBuilder().build()
            .target("https://www.snapengage.com/api/v1/user.json?api_key=" + apiKey);
    
        Response response =
            webTarget.request().put(Entity.entity(snapEngageUser, MediaType.APPLICATION_JSON));
    
        SnapEngageUser responseUser = response.readEntity(SnapEngageUser.class);
    
        System.out.println(responseUser.toJson());
      }
    }
    
    // Note: This object is used in all of the Java code samples for the (User) Provisioning API.
    package com.snapengage.samples;
    
    import com.google.gson.Gson;
    
    public class SnapEngageUser {
      private String email;
      private String name;
      private String accountType;
      private String password;
      private String phone;
    
      public SnapEngageUser() {
        // no-args constructor required for json serialization/de-serialization
      }
    
      public SnapEngageUser(String email, String name, String accountType, String password,
        String phone) {
        this.email = email;
        this.name = name;
        this.accountType = accountType;
        this.password = password;
        this.phone = phone;
      }
    
      public String getEmail() {
        return email;
      }
    
      public void setEmail(String email) {
        this.email = email;
      }
    
      public String getName() {
        return name;
      }
    
      public void setName(String name) {
        this.name = name;
      }
    
      public String getAccountType() {
        return accountType;
      }
    
      public void setAccountType(String accountType) {
        this.accountType = accountType;
      }
    
      public String getPassword() {
        return password;
      }
    
      public void setPassword(String password) {
        this.password = password;
      }
    
      public String getPhone() {
        return phone;
      }
    
      public void setPhone(String phone) {
        this.phone = phone;
      }
    
      public String toJson() {
        return new Gson().toJson(this);
      }
    }
    
    import requests
    
    url = "https://www.snapengage.com/api/v1/user.json"
    
    querystring = {"api_key": "{api_key}"}
    
    payload = '{"email" : "{user_email}", "name" : "Jimbo Something", "password" : "12345",' \
              '"phone" : "555-617-8980", "accountType" : "enterprise"}'
    
    response = requests.request("PUT", url, data=payload, params=querystring)
    
    print(response.text)
    

    Response Parameters

    To view sample response JSON, see the JSON tab to the right.

    {
        "email": "[email protected]",
        "name": "Jimbo Something",
        "phone": "555-617-8980",
        "accountType": "enterprise"
    }
    
    Data Type Description
    email String The user's email address. All characters will be converted to lowercase.
    name String The user's name.
    phone String The user's telephone number.
    accountType String The user's accountType. See "accountType values" table above.

    Success Response

    201 Created

    Get user account details or check if user exists

    To get a new user account or check if it exists, GET to the endpoint with your API key and the user email address as parameters.

    GET /api/v1/user.json?api_key={api_key}&email={user_email}
    

    Request Parameters

    Data Type Description
    email String Required. A valid email address of an existing user. All characters will be converted to lowercase which is how the user will need to log in.

    Sample Request

    To view an example request, click one of the language tabs on the right.

    curl -X GET 'https://www.snapengage.com/api/v1/user.json?api_key={api_key}&email={user_email}'
    
    package com.snapengage.samples;
    
    import javax.ws.rs.client.ClientBuilder;
    import javax.ws.rs.client.Entity;
    import javax.ws.rs.client.WebTarget;
    import javax.ws.rs.core.MediaType;
    import javax.ws.rs.core.Response;
    
    public class Example {
    
      private static final String apiKey = "{api_key}";
    
      public static void main(String[] args) {
        String email = "{user_email}";
    
        WebTarget webTarget = ClientBuilder.newBuilder().build().target(
          "https://www.snapengage.com/api/v1/user.json?api_key=" + apiKey + "&email=" + email);
    
        Response response = webTarget.request().get();
    
        SnapEngageUser responseUser = response.readEntity(SnapEngageUser.class);
    
        System.out.println(responseUser.toJson());
      }
    }
    
    import requests
    
    url = "https://www.snapengage.com/api/v1/user.json"
    
    querystring = {"api_key": "{api_key}", "email": "{user_email}"}
    
    response = requests.request("GET", url, params=querystring)
    
    print(response.text)
    
    

    Response Parameters

    To view sample response JSON, see the JSON tab to the right.

    {
        "email": "[email protected]",
        "name": "Jimbo Something",
        "phone": "555-617-8980",
        "accountType": "enterprise"
    }
    
    Data Type Description
    email String The user's email address. All characters will be converted to lowercase.
    name String The user's name.
    phone String The user's phone number.
    accountType String The user's accountType. See "accountType values" table above.

    Success Response

    200 OK

    Update an existing user account

    To update an existing user account, POST to the endpoint with your API key as a parameter and the request payload below.

    POST /api/v1/user.json?api_key={api_key}
    

    Request Parameters

    To view sample request JSON, see the JSON tab to the right.

    {
        "email": "[email protected]",
        "name": "Jimbo Something",
        "password": "12345",
        "phone": "555-617-8980",
        "accountType": "enterprise"
    }
    
    Data Type Description
    email String Required. A valid email address of an existing user. All characters will be converted to lowercase which is how the user will need to log in.
    name String Required. A valid name less than 100 characters.
    accountType String Requires specific values that are case-sensitive, see the table above of "accountType values".
    password String A valid password that is 5-99 characters.
    phone String A valid phone number.

    Sample Request

    To view an example request, click one of the language tabs on the right.

    curl -X POST \
      'https://www.snapengage.com/api/v1/user.json?api_key={api_key}' \
      -H 'Content-Type: application/json' \
      -d '{
        "email" : "{user_email}",
        "name" : "Jimbo Something",
        "password" : "12345",
        "phone" : "555-617-8980",
        "accountType" : "enterprise"
        }'
    
    package com.snapengage.samples;
    
    import javax.ws.rs.client.ClientBuilder;
    import javax.ws.rs.client.Entity;
    import javax.ws.rs.client.WebTarget;
    import javax.ws.rs.core.MediaType;
    import javax.ws.rs.core.Response;
    
    public class Example {
    
      private static final String apiKey = "{api_key}";
    
      public static void main(String[] args) {
        SnapEngageUser snapEngageUser = new SnapEngageUser("{user_email}", "Jimbo Something",
            "prem", "12345", "555-617-8980");
    
        WebTarget webTarget = ClientBuilder.newBuilder().build()
            .target("https://www.snapengage.com/api/v1/user.json?api_key=" + apiKey);
    
        Response response =
            webTarget.request().post(Entity.entity(snapEngageUser, MediaType.APPLICATION_JSON));
    
        SnapEngageUser responseUser = response.readEntity(SnapEngageUser.class);
    
        System.out.println(responseUser.toJson());
      }
    }
    
    import requests
    
    url = "https://www.snapengage.com/api/v1/user.json"
    
    querystring = {"api_key": "{api_key}"}
    
    payload = '{"email" : "{user_email}", "name" : "Jimbo Something", "password" : "12345", "phone" : "555-617-8980", ' \
              '"accountType" : "prem"}'
    
    response = requests.request("POST", url, data=payload, params=querystring)
    
    print(response.text)
    
    

    Response Parameters

    To view sample response JSON, see the JSON tab to the right.

    {
        "email": "[email protected]",
        "name": "Jimbo Something",
        "phone": "555-617-8980",
        "accountType": "enterprise"
    }
    
    Data Type Description
    email String The user's email address. All characters will be converted to lowercase which is how the user will need to log in.
    name String The user's name.
    accountType String The user's accountType. See "accountType values" table above.
    phone String The user's phone number.

    Success Response

    200 OK

    Delete an existing user account

    To delete a user account, DELETE to the endpoint with your API key and the user email as parameters.

    DELETE /api/v1/user.json?api_key={api_key}&email={user_email}
    

    Request Parameters

    Data Type Description
    email String Required. A valid email address of an existing user (less than 100 characters). All characters will be converted to lowercase.

    Sample Request

    To view an example request, click one of the language tabs on the right.

    curl -X DELETE 'https://www.snapengage.com/api/v1/user.json?api_key={api_key}&email={user_email}'
    
    package com.snapengage.samples;
    
    import javax.ws.rs.client.ClientBuilder;
    import javax.ws.rs.client.Entity;
    import javax.ws.rs.client.WebTarget;
    import javax.ws.rs.core.MediaType;
    import javax.ws.rs.core.Response;
    
    public class Example {
    
      private static final String apiKey = "{api_key}";
    
      public static void main(String[] args) {
        WebTarget webTarget = ClientBuilder.newBuilder().build().target(
          "https://www.snapengage.com/api/v1/user.json?api_key=" + apiKey + "&email={user_email}");
    
        webTarget.request().delete();
      }
    }
    
    import requests
    
    url = "https://www.snapengage.com/api/v1/user.json"
    
    querystring = {"api_key": "{api_key}", "email": "{user_email}"}
    
    response = requests.request("DELETE", url, params=querystring)
    
    print(response.text)
    
    

    Response Parameters

    No response payload is returned.

    Success Response

    200 OK

    Widgets

    The Provisioning REST API allows you to create a SnapEngage widget, get widget details, update, and delete widgets.

    Create a new widget

    PUT /api/v1/widget.json?api_key={api_key}
    

    Request Parameters

    To view sample request JSON, see the JSON tab to the right.

    {
        "email": "[email protected]",
        "destinationEmail": "[email protected]",
        "name": "Widget #1",
        "agents": [
            {
                "agentId": "[email protected]",
                "agentAlias": "An Agent",
                "agentAvatar": "https://www.website.com/charlie.png",
                "agentType": "webclient"
            }
        ],
        "enableProactiveChat": "true",
        "enableConversations": true,
        "conversationSchedule": {
            "timeZone": "US/Mountain",
            "schedules": [
                {
                    "dayOfWeek": "MONDAY",
                    "enabled": true,
                    "scheduleList": ["8:00 AM","5:00 PM"]
    
                },
                {
                    "dayOfWeek": "TUESDAY",
                    "enabled": true,
                    "scheduleList": ["8:00 AM","5:00 PM"]
                }
            ]
        }
    }
    
    Data Type Description
    email String Required. An existing user account email address. All characters will be converted to lowercase.
    name String A valid widget name less than 100 characters.
    destinationEmail String The email where transcripts are sent.
    agents List Required. At least one agent is required. Each agent must contain the below fields (agentId, agentAlias, agentAvatar, agentType).
    ↳ agentId String Required. The agent ID. All characters will be converted to lowercase which is how the user will need to log in.
    ↳ 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 Deprecated Link to an online button image. This field has been deprecated due to it being part of the now-deprecated legacy chat design. Any value passed will be ignored and this field will remain null on the widget.
    offlineButtonUrl String Deprecated Link to an offline button image. This field has been deprecated due to it being part of the now-deprecated legacy chat design. Any value passed will be ignored and this field will remain null on the widget.
    enableProactiveChat String If true proactive chat is enabled for the widget. If false it is not.
    enableConversations boolean If true chat is enabled for the widget. If false it is not.
    proactiveSettings String Deprecated May contain the below fields (delayInSec, message). This field has been deprecated due to it being part of the now-deprecated Proactive Chat V1 settings. Any value passed will be ignored and this field will be null on the widget. All widgets created using this endpoint will be given default Proactive Chat V2 settings.
    ↳ delayInSec String Deprecated The time in seconds to delay a proactive invitation. Default is 45. This field has been deprecated for the same reason as stated above (see 'proactiveSettings'). Any value passed will be ignored and this field will be null on the widget.
    ↳ message String Deprecated The proactive message to display. This field has been deprecated for the same reason as stated above (see 'proactiveSettings'). Any value passed will be ignored and this field will be null on the widget.
    conversationSchedule Json This will contain the schedule for the conversations.
    ↳ timeZone String Time zone for the hours of operation. example ("Europe/Berlin", "UTC", "Asia/Kolkata")
    ↳ schedules List List of schedule(s). This will contain the properties (dayOfWeek, enabled, scheduleList). Note that there can be multiple entries for a given day to accomodate for things like lunch hours, day and evening shifts, etc.
    ↳↳ dayOfWeek String Represents the days of the schedule. Available values for are MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY.
    ↳↳ enabled boolean If true this time period will be evalulated.
    ↳↳ scheduleList List Start and end time using h:mm AM/PM format

    agentType values

    accountType Value
    Hub User 'webclient'
    GChat User (Deprecated) 'google'
    Skype User (Deprecated) 'skype'

    Sample Request

    To view an example request, click one of the language tabs on the right.

    curl -X PUT \
      'https://www.snapengage.com/api/v1/widget.json?api_key={api_key}' \
      -H 'Content-Type: application/json' \
      -d '{
       "email": "[email protected]",
       "destinationEmail": "[email protected]",
       "name": "Widget #1",
       "agents":[
          {
             "agentId": "[email protected]",
             "agentAlias": "A New Agent",
             "agentAvatar": "https://www.website.com/a_new_agent_avatar.png",
             "agentType": "webclient"
          }
       ],
       "enableProactiveChat": "true",
       "enableConversations": true,
       "conversationSchedule": {
            "timeZone": "US/Mountain",
            "schedules": [
                {
                    "dayOfWeek": "MONDAY",
                    "enabled": true,
                    "scheduleList": ["9:00 AM","12:00 PM"]
    
                },
                {
                    "dayOfWeek": "MONDAY",
                    "enabled": true,
                    "scheduleList": ["1:00 PM","5:00 PM"]
                }
            ]
         }
      }'
    
    package com.snapengage.samples.widget;
    
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    
    import javax.ws.rs.client.ClientBuilder;
    import javax.ws.rs.client.Entity;
    import javax.ws.rs.client.WebTarget;
    import javax.ws.rs.core.MediaType;
    import javax.ws.rs.core.Response;
    
    public class WidgetExample {
    
      private static final String apiKey = "{api_key}";
    
      public static void main(String[] args) {
        List<SnapEngageAgent> agentList = new ArrayList<>();
        agentList.addAll(Arrays.asList(
            new SnapEngageAgent("12345", "Jimbo", "https://www.website.com/jimbo.png", "webclient")));
    
        SnapEngageWidget snapEngageWidget =
            new SnapEngageWidget("{user_email}", "Jimbo's Widget", "{user_email}", agentList, true);
    
        WebTarget webTarget = ClientBuilder.newBuilder().build()
            .target("https://www.snapengage.com/api/v1/widget.json?api_key=" + apiKey);
    
        Response response =
            webTarget.request().put(Entity.entity(snapEngageWidget, MediaType.APPLICATION_JSON));
    
        SnapEngageWidget responseWidget = response.readEntity(SnapEngageWidget.class);
    
        System.out.println(responseWidget.toJson());
      }
    }
    
    // Note: This object is used in all of the Java code samples for the (Widget) Provisioning API.
    package com.snapengage.samples.widget;
    
    import java.util.List;
    
    import com.google.gson.Gson;
    
    public class SnapEngageWidget {
      private String email;
      private String name;
      private String destinationEmail;
      private List<SnapEngageAgent> agents;
      private String uuid;
      private boolean enableProactiveChat;
    
      public SnapEngageWidget() {
        // no-args constructor required for json serialization/de-serialization
      }
    
      public SnapEngageWidget(String email, String name, String destinationEmail, List<SnapEngageAgent> agents,
        boolean enableProactiveChat) {
        this.email = email;
        this.name = name;
        this.destinationEmail = destinationEmail;
        this.agents = agents;
        this.enableProactiveChat = enableProactiveChat;
      }
    
      public String getEmail() {
        return email;
      }
    
      public void setEmail(String email) {
        this.email = email;
      }
    
      public String getName() {
        return name;
      }
    
      public void setName(String name) {
        this.name = name;
      }
    
      public String getDestinationEmail() {
        return destinationEmail;
      }
    
      public void setDestinationEmail(String destinationEmail) {
        this.destinationEmail = destinationEmail;
      }
    
      public List<SnapEngageAgent> getAgents() {
        return agents;
      }
    
      public void setAgents(List<SnapEngageAgent> agents) {
        this.agents = agents;
      }
    
      public boolean getEnableProactiveChat() {
        return enableProactiveChat;
      }
    
      public void setEnableProactiveChat(boolean enableProactiveChat) {
        this.enableProactiveChat = enableProactiveChat;
      }
    
      public String getUuid() {
        return uuid;
      }
    
      public void setUuid(String uuid) {
        this.uuid = uuid;
      }
    
      public String toJson() {
        return new Gson().toJson(this);
      }
    }
    
    import requests
    
    url = "https://www.snapengage.com/api/v1/widget.json"
    
    querystring = {"api_key": "{api_key}"}
    
    payload = '{ "email" : "[email protected]", "destinationEmail" : "[email protected]", "name" : "A New Widget!",' \
              '"agents" : [{ "agentId" : "[email protected]", "agentAlias" : "A New Agent",' \
              '"agentAvatar" : "https://www.website.com/a_new_agent_avatar.png", "agentType" : "webclient" }],' \
              '"enableProactiveChat" : "true"}'
    
    response = requests.request("PUT", url, data=payload, params=querystring)
    
    print(response.text)
    

    Response Parameters

    To view sample response JSON, see the JSON tab to the right.

    {
        "name": "Widget #1",
        "email": "[email protected]",
        "destinationEmail": "[email protected]",
        "uuid": "31a11b98-ffd2-425d-aa69-2c6ff8a40a16",
        "agents": [
            {
                "agentId": "wc:[email protected]",
                "agentAlias": "A New Agent",
                "agentAvatar": "https://www.website.com/a_new_agent_avatar.png",
                "agentType": "webclient"
            }
        ],
        "enableProactiveChat": "true",
        "enableConversations": true
    }
    
    Data Type Description
    name String The widget name.
    email String The user account email address. All characters will be converted to lowercase.
    destinationEmail String The email where transcripts are sent.
    uuid String The widget id.
    agents List The list of agent(s) on this widget. Each agent includes the below fields (agentId, agentAlias, agentAvatar, agentType).
    ↳ agentId String The agent ID. All characters will be converted to lowercase.
    ↳ agentAlias String The agent displayed name.
    ↳ agentAvatar String Link to an agent image.
    ↳ agentType String See table of "agentType values" below.
    enableProactiveChat String If true proactive chat is enabled for the widget. If false it is not.

    Success Response

    201 Created

    Get widget details

    To get widget's details, GET to the endpoint with your API key, the widget id, and the user email address as parameters.

    GET /api/v1/widget.json?api_key={api_key}&uuid={widget_id}&email={user_email}
    

    Request Parameters

    Data Type Description
    uuid String Required. The widget public Id.
    email String Required. The user email associated with this widget. All characters will be converted to lowercase.

    Sample Request

    To view an example request, click one of the language tabs on the right.

    curl -X GET \
      'https://www.snapengage.com/api/v1/widget.json?api_key={api_key}&uuid=31a11b98-ffd2-425d-aa69-2c6ff8a40a16&[email protected]'
    
    package com.snapengage.samples.widget;
    
    import javax.ws.rs.client.ClientBuilder;
    import javax.ws.rs.client.Entity;
    import javax.ws.rs.client.WebTarget;
    import javax.ws.rs.core.MediaType;
    import javax.ws.rs.core.Response;
    
    public class WidgetExample {
    
      private static final String apiKey = "{api_key}";
    
      public static void main(String[] args) {
        WebTarget webTarget = ClientBuilder.newBuilder().build()
            .target("https://www.snapengage.com/api/v1/widget.json?api_key=" + apiKey +
            "&uuid={widget_id}&email={user_email}");
    
        Response response = webTarget.request().get();
    
        SnapEngageWidget responseWidget = response.readEntity(SnapEngageWidget.class);
    
        System.out.println(responseWidget.toJson());
      }
    }
    
    import requests
    
    url = "https://www.snapengage.com/api/v1/widget.json"
    
    querystring = {"api_key" : "{api_key}", "uuid" : "31a11b98-ffd2-425d-aa69-2c6ff8a40a16", "email" : "[email protected]"}
    
    response = requests.request("GET", url, params=querystring)
    
    print(response.text)
    

    Response Parameters

    To view sample response JSON, see the JSON tab to the right.

    {
        "name": "Widget #1",
        "email": "[email protected]",
        "destinationEmail": "[email protected]",
        "uuid": "31a11b98-ffd2-425d-aa69-2c6ff8a40a16",
        "agents": [
            {
                "agentId": "wc:[email protected]",
                "agentAlias": "A New Agent",
                "agentAvatar": "https://www.website.com/a_new_agent_avatar.png",
                "agentType": "webclient"
            }
        ],
        "enableProactiveChat": "true"
    }
    
    Data Type Description
    name String The widget name.
    email String The user account email address. All characters will be converted to lowercase.
    destinationEmail String The email where transcripts are sent.
    uuid String The widget id.
    agents List The list of agent(s) on this widget. Each agent includes the below fields (agentId, agentAlias, agentAvatar, agentType).
    ↳ agentId String The agent ID. All characters will be converted to lowercase.
    ↳ agentAlias String The agent displayed name.
    ↳ agentAvatar String Link to an agent image.
    ↳ agentType String See table of "agentType values" below.
    enableProactiveChat String If true proactive chat is enabled for the widget. If false it is not.

    Success Response

    200 OK

    Update an existing widget

    To update an existing widget, POST to the endpoint with your API key as a parameter and the request payload below.

    POST /api/v1/widget.json?api_key={api_key}
    

    Request Parameters

    To view sample request JSON, see the JSON tab to the right.

    {
        "email": "[email protected]",
        "destinationEmail": "[email protected]",
        "name": "Widget #1 - Sales Widget",
        "uuid": "31a11b98-ffd2-425d-aa69-2c6ff8a40a16",
        "agents": [
            {
                "agentId": "[email protected]",
                "agentAlias": "A New Agent",
                "agentAvatar": "https://www.website.com/a_new_agent_avatar.png",
                "agentType": "webclient"
            }
        ],
        "enableProactiveChat": "false",
        "enableConversations": true,
        "conversationSchedule": {
            "timeZone": "US/Mountain",
            "schedules": [
                {
                    "dayOfWeek": "MONDAY",
                    "enabled": true,
                    "scheduleList": ["9:00 AM","12:00 PM"]
    
                },
                {
                    "dayOfWeek": "MONDAY",
                    "enabled": true,
                    "scheduleList": ["1:00 PM","5:00 PM"]
                }
            ]
        }
    }
    
    Data Type Description
    email String Required. An existing user account email address. All characters will be converted to lowercase.
    uuid String Required. The id of the widget to be updated.
    name String A valid widget name less than 100 characters.
    destinationEmail String The email where transcripts are sent
    agents List Required. At least one agent is required. Each agent must contain the below fields (agentId, agentAlias, agentAvatar, agentType).
    ↳ agentId String Required. The agent ID. All characters will be converted to lowercase.
    ↳ 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 Deprecated Link to an online button image. This field has been deprecated due to it being part of the now-deprecated legacy chat design. Any value passed will be ignored and this field will remain null on the widget.
    offlineButtonUrl String Deprecated Link to an offline button image. This field has been deprecated due to it being part of the now-deprecated legacy chat design. Any value passed will be ignored and this field will remain null on the widget.
    enableProactiveChat String If true proactive chat is enabled for the widget. If false it is not.
    enableConversations boolean If true chat is enabled for the widget. If false it is not.
    proactiveSettings String Deprecated May contain the below fields (delayInSec, message). This field has been deprecated due to it being part of the now-deprecated Proactive Chat V1 settings. Any value passed will be ignored and this field will be null on the widget. All widgets updated using this endpoint will be given default Proactive Chat V2 settings.
    ↳ delayInSec String Deprecated The time in seconds to delay a proactive invitation. Default is 45. This field has been deprecated for the same reason as stated above (see 'proactiveSettings'). Any value passed will be ignored and this field will be null on the widget.
    ↳ message String Deprecated The proactive message to display. This field has been deprecated for the same reason as stated above (see 'proactiveSettings'). Any value passed will be ignored and this field will be null on the widget.
    conversationSchedule Json This will contain the schedule for the conversations.
    ↳ timeZone String Time zone for the hours of operation. example ("Europe/Berlin", "UTC", "Asia/Kolkata")
    ↳ schedules List List of schedule(s). This will contain the properties (dayOfWeek, enabled, scheduleList). Note that there can be multiple entries for a given day to accomodate for things like lunch hours, day and evening shifts, etc.
    ↳↳ dayOfWeek String Represents the days of the schedule. Available values for are MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY.
    ↳↳ enabled boolean If true this time period will be evalulated.
    ↳↳ scheduleList List Start and end time using h:mm AM/PM format

    Sample Request

    To view an example request, click one of the language tabs on the right.

    curl -X POST \
      'https://www.snapengage.com/api/v1/widget.json?api_key={api_key}' \
      -H 'Content-Type: application/json' \
      -d '{
       "email": "[email protected]",
       "destinationEmail": "[email protected]",
       "name": "Widget #1 - Sales Widget",
       "uuid": "31a11b98-ffd2-425d-aa69-2c6ff8a40a16",
       "agents":[
          {
             "agentId": "[email protected]",
             "agentAlias": "A New Agent",
             "agentAvatar": "https://www.website.com/a_new_agent_avatar.png",
             "agentType": "webclient"
          }
       ],
       "enableProactiveChat": "false",
       "enableConversations": true
    }'
    
    package com.snapengage.samples.widget;
    
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    
    import javax.ws.rs.client.ClientBuilder;
    import javax.ws.rs.client.Entity;
    import javax.ws.rs.client.WebTarget;
    import javax.ws.rs.core.MediaType;
    import javax.ws.rs.core.Response;
    
    public class WidgetExample {
    
      private static final String apiKey = "{api_key}";
    
      public static void main(String[] args) {
        List<SnapEngageAgent> agentList = new ArrayList<>();
        agentList.addAll(Arrays.asList(
          new SnapEngageAgent("12345", "Jimbo", "https://www.website.com/jimbo.png", "webclient")));
    
        SnapEngageWidget snapEngageWidget =
          new SnapEngageWidget("{user_email}", "Jimbo's US Widget", "{user_email}", agentList, true);
        snapEngageWidget.setUuid("{widget_id}");
    
        WebTarget webTarget = ClientBuilder.newBuilder().build()
          .target("https://www.snapengage.com/api/v1/widget.json?api_key=" + apiKey);
    
        Response response =
          webTarget.request().post(Entity.entity(snapEngageWidget, MediaType.APPLICATION_JSON));
    
        SnapEngageWidget responseWidget = response.readEntity(SnapEngageWidget.class);
    
        System.out.println(responseWidget.toJson());
      }
    }
    

    Response Parameters

    To view sample response JSON, see the JSON tab to the right.

    {
        "name": "Widget #1 - Sales Widget",
        "email": "[email protected]",
        "destinationEmail": "[email protected]",
        "uuid": "31a11b98-ffd2-425d-aa69-2c6ff8a40a16",
        "agents": [
            {
                "agentId": "wc:[email protected]",
                "agentAlias": "A New Agent",
                "agentAvatar": "https://www.website.com/a_new_agent_avatar.png",
                "agentType": "webclient"
            }
        ],
        "enableProactiveChat": "false",
        "enableConversations": true
    }
    
    import requests
    
    url = "https://www.snapengage.com/api/v1/widget.json"
    
    querystring = {"api_key":"{api_key}"}
    
    payload = '{ "email" : "[email protected]", "destinationEmail" : "[email protected]",' \
              '"name" : "A new name for this widget", "uuid" : "31a11b98-ffd2-425d-aa69-2c6ff8a40a16",' \
              '"agents" : [{ "agentId": "[email protected]", "agentAlias" : "A New Agent",' \
              '"agentAvatar" : "https://www.website.com/a_new_agent_avatar.png", "agentType" : "webclient" }],' \
              '"enableProactiveChat" : "true"}'
    
    response = requests.request("POST", url, data=payload, params=querystring)
    
    print(response.text)
    
    Data Type Description
    name String The widget name.
    email String The user account email address. All characters will be converted to lowercase.
    destinationEmail String The email where transcripts are sent.
    uuid String The widget id.
    agents List The list of agent(s) on this widget. Each agent includes the below fields (agentId, agentAlias, agentAvatar, agentType).
    ↳ agentId String The agent ID. All characters will be converted to lowercase.
    ↳ agentAlias String The agent displayed name.
    ↳ agentAvatar String Link to an agent image.
    ↳ agentType String See table of "agentType values" below.
    enableProactiveChat String If true proactive chat is enabled for the widget. If false it is not.

    Success Response

    200 OK

    Delete an existing widget

    To delete a widget, DELETE to the endpoint with your API key, the uuid (widget id), and the user email as parameters.

    DELETE /api/v1/user.json?api_key={api_key}&uuid={widget_id}&email={user_email}
    

    Request Parameters

    Data Type Description
    uuid String Required. The widget public Id.
    email String Required. The user email associated with this widget. All characters will be converted to lowercase.

    Sample Request

    To view an example request, click one of the language tabs on the right.

    curl -X DELETE 'https://www.snapengage.com/api/v1/widget.json?api_key={api_key}&uuid=31a11b98-ffd2-425d-aa69-2c6ff8a40a16&[email protected]'
    
    package com.snapengage.samples.widget;
    
    import javax.ws.rs.client.ClientBuilder;
    import javax.ws.rs.client.WebTarget;
    
    public class WidgetExample {
    
      private static final String apiKey = "{api_key}";
    
      public static void main(String[] args) {
        WebTarget webTarget = ClientBuilder.newBuilder().build()
            .target("https://www.snapengage.com/api/v1/widget.json?api_key=" + apiKey
                + "&uuid={widget_id}&email={user_email}");
    
        webTarget.request().delete();
      }
    }
    
    import requests
    
    url = "https://www.snapengage.com/api/v1/widget.json"
    
    querystring = { "api_key" : "{api_key}", "uuid" : "31a11b98-ffd2-425d-aa69-2c6ff8a40a16", "email" : "[email protected]" }
    
    response = requests.request("DELETE", url, params=querystring)
    
    print(response.text)
    

    Response Parameters

    No response payload is returned.

    Success Response

    200 OK

    Visitor Chat API

    Check widget availability

    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 the widget

    Sample Request

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

    // NOTE: Make sure to replace the "{api_key}" below with your API key!
    
    curl -X GET \
      https://www.snapengage.com/api/v1/chat/5286374d-5c92-419d-bcdb-b926d242b78b \
      -H 'x-api-key: {api_key}'
    

    Response Parameters

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

    Success Response

    200 OK

    {
        "widgetId": "5286374d-5c92-419d-bcdb-b926d242b78b",
        "online": "true",
        "emailRequired": "false",
        "messageRequired": "false",
        "screenshotRequired": "false"
    }
    

    Start new chat

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

    POST /api/v1/chat
    

    Request Parameters

    Data Type Description
    widgetId String Required. Unique identifier of the widget.
    email String (Required if emailRequired is true for chat widget) Visitor’s email address.
    phone String Visitor’s phone number.
    userAgent String Similar to web browser user agent string.
    locale String Locale of this chat session. Example could be “en” or “en-GB”.
    isOffline Boolean true/false – Open chat session or send message directly to email (offline). Default is false.
    appVersionName String 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.

    // NOTE: Make sure to replace the "{api_key}" below with your API key!
    
    curl -X POST \
      'https://www.snapengage.com/api/v1/chat?widgetId=5286374d-5c92-419d-bcdb-b926d242b78b&[email protected]&phone=555-123-4567&userAgent=Mozilla/5.0%20%28Macintosh;%20Intel%20Mac%20OS%20X%2010_8_2%29%20AppleWebKit/537.17%20%28KHTML,%20like%20Gecko%29%20Chrome/24.0.1309.0%20Safari/537.17&locale=en&isOffline=false&appVersionName=My%20Mobile%20App&visitorMessage=hello' \
      -H 'Content-Type: application/x-www-form-urlencoded' \
      -H 'x-api-key: {api_key}'
    

    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": "ca5e3eca-8659-44a7-89fd-2f0b4dd71fa6",
        "widgetId": "5286374d-5c92-419d-bcdb-b926d242b78b"
    }
    

    Send chat message

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

    PUT /api/v1/chat
    

    Request Parameters

    Data Type Description
    caseId Sting Required. 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.

    // NOTE: Make sure to replace the "{api_key}" below with your API key!
    
    curl -X PUT \
      'https://www.snapengage.com/api/v1/chat?caseId=a26503d8-4495-4147-acb4-d1a95ae744d5&messageType=1&messageBody=I%20need%20help%20finding%20shoes%21' \
      -H 'Content-Type: application/x-www-form-urlencoded' \
      -H 'x-api-key: {api_key}'
    

    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": "a26503d8-4495-4147-acb4-d1a95ae744d5",
        "messageBody": "I need help finding shoes!",
        "messageType": "1"
    }
    

    Poll for new chat message

    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 The start index of chats to return. Default is 0.
    isTyping Boolean Is the visitor currently typing a message? Default is false.

    Sample Request

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

    // NOTE: Make sure to replace the "{api_key}" below with your API key!
    
    curl -X GET \
      https://www.snapengage.com/api/v1/chat/poll/f383eadb-a15e-4d13-bda2-6f3bf412de62 \
      -H 'x-api-key: {api_key}'
    

    Response Parameters

    Data Type Description
    caseId String Unique identifier of chat session.
    agentTyping Boolean Is true if the agent is currently typing a message.
    messageList Array An array of messages.
    ↳index Integer Index of the chat message in the transcript.
    ↳type String Either “agent” or “system”.
    ↳author String The agent alias.
    ↳text String The message that was sent.

    Success Response

    200 OK

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

    {
        "caseId": "f383eadb-a15e-4d13-bda2-6f3bf412de62",
        "messageList": [
            {
                "index": 2,
                "type": "system",
                "author": "Sam",
                "text": "/NIC Sam "
            },
            {
                "index": 3,
                "type": "system",
                "author": "Sam",
                "text": "/CAL 1 "
            },
            {
                "index": 4,
                "type": "system",
                "author": "",
                "text": "/NFO Just a moment...<br> "
            },
            {
                "index": 6,
                "type": "system",
                "author": "Sam",
                "text": "/SYS EMTR false "
            },
            {
                "index": 7,
                "type": "system",
                "author": "Sam",
                "text": "/SYS GRCP -1 "
            },
            {
                "index": 8,
                "type": "system",
                "author": "Sam",
                "text": "/SYS WAGT 6%2CSorry%2520for%2520the%2520delay.%2520We%27re%2520working%2520on%2520getting%2520to%2520you%2520as%2520quickly%2520as%2520possible.%2520If%2520you%2520need%2520to%2520run%2C%2520please%2520feel%2520free%2520to%2520%5Bleave%2520us%2520a%2520message%5D "
            },
            {
                "index": 9,
                "type": "system",
                "author": "Sam",
                "text": "/SYS REAS 16 "
            },
            {
                "index": 10,
                "type": "system",
                "author": "Sam",
                "text": "/NIC Sam "
            },
            {
                "index": 11,
                "type": "system",
                "author": "Sam",
                "text": "/CAL 1 "
            },
            {
                "index": 12,
                "type": "agent",
                "author": "Sam",
                "text": "hi "
            },
            {
                "index": 14,
                "type": "agent",
                "author": "Sam",
                "text": "Ok, I can help you with that! "
            }
        ],
        "agentTyping": false
    }
    

    Proactive Chat in Single Page Applications

    Proactive Chat can be triggered by a URL change or a page refresh.

    These kind of events can't be automatically tracked by SnapEngage, therefore we have worked on a solution and we have exposed a function by the name reInitProactiveRules(). Whenever there is a url change, call this function SnapEngageChat.reInitProactiveRules(). You can also bypass 'Proactive chat re-engagement delay' by calling the method like this reInitProactiveRules({force:true})

    Error responses

    Error Code Description
    400 Invalid or missing parameter
    401 Unauthorized – Invalid or no header x-api-key set
    404 Not Found – Widget or Chat object not found (Empty response)
    405 HTTP 405 Method Not Allowed - Something is wrong with the structure of your request.
    500 Internal Server Error – Contact SnapEngage support if you continue to see this Response.

    Widget Availability API

    The SnapEngage Widget Availability API allows developers to query for the status of a widget without an API Key or installing the SnapEngage Javascript.

    Authentication for the Widget Availability API

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

    How to use the Widget Availability API

    Click on the the JavaScript or cURL tab to the right to see examples requests.

    Parameters

    Parameter Type Description
    widgetId String Required. You can find the widgetId in the Admin Dashboard, in the (Advanced) Widget ID section of the Get the Code tab.
    curl https://www.snapengage.com/public/api/v2/chat/{widgetId}
    
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function() {
      if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
        console.log(xmlHttp.response);
      }
    }
    xmlHttp.open("GET", "https://www.snapengage.com/public/api/v2/chat/{widgetId}", true);
    xmlHttp.send(null);
    

    Sample JSON Response

    Click the JSON tab to the right to view sample response JSON.

    {
      "statusCode":1,
      "data":{
        "widgetId":"{widgetId}",
        "online":"false",
        "emailRequired":"true",
        "messageRequired":"true",
        "screenshotRequired":"false"
      }
    }
    

    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.

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