Examples

Use cases

Use cases are real-world API examples. They can be a combination of different languages, APIs, and settings. They are built to complete specific tasks.


Register a custom user and log in it

This use case explains how to manually register a custom user and log-in it before starting the chat. You can register a new user in four ways, JS VARIABLE, PHP API, JS API and PHP + JS + WEB. JS VARIABLE, PHP API and PHP + JS + WEB API are the recommended methods.


JS VARIABLE

Just Enter the variable SB_DEFAULT_USER. More details here.


PHP API


1 Register the user and login it

Check if an active user is already logged-in by checking the email, if yes, login it, otherwise register a new user.

                                require_once($_SERVER["DOCUMENT_ROOT"] . "/supportboard/include/functions.php");
                                $active_user = sb_get_active_user();
                                if (!$active_user || $active_user["email"] != "don.john@email.com") {
                                    $response = sb_add_user_and_login([ "profile_image" => "https://board.support/media/docs/user.png", "first_name" => "Don", "last_name" => "John", "email" => "don.john@email.com", "password" => "12345678"], ["phone" => ["123456789", "Phone"], "city" => ["London", "City"]]);
                                    if ($response == "duplicate-email") {
                                        $response = sb_login("don.john@email.com", "12345678");
                                    }
                                }
                            

PHP + JS + WEB API


1 Enable the manual initialization

Go to Settings > Chat, check the option Manual initialization, and save.


2 Print the JS code to register the user and login it

Generate a JS code to insert into all the pages containing the chat. The code checks if an active user is already logged in, if yes, log in it, otherwise register a new user. The code also provides the details to log in an existing user.

                                $existing_user_email = 'don.john@email.com';
                                $sb_user = supportboard_curl(['function' => 'get-user-by', 'by' => 'email', 'value' => $existing_user_email]);
                                $code_login_existing_user = '';
                                if (isset($sb_user['success']) && $sb_user['success']) {
                                   $sb_user = $sb_user['response']; 
                                   $code_login_existing_user = 'SBF.login("", "", "' . $sb_user['id'] . '", "' . $sb_user['token'] . '", () => { SBChat.initChat(); });';
                                }  
                                $code = 'jQuery(document).on("SBReady", function () {
                                            SBF.getActiveUser(true, () => {
                                                if (!SBF.activeUser() || (SBF.activeUser().email != "' . $existing_user_email . '")) {
                                                    SBF.ajax({
                                                        function: "add-user-and-login",
                                                        settings: { profile_image: "https://board.support/media/docs/user.png", first_name: "Don", last_name: "John", email: "don.john@email.com" },
                                                        settings_extra: { phone: ["123456789", "Phone"], city: ["London", "City"] }
                                                    }, (response) => {
                                                        if (!SBF.errorValidation(response)) {
                                                            SBF.loginCookie(response[1]);
                                                            SBF.activeUser(new SBUser(response[0]));
                                                            SBChat.initChat();
                                                        } else if (response[1] == "duplicate-email") {
                                                           ' . $code_login_existing_user . '
                                                        } else {
                                                            SBChat.initChat();
                                                        }
                                                     });
                                                  }
                                              });
                                          });';
                                echo $code;
                            

JAVASCRIPT API


1 Enable the manual initialization

Go to Settings > Chat, check the option Manual initialization, and save.

2 Register the user and login it

Check if an active user is already logged-in, if yes, login it, otherwise register a new user. Warning! This method is not secure, password and user details are visible to everyone.

                                jQuery(document).on("SBReady", function () {
                                    SBF.getActiveUser(true, () => {
                                        if (!SBF.activeUser() || (SBF.activeUser().email != "don.john@email.com")) {
                                            SBF.ajax({
                                                function: "add-user-and-login",
                                                settings: { profile_image: "https://board.support/media/docs/user.png", first_name: "Don", last_name: "John", email: "don.john@email.com", password: "12345678" },
                                                settings_extra: { phone: ["123456789", "Phone"], city: ["London", "City"] }
                                            }, (response) => {
                                                if (!SBF.errorValidation(response)) {
                                                    SBF.loginCookie(response[1]);
                                                    SBF.activeUser(new SBUser(response[0]));
                                                    SBChat.initChat();
                                                } else if (response[1] == "duplicate-email") {
                                                    SBF.login("don.john@email.com", "12345678", "", "", () => { SBChat.initChat(); });
                                                } else console.log(response);
                                            });
                                        } else {
                                            SBChat.initChat();
                                        }
                                    });
                                });
                            

Display the chat only on specific pages

This use case explains how to display the chat only on specific pages.


1 Enable the manual initialization

Go to Settings > Chat, check the option Manual initialization, and save.

2 Initialize the chat

Initialize the chat with the function SBChat.initChat() of the JavaScript API . You can use the JS variable window.location.href to get the URL and display the chat only if the URL matches your criteria.

                                $(document).on("SBReady", function () {
                                    // Example: display the chat only on the contact page
                                    if (window.location.href.indexOf("/contact") > 0) {
                                        SBChat.initChat();
                                    }

                                    // Example: display the chat only on the home page
                                    if (window.location.href == "https://example.com") {
                                        SBChat.initChat();
                                    }
                                });
                            

Display the chat on click

This use case explains how to display the chat only after the user click a button.

1 Enable manual initialization and auto opening

Enable the options Settings > Chat > Manual initialization, Settings > Chat > Open automatically, and save the changes.

2 Display the chat

Use the function SBChat.initChat() to display the chat. You can use it as a link with the code javascript:SBChat.initChat(). To open the chat on mobile devices you need to use also the function SBChat.open(). Example:

                                <a href="javascript:SBChat.initChat();SBChat.open()">Click here</a>
                            

Display and hide the chat on click

This use case explains how to display the chat only after the user click a button, and hide it again when the user close it.


1 Enable the manual initialization

Go to Settings > Chat, check the option Manual initialization, and save.

2 Add the click events code

The first click event shows the chat, the second hide it. Replace button-id with the ID of your HTML button or element.

                                $("body").on("click", "#button-id", function () {
                                    SBChat.initChat();
                                    $(".sb-chat-btn").show();
                                    setTimeout(function () {
                                        SBChat.open();
                                     }, 500);
                                });

                                $("body").on("click", ".sb-chat .sb-chat-btn", function () {
                                    $(this).hide();
                                });
                            

Create a new conversation and assign a department to it

This use case explains how to create a new conversation, assign a department to it, and open it in the chat. If you want that all the conversations are automatically assigned to a fixed department use the JavaScript variable SB_DEFAULT_DEPARTMENT. You can get the IDs from Settings > Miscellaneous > Departments.


1 Create a new conversation, and open it

Create a new conversation with the function SBChat.newConversation() of the JavaScript API and pass the department ID 2 in the function' arguments. After the conversation is created, it's opened with the function SBChat.openConversation() . In the code snippet below, the conversation is created only if the user has no other conversations.

                                $(document).on("SBInit", function () {
                                    if (SBF.activeUser() != false && SBF.activeUser().conversations.length == 0) {
                                        SBChat.newConversation(2, -1, "", [], 2, null, function (conversation) {
                                            SBChat.openConversation(conversation.id);
                                        });
                                    }
                                });
                            

Create a new conversation and assign it to an agent

This use case explains how to create a new conversation, assign an existing agent to it, and allow only that agent to see the conversation in the administration area.


1 Enable the routing

Go to Settings > Miscellaneous, check the option Routing, and save.

2 Create a new conversation, and open it

Create a new conversation with the function SBChat.newConversation() of the JavaScript API and pass the agent ID 445 in the function' arguments. After the conversation is created, it's opened with the function SBChat.openConversation() .

                                $(document).on("SBInit", function () {
                                    if (SBF.activeUser() != false && SBF.activeUser().conversations.length == 0) {
                                        SBChat.newConversation(2, -1, "", [], null, 445, function (conversation) {
                                            SBChat.openConversation(conversation.id);
                                        });
                                    }
                                });
                            

Force a specific conversation

This use case explains how to set a specific conversation when a condition becomes valid and forces the user to use only such conversation until the condition remains valid. The below code uses the conversation title to understand what is the right conversation to use, it searches for the specific conversation by using its title, if it's found, it's opened, otherwise, a new conversation with the searched title is created. This use case can be used in different scenarios, for example, if you want to force the user to use a different conversation for different pages.


1 Insert this JavaScript code in your website

                                (function ($) {
                                    jQuery(document).on("SBInit", function () {
                                        let conversation_title = "CONVERSATION-NAME";
                                        let conversations = SBF.activeUser().conversations;
                                        if (conversations) {
                                            for (var i = 0; i < conversations.length; i++) {
                                                if (conversations[i].get("title") == conversation_title) {
                                                    SBChat.openConversation(conversations[i].id);
                                                    return;
                                                }
                                            }
                                        }
                                        SBF.ajax({
                                            function: "new-conversation",
                                            title: conversation_title
                                        }, (response) => {
                                            SBChat.setConversation(new SBConversation([], response["details"]));
                                        });
                                    });
                                }(jQuery));
                            

Replace CONVERSATION-NAME with the unique ID of the conversation you want to use.

If you're using the tickets area repalce SBInit with SBTicketsInit.


Force a specific department

This use case explains how to assign a specific department to a conversation when a condition becomes valid and forces the user to use only such conversation until the condition remains valid. The code below searches for a conversation with the desidered department, if it's found, it's opened, otherwise, a new conversation assigned to that department is created. This use case forces the user to use a different conversations and departments for different pages.


1 Insert this JavaScript code in your website

                                (function ($) {
                                    jQuery(document).on("SBInit", function () {
                                        let active_department = "YOUR-DEPARTMENT-ID";
                                        let conversations = SBF.activeUser().conversations;
                                        SBChat.default_department = active_department
                                        if (conversations) {
                                            for (var i = 0; i < conversations.length; i++) {
                                                if (conversations[i].get("department") == active_department) {
                                                    setTimeout(() => { SBChat.openConversation(conversations[i].id) }, 300);
                                                    return;
                                                }
                                            }
                                        }
                                        SBChat.open(false);
                                        SBF.ajax({
                                            function: "new-conversation",
                                            department: active_department
                                        }, (response) => {
                                            SBChat.setConversation(new SBConversation([], response["details"]));
                                        });
                                    });
                                }(jQuery));
                            

Replace YOUR-DEPARTMENT-ID with the ID of the department you want to use.

If you're using the tickets area repalce SBInit with SBTicketsInit.


Force a specific agent

This use case explains how to assign a specific agent to a conversation when a condition becomes valid and forces the user to use only such conversation until the condition remains valid. The code below searches for a conversation with the desidered agent, if it's found, it's opened, otherwise, a new conversation assigned to that agent is created. This use case forces the user to use a different conversations and agents for different pages.


1 Insert this JavaScript code in your website

                                (function ($) {
                                    if (typeof SB_DEFAULT_AGENT != 'undefined') {
                                         jQuery(document).on("SBInit", function () {
                                            if (!SBF.activeUser()) return;
                                            let conversations = SBF.activeUser().conversations;
                                            if (conversations) {
                                                for (var i = 0; i < conversations.length; i++) {
                                                    if (conversations[i].get("agent_id") == SB_DEFAULT_AGENT) {
                                                        setTimeout(() => { SBChat.openConversation(conversations[i].id) }, 300);
                                                        return;
                                                    }
                                                }
                                            }
                                            $('.sb-list').sbLoading(true);
                                            SBChat.open(false);
                                            SBF.ajax({
                                                function: "new-conversation",
                                                agent_id: SB_DEFAULT_AGENT
                                            }, (response) => {
                                                SBChat.clear();
                                                $('.sb-list').sbLoading(false);
                                                SBChat.setConversation(new SBConversation([], response["details"]));
                                            });
                                        });
                                    }
                                }(jQuery));
                            

In each of your pages Enter the code <script>var SB_DEFAULT_AGENT = 123</script> and change the agent ID with the one you want.

If you're using the tickets area repalce SBInit with SBTicketsInit.


Send a new message and open the chat

This use case explains how to send a new message, and open the chat after the message has been sent.


1 Send the message and open the chat

Check if the same message is already in the conversation with the method searchMessages() of the JavaScript API . If the message is not in the conversation send a new message with the function SBChat.sendMessage() . After the message is sent, open the conversation with the function SBChat.openConversation() , check if the chat is open, and if not, open it with the function SBChat.open() .

                                $(document).on("SBInit", function () {
                                    let message = "Do you want to buy the product on this page?";
                                    if (SBChat.conversation == false || SBChat.conversation.searchMessages(message).length == 0) {
                                        SBChat.sendMessage(SBF.setting("bot-id"), message, [], function (response) {
                                            SBChat.openConversation(response["conversation_id"]);
                                            if (!SBChat.chat_open) {
                                                SBChat.open();
                                            }
                                        });
                                    }
                                });
                            


Display the chat within the WordPress administration area

This use case explains how to display the chat within the WordPress administration area and automatically identify the logged-in WordPress user.


1 Enter the code in the functions.php file

Edit the file functions.php of your WordPress Theme (ex. /wp-content/themes/your-theme/functions.php) and Enter the code below at the bottom.

                                function sb_enqueue_admin_custom() {
                                    if (!key_exists('page', $_GET) || $_GET['page'] != 'support-board') {
                                        wp_enqueue_script('sbinit', SB_URL . '/js/main.js', ['jquery'], SB_VERSION);
                                        $current_user = wp_get_current_user();
                                        if (!empty($current_user->ID)) wp_add_inline_script('sbinit', 'document.cookie = "sb-login=false;expires=Thu, 01 Jan 1970 00:00:01 GMT;path=/;SameSite=None;Secure;" + (location.protocol == "https:" ? "SameSite=None;Secure;" : ""); var SB_WP_ACTIVE_USER = ' . $current_user->ID  . ';');
                                    }
                                }
                                add_action('admin_enqueue_scripts', 'sb_enqueue_admin_custom');
                            

If Settings > Miscellaneous > Cookie domain is set, add also the code domain=YOUR-VALUE to the cookie string above.