Examples: query, "exact match", wildcard*, wild?ard, wild*rd
Fuzzy search: cake~ (finds cakes, bake)
Term boost: "red velvet"^4, chocolate^2
Field grouping: tags:(+work -"fun-stuff")
Escape special characters +-&|!(){}[]^"~*?:\ - e.g. \+ \* \!
Range search: properties.timestamp:[1587729413488 TO *] (inclusive), properties.title:{A TO Z}(excluding A and Z)
Combinations: chocolate AND vanilla, chocolate OR vanilla, (chocolate OR vanilla) NOT "vanilla pudding"
Field search: properties.title:"The Title" AND text
 
Answered
Using Ajax in a UUXPayload extension

I'm working on adding a chat service to online banking pages using the UUXPayload extension type, but I wanted the ability to have the chat program have visability to some user information when activated. I noticed in the documentation the availablity of wedge configs to the JS, but could I use an ajax call from the static JS to get for example the user's name instead of just having the wedge configs pushed up as JS variables?

Posted 2 years ago
Votes Newest

Answers


Hi Justin,

Check out this example I put together for our UUX payload chat functionality. It subscribes to the login event, retrieves the user's ID, and makes two requests to the backend Python extension: one for wedge_config data and another for user_data.

If I remember correctly, there are some Q2 examples linked here as well:

https://docs.q2developer.com/guides/frontend_development/uux_payload.html

function consoleLog(message) {
    console.log("[{EXTENSION_NAME}] " + message);
}

consoleLog("chat.js running");

// gets the url of the chat.js file
scriptUrl = new URL(document.currentScript.src);

// takes the chat js url... removes chat.js from the end and gets the base path
assetPath = scriptUrl.origin + scriptUrl.pathname.split('/').slice(0, -1).join('/');

// chat SDK object
var webchat;

// Login event
const postLoginHook = function (userData) {
    consoleLog("in postLoginHook");

    if (userData.userId === 0) {
        return;
    }

    const postData = {
        "user_id": userData.userId
    };

    // Create the data string to send to the backend via the get_wedge_address_configs route in extension.py
    var getWedgeAddressConfigDataString = JSON.stringify({
        formData: `routing_key=get_wedge_address_configs&data=${btoa(JSON.stringify(postData))}`
    });

    // response from get_wedge_address_configs
    var wedgeConfigResponse;

    // Calls the python backend to retrieve form data from the get_wedge_address_configs route
    // 'mobilews/form/{EXTENSION_NAME}' will change based on your extension's name
    wedgeIntegrationController.get('store').sendRequest(getWedgeAddressConfigDataString, 'mobilews/form/{EXTENSION_NAME}', function (data) {
        consoleLog("data returned from get_wedge_address_configs");
        wedgeConfigResponse = JSON.parse(data.data.forms[0]);
        console.log(wedgeConfigResponse);

        // This is the success handler for get_wedge_address_configs, user has been entitled to the "{EXTENSION_NAME}" form
        // Do something here with the data/token/cookie
        // If you want to only initialize your Chat if the user is "entitled", do so in this success callback

        if (wedgeConfigResponse.data['WebchatEnabled']) {
            consoleLog("webchat enabled");

            if (wedgeConfigResponse.data['WebchatOpen']) {
                consoleLog("webchat within business hours");

                // Create the data string to send to the backend via the get_online_user_data route in extension.py
                var userDataDataString = JSON.stringify({
                    formData: `routing_key=get_online_user_data&data=${btoa(JSON.stringify(postData))}`
                });

                // response from get_online_user_data
                var userDataResponse;

                // Calls the python backend to retrieve form data from the get_online_user_data route
                // 'mobilews/form/{EXTENSION_NAME}' will change based on your extension's name
                wedgeIntegrationController.get('store').sendRequest(userDataDataString, 'mobilews/form/{EXTENSION_NAME}', function (data) {
                    consoleLog("data returned from get_online_user_data");
                    userDataResponse = JSON.parse(data.data.forms[0]);
                    console.log(userDataResponse);

                    // This is the success handler for get_online_user_data, user has been entitled to the "{EXTENSION_NAME}" form
                    // Do something here with the data/token/cookie
                    // If you want to only initialize your Chat if the user is "entitled", do so in this success callback

                    if (userDataResponse.data["enabled_for_user"]) {
						consoleLog("webchat enabled for logged in user");
						// Init webchat
                        
                    } else {
                        consoleLog("webchat disabled for logged in user");
                    }
                }, function () {
                    console.error("Failed to get online user data");
                }, 'POST');
            } else {
                consoleLog("webchat outside of business hours");
            }
        } else {
            consoleLog("webchat disabled");
        }
    }, function () {
        console.error("Failed to get wedge configuration data");
    }, 'POST');
}

function afterLogoffHook() {
    // Handle logoff event and perform any necessary cleanup
    // Notify your server that the session has been terminated
    webchat = null;
}

function ready(fn) {
    if (document.attachEvent ? document.readyState === "complete" : document.readyState !== "loading") {
        fn();
    } else {
        document.addEventListener('DOMContentLoaded', fn);
    }
}

// Everything below here can be ignored, just registration boilerplate

var _uux_payload_registered = false;

var register = function () {
    if (window.Ngam && !_uux_payload_registered) {
        // this is a bunch of backwards compatibility afordances to make sure the hook registers
        var loginFlow = Ngam.__container__.lookup('service:loginFlow');
        var loginController = Ngam.__container__.lookup('controller:login');
        var loginFlowReq = loginController && loginController.get('loginFlowRequirements');
        if (loginFlow && loginFlow.authenticatedStatus === 200) {
            postLoginHook(loginFlow);
        } else if (loginFlowReq && loginFlowReq.authenticatedStatus === 200) {
            postLoginHook(loginFlowReq);
        } else {
            Ngam.__container__.lookup('controller:application').get('notificationCenter').on('POST_LOGIN', postLoginHook);
        }
        Ngam.__container__.lookup('controller:application').get('notificationCenter').on('BEFORE_LOGOFF', afterLogoffHook);
        _uux_payload_registered = true;
    }
};

window.addEventListener('load', register);
ready(register);
setTimeout(function () {
    register();
});

if (window.Ngam) {
    register();
}
Posted 2 years ago
0

I would like to add that the userData has a lot of good information about the current user. This is what I used to grab user info and pass along to the agent on the other side of the chat conversation. See below:

function setContext() { webchat.setContextParam({ "userId": userData.userId, "firstName": userData.firstName, "lastName": userData.lastName, "logonName":userData.loginName, 'source':'Desktop'}) }

— Bradley Bell   2 years ago
142 Views
1 Answer
2 years ago
2 years ago