Skip to content

JS API Reference

Users can use 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 website's visitors;

  • opening forms and callback order through sitephone;

  • characteristics 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 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:

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

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

Application form

To open 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:

Title Type Description
req {name: myName, email: myEmail, phone: myPhone, message: myMessage, is_sale: mySale, sale_cost: myCost, group_id: 12345 } Description of parameters: myName - text type - visitor name, myEmail - text type - visitor email, myPhone - text type - visitor phone number, myMessage - text type - application type and other information for which there is no specific field, mySale - true - if it's a sale; false - if it's not a sale (by default), group_id - id groups, to which an application should have been sent to, myCost - transaction cost. If you need to send transaction cost, you must send value true in the parameter is_sale.
callback "success": <Boolean>, "result": {"code": <String>}} An argument's feature, which will be called after the server sends the result of saving the form. Optional parameters.

Example:

  1. Regular application:
CallGear.addOfflineRequest({
  name: 'Dmitry',
  email: 'dmitry@callgear.com',
  phone: '79123456789',
  message: 'Application text...',
  group_id: 1234
});
  1. Application, that lead to a sale:
CallGear.addOfflineRequest({
  name: 'Dmitry',
  email: 'dmitry@callgear.com',
  phone: '79123456789',
  message: 'Online order...',
  is_sale: true,
  sale_cost: '9999'
});
  1. Example using the parameter callback:
CallGear.addOfflineRequest({"name": "My Name Is"}, function(o) {console.log(o);});

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

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 method JS API CallGear.getCredentials(). This method returns an object:
{
  "site_key": "VcB4qqpO1WPSopO670cAbXwAH9Ryaw75",
  "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 data from the form.

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

URL base cannot be hard-coded. It must be taken from the data from the paragraph 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
site_key=VcB4qqpO1WPSopO670cAbXwAH9Ryaw75
&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 a 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 form of feedback 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: to 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='site_key'/>
    <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 a page code or in a separate JS-file. This function is called every time you click on 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 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 called 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 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>

AJAX-request sending JS-code:

function sendAjaxSubmit() {
    /* This can be a check of the required filled in 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);
             }
         },
     })
}

Processing the received request PHP-code:

<?
    /* 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';
    }
?>

In order to send an application in case of sending an 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 filled in 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 a 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 service field site_key
            'visitor_id' => $_POST['visitor_id'], //Unchanged value from the service field visitor_id
            'hit_id' => $_POST['hit_id'], //Unchanged value from the service field hit_id
            'session_id' => $_POST['session_id'], //Unchanged value from the service field session_id
            '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 called 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:

Title 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 phone number mask for 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 a format of a mask, displayed on the sitephone.

Sitephone user form

In addition to standard widgets, you can use any form you want to call back 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:

Title 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 myURL result from the method Captcha.get_captcha(), click a 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 Employees group ID, where a call will be directed to.
callback {"success": <Boolean>, "result":{status: <Integer>, code: <String>}} Returning reply, optional (but advised). If it's not specified, the feature 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, if there are operators online, a chat form opens:

CallGear.openChatWindow();

If no operators are online, the application form opens.

Working with visitors

Getting visitor ID

To get visitor ID, use the following method:

CallGear.getVisitorId();

Getting user session ID

To get 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 a method successfully, at least one parameter must be filled.
All other parameters will be ignored.

Parameters:

Title Parameters Description
req {name: myName, email: myEmail, phone: myPhone} myName - text type - visitor name (rewritable)
myEmail - text type - visitor email (unique one is added)
myPhone - text type - visitor phone number (unique one is added)
callback "success": <Boolean> A feature 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 an embed code, the jQuery library is connected

  • Before sending information about the visitor, you need to obtain authentication data using the JS API method CallGear.getCredentials().

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

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 feature or its value, use the method:

CallGear.setProperty(name, value);

Parameters:

Title Type Description
name text Title 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 value is assigned in the following way:

CallGear.setProperty('Current customer');

Checking whether or not visitor has a feature

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

CallGear.hasProperty(name, callback);

Parameters:

Title Type Description
name text Title 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 - value name assigned false - feature name not assigned

Example:

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

Getting visitor features values

To get visitor features values use the following method:

CallGear.getProperty(name, callback);

Parameters:

Title Type Description
name text Title 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 - value name, 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 visitor feature, use the following method:

CallGear.deleteProperty(name);

Parameters:

Title Type Description
name text Title of a feature, that's 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 a number substitution is necessary only under certain conditions, for example, only for visitors from Moscow, you need to redefine the feature 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 feature 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 feature.

If numbers need to be substituted only under certain conditions, then this feature must be redefined by adding necessary conditions into the 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 feature:

CallGear.getPhones();

The reply will return a bulk 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 feature:

CallGear.getDTPhones();

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

If there are several reserved numbers, then a bulk of objects will return, 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]