Skip to content

JS API Reference

Users can use the JavaScript API to solve the following problems.

To implement additional features on a website:

  • opening forms to communicate with an online consultant (chat, inquiry) from any place on a user's website;

  • getting additional information about a website's visitors;

  • opening forms and callback orders through sitephone;

  • characteristic assignment (for example, the characteristic “active customer” is assigned to a visitor who opened the personal area, “potential” is assigned to a visitor who opened the tariffs, etc.).

Getting additional data in reports:

  • data about any user event on a website (reading a book, viewing tariffs, visiting the personal area, etc.);

  • information from any user application form.

Working with events

Sending user events

To send a user event, use the following method:

CallGear.trackEvent(category, action, name, value);

Parameters:

Name Type Description
category text category, required parameter
action text action, required parameter
name text name, optional parameter
value text value, optional parameter

Usage example:

CallGear.trackEvent('Offer', 'DownloadBook', 'CallTrackingBook', 'value');

Working with banners

Checking for operators who are online

To check for operators who are online, use the method:

CallGear.getOperatorStatus();

The method returns true if there is at least one operator online, otherwise it returns false.

Application form

To open the application form, use the method:

CallGear.openSiteRequestPanel();

User application form

Data received from a user application form on a website can be sent via the following method:

CallGear.addOfflineRequest(req, callback);

You can only use this method when sending a form in a way that does not reload the page. There is an alternative method for all other cases.

Parameters:

Name Type Description
req {name: myName, email: myEmail, phone: myPhone, message: myMessage, is_sale: mySale, sale_cost: myCost, group_id: 12345, form_name: formName, user_fields: myFields} Description of parameters: myName - text type - visitor name; myEmail - text type - visitor email; myPhone - text type - visitor phone number; myMessage - text type - application text and other information for which there is no separate field; mySale - true if it is a sale and false otherwise; group_id - ID of the group to which the application should be sent; myCost - sale cost. If you need to send the sale cost, pass true in the is_sale parameter. form_name is the name of the tracked form. myFields contains custom application fields.
callback "success": <Boolean>, "result": {"code": <String>}} A callback function that will be called after the server sends the result of saving the form. Optional parameter.

Example:

  1. Regular application:
CallGear.addOfflineRequest({
  name: 'Dmitry',
  email: 'dmitry@callgear.com',
  phone: '79123456789',
  message: 'Application text...',
  group_id: 1234
});
  1. Application that leads to a sale:
CallGear.addOfflineRequest({
  name: 'Dmitry',
  email: 'dmitry@callgear.com',
  phone: '79123456789',
  message: 'Online order...',
  is_sale: true,
  sale_cost: '9999'
});
  1. Application submitted through a specific form with additional parameters:
CallGear.addOfflineRequest({
  name: 'Dmitry',
  email: 'dmitry@callgear.com',
  phone: '79123456789',
  message: 'Online order...',
  is_sale: true,
  sale_cost: '9999',
  form_name: 'Test form',
  user_fields: {
    "KvartiriMoscow": "Three-room apartment",
    "NomeraKvartirvMoscow": "10"
  }
});
  1. Example using the callback parameter:
CallGear.addOfflineRequest({"name": "My Name Is"}, function(o) {console.log(o);});

After an application is successfully saved, the following result will be displayed in the browser console:

Object {success: true, result: null}

An alternative way to send user applications

  1. You need to receive widget authentication data before sending an application, using the JS API method CallGear.getCredentials(). This method returns an object:
{
  "site_key": "VcB4qqpO1WPSopO670cAbXwAH9Ryaw75",
  "key": "u8N4wqLtywFKSaxGOUCreGKD0zglE2s0",
  "uri": "https://server.callgear.com/",
  "visitor_id": 17258569,
  "hit_id": 546833568748,
  "session_id": 255544855,
  "consultant_server_url": "https://server.callgear.com/" // URL base part
}
  1. Transfer the received data along with the rest of the data from the form.

  2. To add an application, make an HTTP request to a service in a server handler.

The URL base cannot be hard-coded. It must be taken from the data obtained in step 1. It may change.

POST https://server.callgear.com/api/add_offline_message/
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Form Data // data is formatted for display purposes
key=u8N4wqLtywFKSaxGOUCreGKD0zglE2s0
&uri=https://server.callgear.com/
&visitor_id=17258569
&hit_id=546833568748
&session_id=255544855
&name=John Smith
&email=no@email.adr
&phone=+79251234567
&text=Hello, world!
&is_sale=true
&sale_cost=10000

In reply, a success flag will be sent (application/json):

{
  "success": true
}

Example of using an alternative method to send a user application

Page reload option

We will assume that the embed code is already installed on a website, the jQuery library is connected and there is a feedback form. The simplest feedback form code may look like this:

<form id='myform' action="/send.php" method="POST">
    <input type="text" name='name' value='' placeholder="Name" /><br>
    <input type="text" name='phone' value='' placeholder="Phone number" /><br>
    <input type="text" name='email' value='' placeholder="E-mail" /><br>
    <textarea name="text"></textarea><br>
    <input type='submit' />
</form>

In order to send an application, the form code needs to be finalized: add service fields and a handler to the "Send" button:

<form id='myform' action="/send.php" method="POST">
    <input type="text" name='name' value='' placeholder="Enter a name" /><br>
    <input type="text" name='phone' value='' placeholder="Enter a phone number" /><br>
    <input type="text" name='email' value='' placeholder="Enter an e-mail" /><br>
    <textarea name="text"></textarea><br>
    <input type='button' value='Send' onclick="formSubmit()"/>
    <input type="hidden" name='key'/>
    <input type="hidden" name='uri'/>
    <input type="hidden" name='visitor_id'/>
    <input type="hidden" name='hit_id'/>
    <input type="hidden" name='session_id'/>
    <input type="hidden" name='consultant_server_url'/>
</form>

You need to write the function formSubmit() in the page code or in a separate JS file. This function is called every time you click the "Send" button:

function formSubmit() {
    var credentials = CallGear.getCredentials();
    for (var field in credentials) {
        if (credentials.hasOwnProperty(field)){
            $('[name='+field+']').val(credentials[field]);
        }
    }
    $('#myform').submit();
}

This code receives service information, saves it in the invisible service fields of the form and sends the form to the server.

Next, you need to modify the code that is responsible for processing the application on the server. In our case, this code is in the send.php file:

<? /* Here is the default code associated with processing an application on the server side. For example, sending letters, or saving to a database. */ ?>
<?
    $url = $_POST['consultant_server_url'].'api/add_offline_message/';
          $data = array(
            'site_key' => $_POST['site_key'], // Unchanged value from the site_key service field
            'visitor_id' => $_POST['visitor_id'], // Unchanged value from the visitor_id service field
            'hit_id' => $_POST['hit_id'], // Unchanged value from the hit_id service field
            'session_id' => $_POST['session_id'], // Unchanged value from the session_id service field
            'name' => $_POST['name'], // Customer name
            'email' => $_POST['email'], // E-mail
            'phone' => $_POST['phone'], // Phone number
            'text' => $_POST['text'], // Application text
            'is_sale' => true, // true, if it's a sale
            'sale_cost' => 10000 // Sale cost. If you need to transfer a sale cost, then is_sale must equal true
            );
    /* If all the fields in the html markup of the form are named as CallGear requires, you can write "$data = $_POST".
    Otherwise, additional conversions are required. */
    $options = array( 'http' =>
        array(
            'header' => "Content-type: application/x-www-form-urlencoded; charset=UTF-8",
            'method' => "POST",
            'content' => http_build_query($data)
        )
    );
    print $options['http']['content'];
    $context = stream_context_create($options);
    $result = file_get_contents($url, false, $context);
    $resultArray = json_decode($result, true);

    if ($result === false or $resultArray['success'] === false) {
        /* There may be actions in case sending of an application fails. */
    }
?>

Example with an AJAX request

HTML markup of a simple form:

<form id='myform2'>
    <input type="text" name='name' value='' placeholder="Enter name" /><br>
    <input type="text" name='phone' value='' placeholder="Enter phone number" /><br>
    <input type="text" name='email' value='' placeholder="Enter e-mail" /><br>
    <textarea name="text"></textarea><br>
    <input type='button' value='Send' onclick="sendAjaxSubmit()"/>
</form>

JS code that sends the AJAX request:

function sendAjaxSubmit() {
    /* This can be a check of the required fields, validation of the phone number and other checks. */
     $.ajax({
         url: 'sendAjax.php',
         method: 'POST',
         data: $('#myform2').serialize(),
         complete: function(response) {
             if (response.readyState === 4 && response.status === 200) {
                alert(response.responseText);
             }
         },
     })
}

PHP code that processes the received request:

<?
    /* Code for processing incoming data, saving to the database or sending an application by email. */
    $success = true; /* The variable defines whether or not the application was saved. */
    if ($success) {
        print 'Application successfully saved';
    } else {
        print 'An unexpected error has occurred';
    }
?>

If you send the application with an AJAX request, you do not need to modify the HTML form. It is necessary to modify the JS code so that service information is received before sending the request:

function sendAjaxSubmit() {
    /* Here you can check the required fields, validate the phone number and make other checks. */
    $.ajax({
        url: '/sendAjax.php',
        method: 'POST',
        data: $('#myform2').serialize(),
        complete: function(response) {
            if (response.readyState === 4 && response.status === 200) {
                alert(response.responseText);
            }
        },
        beforeSend: function(jqXHR, settings) {
            var credentials = CallGear.getCredentials();
            settings.data += '&' + $.param(credentials);
        }
    })
}

The code needs to be executed on the server. In this case, it is in the sendAjax.php file:

<?
    /* Here is the default code associated with processing an application on the server side. For example, sending letters, or saving to a database. */
?>
<?
    $success = true; /* Check that everything is done correctly. */
    if ($success) {
        $url = $_POST['consultant_server_url'].'api/add_offline_message/';
        $data = array(
            'site_key' => $_POST['site_key'], // Unchanged value from the site_key service field
            'visitor_id' => $_POST['visitor_id'], // Unchanged value from the visitor_id service field
            'hit_id' => $_POST['hit_id'], // Unchanged value from the hit_id service field
            'session_id' => $_POST['session_id'], // Unchanged value from the session_id service field
            'name' => $_POST['name'], // Customer name
            'email' => $_POST['email'], // E-mail
            'phone' => $_POST['phone'], // Phone number
            'text' => $_POST['text'], // Application text
            'is_sale' => true, // true, if it's a sale
            'sale_cost' => 10000 // Sale cost. If you need to transfer a sale cost, then is_sale must equal true
        );
        /* If all the fields in the html markup of the form are named as CallGear requires, you can write "$data = $_POST".
    Otherwise, additional conversions are required. */
        $options = array(
            'http' => array(
                'header' => "Content-type: application/x-www-form-urlencoded; charset=UTF-8",
                'method' => "POST",
                'content' => http_build_query($data)
            )
        );
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        $resultArray = json_decode($result, true);
        if ($result === false or $resultArray['success'] === false) {
            /* Processing the case if sending of an application failed. */
        } else {
            print 'Application successfully saved.';
        }
    } else {
        print 'An unexpected error has occurred';
    }
?>

Sitephone form

To open our standard sitephone form, use the method:

CallGearWidget.openSitePhonePanel();

Captcha for sitephone forms

CallGear.Captcha.get_captcha(callback);

Parameters:

Name Type Description
callback {key: myKey, url: myURL} Returning reply: myKey - captcha key, myURL - picture address.

Example:

CallGear.Captcha.get_captcha(function(resp){console.log(resp)});

Changing the phone number mask for the sitephone form

In order to replace the standard mask for entering the number in the sitephone and allow entering numbers in other formats, add a line to the insert code:

__cs.push(["setUIPhoneMaskFormat", '1 () __-__']);

As the second parameter, you should send the format of the mask displayed on the sitephone.

Sitephone user form

In addition to standard widgets, you can use any form you want for callbacks on the site.

To do so, you need to embed the callback method call into your form using the JS API:

CallGearWidget.sitePhoneCall({captcha_key: <captcha ID>, captcha_value: <captcha value>, phone: <phone number>, delayed_call_time: <call time>, group_id: <group id>}, callback);

Parameters:

Name Type Description
captcha_key text Captcha ID. Required if captcha is switched on in the callback settings.
captcha_value text Captcha value (what a visitor entered in the form): take the myURL result from the Captcha.get_captcha() method, click the link, see 4 figures. Required if captcha is switched on in the callback settings.
phone text Visitor phone number. Required.
delayed_call_time text UTC call time in milliseconds.
group_id text Employee group ID, where a call will be directed.
callback {"success": <Boolean>, "result": {status: <Integer>, code: <String>}} Returning reply, optional (but advised). If it is not specified, the method will work similarly to a call from the standard sitephone form and will display a pop-up notification with the result. Parameters: success: true - successful, false - failed; result - call results: status - call status.

Possible statuses:

Code Value
0 successful, call sent to platform
1 captcha is incorrect
2 callback processing scenario is not specified
3 platform error
4 limit of calls per minute has been exceeded (up to 10 calls)

Example of usage:

CallGearWidget.sitePhoneCall({captcha_key: 'jwgtGYZDYTA...4pBEWRx', captcha_value: '8315', phone: '79101234567', delayed_call_time: 1508927547000, group_id: '16587'}, function(resp){console.log(resp)});

Chat form

When the following method is called, a chat form opens if there are operators online:

CallGear.openChatWindow();

If no operators are online, the application form opens.

Working with visitors

Getting visitor ID

To get the visitor ID, use the following method:

CallGear.getVisitorId();

Getting user session ID

To get the user session ID, use the following method:

CallGear.getSessionId();

Adding visitor information

To add visitor information, use the following method:

CallGear.addVisitorInfo({name:'myName', phone:'myPhone', email:'myEmail'});

You can use this method only if you send the form in a way that does not reload the page. For other cases, there is an alternative method.

To call the method successfully, at least one parameter must be filled in.
All other parameters will be ignored.

Parameters:

Name Parameters Description
req {name: myName, email: myEmail, phone: myPhone} myName - text type - visitor name (rewritable);
myEmail - text type - visitor email (a unique one is added);
myPhone - text type - visitor phone number (a unique one is added)
callback "success": <Boolean> A callback function of a single argument, which will be called after the server sends the result of saving the form. Optional parameter.

Example:

CallGear.addVisitorInfo({name:'Test', phone:'79000000000', email:'myemail@axample.com'}, function(resp){console.log(resp)})

Alternative way to add visitor information

We will proceed from the fact that a website already has the embed code and the jQuery library is connected.

  • Before sending information about the visitor, you need to obtain authentication data using the JS API method CallGear.getCredentials(). The method returns an object:
{
  "site_key": "VcB4qqpO1WPSopO670cAbXwAH9Ryaw75",
  "visitor_id": 17258569,
  "hit_id": 546833568748,
  "session_id": 255544855,
  "consultant_server_url": "https://server.callgear.com/" // We don't need this URL
}
  • Transfer the received data along with other data from the form.

Parameters:

url - https://tracker.callgear.com/vc/s/
parameters from the CallGear.getCredentials() request:
sk = site_key
ci = callgear_id
hi = hit_id
vp = phone number
vn = name
ve = email
s = 1 removes the output of system fields in the reply (only success: true is returned)

Example:

https://tracker.callgear.com/vc/s/?sk=nS5lMAgURPyUQXVyBgguFy0AvIRdbfdy&ci=2032047566.3117192853.1555675484&hi=9228054013&vn=new_user

Adding a feature to a visitor

To add a feature or its value, use the method:

CallGear.setProperty(name, value);

Parameters:

Name Type Description
name text Name of the feature to be assigned to a visitor
value text Feature value (optional)

Examples:

The feature "Visitor type" with value "Potential" is assigned in the following way:

CallGear.setProperty('Visitor type', 'Potential');

The feature "Current customer" without a value is assigned in the following way:

CallGear.setProperty('Current customer');

Checking whether or not a visitor has a feature

To check whether or not a visitor has a feature, use the following method:

CallGear.hasProperty(name, callback);

Parameters:

Name Type Description
name text Name of a feature to be assigned to a visitor
callback {"success": <Boolean>,"result": <Boolean>,} Returning reply. success: true - method successfully processed, false - error; result: true - feature name assigned, false - feature name not assigned

Example:

CallGear.hasProperty('Current customer', callback);
CallGear.hasProperty('Current customer', function(resp){console.log(resp)});

Getting visitor feature values

To get visitor feature values, use the following method:

CallGear.getProperty(name, callback);

Parameters:

Name Type Description
name text Name of a feature to be assigned to a visitor
callback {"success": <Boolean>,"result": <Boolean>,} Returning reply. success: true - method successfully processed, false - error; result: true - feature name value, false - the name feature not assigned

Example:

CallGear.getProperty('Customer type', callback);
CallGear.getProperty('Current customer', function(resp){console.log(resp)});

Deleting visitor features

To delete a visitor feature, use the following method:

CallGear.deleteProperty(name);

Parameters:

Name Type Description
name text Name of a feature that is to be deleted

Example:

CallGear.deleteProperty('visitor type');

Number substitution

Number substitution in dynamic blocks

In order to enable number substitution in dynamically added blocks, an additional line must be added to the insert code:

__cs.push(["setDynamicalReplacement", true]);

or

CallGear.push(["setDynamicalReplacement", true]);

Number substitution management

When number substitution is necessary only under certain conditions - for example, only for visitors from Moscow - you need to redefine the function that controls the number substitution, window.__cs_onReplacePhones(phones). It works as follows:

  • if it returns true, the substitution will be performed as if the function had not been redefined;

  • if it returns false, the substitution will not be performed.

The function is created at the time of the service code initialization and by default has the form:

window.__cs_onReplacePhones = function(phones) {return true;};

If you do not need to manage the substitution, then you do not need to redefine the function.

If numbers need to be substituted only under certain conditions, then this function must be redefined by adding the necessary conditions to its body.

Getting numbers given to a visitor

If a customer needs to get a list of all the numbers issued to a website visitor, you can use the following method:

CallGear.getPhones();

The reply will return an array of objects similar to the phones list in __cs_onReplacePhones.

Example:

[
  {
    id: '#callgear_phone', // element ID
    img: null || 'path/to/img', // image address (if image substitution is used)
    text: null || '+7(495)999-99-99', // formatted number
    raw: '74959999999' // number without formatting
  },
  ...
]

Parameters:

Substituted ID type Example of ID field return value
id #callgear_phone
class .callgear_phone
name [name=callgear_phone]
number number=XXXXXXXXXXX

Getting a list of dynamic tracking numbers reserved for a visitor

If a customer needs to get a list of dynamic tracking numbers reserved for a visitor, you can use the following method:

CallGear.getDTPhones();

This method will return null in the case that no dynamic tracking numbers are reserved for a visitor.

If there are several reserved numbers, then an array of objects will be returned, similar to the phones list in __cs_onReplacePhones.

Example:

[
  {
   id: '#callgear_phone', // element ID
    img: null || 'path/to/img', // image address (if image substitution is used)
    text: null || '+7(495)999-99-99', // formatted number
    raw: '74959999999' // number without formatting
  },
  ...
]

Parameters:

Substituted ID type Example of ID field return value
id #callgear_phone
class .callgear_phone
name [name=callgear_phone]