SDK Wrapper Specifications

View the list of functions and events used by the webMethods.io Embed SDK, along with their descriptions.

Common Functions

Below is the list of common functions provided by webMethods.io Embed SDK:

Note: While consuming the webMethods.io Embed SDK, follow promises paradigm, as each function inside the SDK supports only promises.

  1. SDK Initializer
    There are two ways to initialize the Embed SDK in a front-end application:
    a) Using Embed API request
    b) Using init() function

    • Initializing Embed SDK using Embed API request

      Perform the following three steps to initialize the Embed SDK using the Embed API request:

      Step 1: Send initializer API request to Embed server

      Send the following initializer API request from your backend server to Embed server:

      Request details:
      URL: {Embed_API_Server}/embed/v2/embed/synergy/initializer/create
      Method: POST
      Headers:

      • identifier: , //Retrieve the identifier by navigating to Settings > Developer Tools > Identifier in the Embed Admin Portal
      • jwt: (OPTIONAL header)
      • Note: If you want to login the user along with initializing the SDK, you need to send a JWT signed string which is encrypted using an API_KEY.

        Given below is the sample code to create a JWT:

        const jsonwebtoken = require(‘jsonwebtoken’)
        const API_KEY = // Settings -> Developer Tools -> API Key
        const user = {
        consumer_uid : , //
        domain : , // Settings -> Developer Tools -> Domain
        plan : “,
        time : new Date().getTime() }
        var jwt = jsonwebtoken.sign(user, API_KEY);
        console.log(jwt);

      If the request is completed successfully, the Embed server sends a hash key in response.

      Step 2: Send the hash key from your backend server to frontend server
      You can use your preferred method to send the hash key from the backend server to the frontend application.

      Step 3: Use the fetchInitializerKeys function to fetch initializer keys

      fetchInitializerKeys({String hash_key, String api_host(OPTIONAL)}, callback)
      This function fetches the keys required to initialize the Embed SDK and returns the Embed object. It performs a handshake with the API server and checks whether the provided key combination is valid or not. Since the basic communication rules are set by this function, it must be called before any other function provided by the SDK.

      FlowEmbed.revalidateKeys(IDENTIFIER, callback)
      When you call this function, it allows Embed SDK to use older initializers. On each refresh of the page, we cannot make a new initializer call to the backend component. Instead of making a new API call, use this function to verify whether the older communication is working or not. If the validation is correct then it returns an Embed object as following:

      FlowEmbed.revalidateKeys(IDENTIFIER, (err, embed) => {
         if(embed) {
             window.Embed = embed;
             start(embed);
             return cb(err,embed);
         }
        // below is the function call to initialize embed sdk
         return initiateEmbedSDK(cb)
      })

      If the identifier doesn’t match or it fails to use an older initializer then the function throws an error “Initialization failed”. On receiving this error, you have to make a new initializer request to the backend server.

      Sample Code to initialize the Embed SDK using API request:

      function start(Embed) {
      Embed.on('logout', logoutUser);
      }
      function initiateEmbedSDK(cb) {
      
      const API_DOMAIN = "" // Your backend server domain
      const API_INITIATE_ROUTE = "" // Newly created route for SDK initializer in your backend component
      const IDENTIFIER = "" // Settings -> Developer Tools -> Identifier
      const USERNAME = ""  // <Any string>
      const EMBED_API_ENDPOINT = "" // Custom Embed API Server
      var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
         if (this.readyState == 4 && this.status == 200) {
             var hash_key = null;
             try{
                 hash_key =  JSON.parse(this.responseText).output.key;
             } catch(e){
                 hash_key = "";
             }
             if(!hash_key) {
                 try{   
                     showLoginErrorMessage(JSON.parse(this.responseText).error.message);
                     return;
                 } catch(e) {
                     console.log(this.responseText);
                     return;
                 }
             }
             FlowEmbed.fetchInitializerKeys({hash_key, (optional)api_host: EMBED_API_ENDPOINT }, (err, embed) => {
      
                 if(err) {
                     try{
      
                         return showLoginErrorMessage(JSON.parse(err).user.message);
                     } catch(e) {
                         return showLoginErrorMessage(err);
                     }
                 }
                 window.Embed = embed;
                 start(embed);
                 if(typeof cb === "function" ) {
                     return cb(err, embed);
                 } else {
                     embed.on('ready', () => {
                         window.location = "/";
                     })
                 }
             });
         }
         if(this.readyState == 4 && this.status != 200) {
             console.log("Err - ", this.responseText);
         }
      };
      
      xhttp.open("POST", API_DOMAIN + API_INITIATE_ROUTE, true);
      
      // Identifer and email can be sent via body, headers as per your requirement.
      xhttp.setRequestHeader('identifier', IDENTIFIER);
      if(USERNAME)
         xhttp.setRequestHeader('consumer_uid', USERNAME);
         xhttp.send();
      }

      Error Message
      The fetchInitializerKeys function throws the following error if the IP address of your API server is not registered with your Embed tenant: You don’t have the necessary permissions to perform the specified operation.
      In the Developer Tools screen in Admin Portal, we can add an IP Range to restrict API servers from accessing tenant information via initializer request. This only works for step 1.

    • Initializing Embed SDK using init() function

      init(String identifier, String source_token, String master_token, String environment, String version , String api_host, String exhibit)

      This function initializes the SDK. It performs a handshake with the API server and checks whether the provided key combination is valid or not. Since the basic communication rules are set by this function, it should always be called before any other function provided by the SDK.

      Parameter details:

      • identifier: Retrieve the identifier by navigating to Settings > Developer Tools > Identifier in the Embed Admin Portal.
      • source_token: Retrieve the source token by navigating to Settings > Developer Tools > Source Verification Token in the Embed Admin Portal.
      • master_token: Retrieve the identifier by navigating to Settings > Developer Tools > Master Token in the Embed Admin Portal.
      • environment: sandbox or production
      • version: v2
      • api_host: domain for API server (default: null)
      • exhibit: Set this to ‘true’ disable the encryption/decryption mechanism.
      • Note: Since the client-side JavaScript does not maintain state, you need to initialize the SDK using the init function while reloading or redirecting to any particular page.

      Sample Code for initialize SDK:

      window.Embed = FlowEmbed.init( identifier, source_verification_token, master_token, environment, "v2", null, false);
      //Below is the logout listener code
          window.Embed.on("logout", function () {
              logoutUser();
          });

  2. login(String jwt_signed_token)

    This function logs in the user present inside the JWT token.

    Note: To log in the user along with SDK initialization, send a JWT signed string which is encrypted using an API_KEY.

    Code snippet for JWT token generation:

    const jsonwebtoken = require('jsonwebtoken')
         const API_KEY = <API_KEY> // Settings -> Developer Tools -> API Key
          const user = {
                   consumer_uid : <username>, // <Any string>
                   domain : <tenant domain>,   // Settings -> Developer Tools -> Domain
                   plan : '',
        time: new Date().getTime()
      }
    var jwt = jsonwebtoken.sign(user, API_KEY);
    
    
    //Please use hmac256 encryption algorithm

    Sample code:

    window.Embed.login(d).then(
    () => {
    window.location = "/";  // redirect to home page
        },
        (err) => {
            console.log(err);
            window.location = "/login"; 
        }
    }
    );

    Note: plan code can be found under the Plans tab in the Embed Admin portal.

  3. setActive(deployment_uid, Boolean status) - requires login

    This function turns the specified deployment active or inactive based on the value of status.

    Sample Code:

    let el = document.getElementById('#deployment_elemenet_id');
    var status = true;
    if(el.dataset.active === "true"){ //set active status in dataset of deployment element
    status = false;
    }
    window.Embed.setActive(<deployment_uid> ,status, (res) => {
        if(status)
        el.dataset.active = "true";
        else
     el.dataset.active = "false"
    
     }, (err) => 
    {
    console.log(err);
    })

  4. deleteDeployment(deployment_uid) - requires login

    This function deletes the specified deployment from the list of deployments available in the current user’s account.

    Sample code:

    window.Embed.deleteDeployment(deployment_uid).then(function (response) {
        showNotification('success','Integration deleted successfully.', 5);
        location.reload(); // To fetch updated deployment records
    }, 
    function (err) {
        console.log(err);
    })

  5. getMyIntegrations() - requires login

    This function retrieves a list of all deployments added in the current user’s account.

    Note: You can use getMyDeployments() for optimized pagination (sdk-version 2.1.42 and further).

    Sample Code:

    get({skip, limit,  query: {"name" : {"$regex" : search, "$options" : "gmi"}}, fields});
    
    function get(obj){
        $('#loader-wrapper').show();
        window.Embed.getMyIntegrations({skip: obj.skip || 0, limit : obj.limit || 15, query: obj.query},fields : ['flows']).then(function(res){
            showIntegrations(res.flows);
            viewPagination(res);
            $('#loader-wrapper').hide();
        })  
    }

  6. getMyDeployments() – requires login (sdk-version: 2.1.42)

    This function retrieves a list of all deployments added in the logged in user’s account.

    Sample Code

    get({limit,  name: {"name" : {"$regex" : search, "$options" : "gmi"}}, fields: [‘flows’], tags: ‘tag1’, next_sort_date: ‘2022-10-11T10:38:20.237Z’});
    
    function get(obj){
        $('#loader-wrapper').show();
        window.Embed.getMyDeployments({limit : obj.limit || 15, query: obj.query}, fields : obj.fields, tags: obj.tags, next_sort_date: obj.next_sort_date)
        .then(function(res){
            showIntegrations(res.flows);
            viewPagination(res);
            $('#loader-wrapper').hide();
        })  
    }

  7. getConnectors()

    This function retrieves a list of connectors/services from the set of available solutions. The Response object contains connector/service name, icon, title, and solutions_count.

    Sample Code:

    window.Embed.getConnectors().then((resp)=>{
        var divs = [];
        for(var i = 0; i < resp.length; i++){
            var a = resp[i];
            if(a.name === "developertools")
            continue;
            if(a.name === "devtools-logger")
            continue;
            var str = '<div data-name="'+a.title+'" class="servicename col-2 center-align mb-30">' +
            '<div class="row">' +
                '<div class="service-link">'+
                    '<a href="/solutions/' + a.name +'" class="mbxl service-icon">'+ window.Embed.getIcon(a,90) + '</a>' +
                '</div>'+
                '<div class="action-details">' +
                    '<a href="/solutions/' + a.name + '" class="action-name block"><span class="action-name-search">'+ a.title+ '</span></a>' +
                    '</div> </div> </div>';
                    divs.push(str);
        }
        divs = divs.join("");
        var list_content = document.querySelector("#connector-list")
        list_content.innerHTML += divs;
        $('#loader-wrapper').hide(); 
    },(err)=>{
        console.log(err);
    })

  8. getTemplatesByConnector(String connector_name, [String field_name1, String field_name2](optional), String solution_type(optional))

    This function retrieves a list of all active solutions associated with the specified connector/service. The solution type can be webhook or default.

    Sample Code:

    let connector = ""; // Use value of `name` key of response of getConnector function.
    let fields = ["version", "is_head", "published", "action_icons", "sandbox_version", "trigger_icon", "name", "published_on", "uid", "context", "environment", "custom_connector_exists"]
    window.Embed.getTemplatesByConnector(connector, fields).then((resp)=>{
        $('#loader-wrapper').hide();
        var list_content = document.querySelector("#solutions-list")
        let path = window.location.pathname;
        for(var i = 0; i < resp.length; i++){
    
            var a = resp[i];
            var li = document.createElement('li');
            li.classList.add('inline-block');
            li.classList.add('clearfix');
            li.classList.add('col-12');
            li.classList.add('left');
            li.classList.add('ptm');
            li.classList.add('pbm');
    
            var solutionName = document.createElement('p');
            solutionName.classList.add('left');
            solutionName.classList.add('col-6');
            solutionName.classList.add('ellipsis');
            solutionName.classList.add('prl');
            solutionName.innerText = a.name;
            solutionName.title = a.name;
    
            var icon = document.createElement('div');
            icon.classList.add("left");
            icon.classList.add("col-4");
            icon.classList.add("content-limit");
            icon.innerHTML = window.Embed.getIcon(a,30);
    
            var add = document.createElement('a');
            add.classList.add('btn');
            add.classList.add('btn-primary');
            add.classList.add('add-button');
            add.classList.add('right');
            add.innerText = 'Add';
            add.id = i;
            add.dataset.path = path+'/'+a.uid
    
            add.addEventListener('click',  (e) => redirectToFormPage(e.target.dataset.path));
    
            if(isLoggedIn()) {
                li.append(solutionName);
                li.append(icon);
                li.append(add);  // Only loggedin use can view the form
            } else{
                li.append(solutionName);
                li.append(icon);
            }
        }
    },(err)=>{
    console.log(err);})

  9. getTemplates([String field_name1, String field_name2])
    Retrieves a list of all active solutions available to the user. Users can pass specific field names they want to fetch along with the solution, in the form of an array of strings.

    Sample Code:

    fields = ["version", "is_head", "published", "action_icons", "sandbox_version", "trigger_icon", "name", "published_on", "uid", "context", "environment", "custom_connector_exists"]
        window.Embed.getTemplates(fields).then((resp) => {
        listTemplates(resp);
    }, (err)= {
        console.log(err);
    })

  10. getDeploymentIcons(Object deployment, String|Number size)

    This function retrieves a strip of HTML containing icons of trigger and actions used in the specified deployment. This function is especially useful while listing solutions/deployments. Icon size can be of 16/24/28/30/36/40/45/48/50/64/70/80/90/96/128 pixels.

    Sample Code:

    var deployment_obj = {trigger_icon: “webhook”, action_icons: [“trello”,”asana”]};
    var size = 30;
    var element = window.Embed.getDeploymentIcons(deployment_obj, size);
    Add above element in DOM.

  11. getIcon(Object obj|String icon, Number size)

    This function retrieves icon for the specified object. This function is especially useful for displaying connector icons. Icon size can be of 16/24/28/30/36/40/45/48/50/64/70/80/90/96/128 pixels.

  12. Sample Code:

    var icon = “trello”
    var obj = {icon: “trello”};
    var size = 30;
    var element = window.Embed.getIcon(icon, size);
    Add above element in DOM.

  13. logout() - requires login

    This function logs out the user. After successful logout, the ‘logout’ event is raised which can be caught by the client JavaScript to perform other tasks. Event listeners can be attached and removed by using ‘on’ and ‘off’ methods. On logout, all the local storage and event listeners are removed.

    Once user clicks on the Logout button, perform below logout operation using SDK’s logout function.

    function embedLogout() {
        window.Embed.logout();
    }

  14. getAuths(provider, searchPattern) - requires login

    This function fetches all auths associated with the currently logged-in user for the specified provider. There are two function parameters required, first is provider which is mandatory and second is searchObject which is optional. For searchObject, we can fetch objects by label of auth.

    Note: This function can be in custom form-render to fetch the user’s auth based on the provider and show it as options in the select box.

    Sample Code:

    var provider = “asana”;
    var searchObject = {“label”: “Asana_12345687”}; // This is optional
    Embed.getAuths(provider , searchObject ).then((resp) => {
        listUserAuthOptions(resp);
    },
    (err)=> {
    console.log(err);
    })

  15. validateToken()

    This function checks whether the user is logged in or not. This function calls the ‘logout’ event internally if the session of the user is invalid. Make sure that you have logout functionality handled in your application.

    Sample Code:

    window.Embed.on('ready', () => {
        window.Embed.validateToken();
    })

  16. getDeploymentStats(Array deployments, Object params(optional))

    This function retrieves the number of executions for some or all deployments. Deployments should be passed as an array. If the array is left blank, it returns the execution statistics for all deployments. Optionally, ‘params’ can be used to enable pagination functionality with the ‘skip’ and ‘limit’ properties.

    Sample Code:

    var deployment = [ 'deployment_uid1', 'deployment_uid2' ... ]; // deployment array can be empty
    var params = {“skip”: 0,”limit”:15}
    window.Embed.getDeploymentStats(deployment, params).then((resp)=> {
        //resp is array of object which has following keys - flow_uid, title, runcount
        listDeploymentStats(resp);
    }, (err)=> 
    {
    console.log(err);
    })

  17. getConsumerUsage()

    This function retrieves the total number of executions that have been done by the user. If the tenant is transaction based then skip the available key as it won’t matter.

    Sample Code:

    window.Embed.getConsumerUsage().then((res)=> {
        document.querySelector("#used-usage").innerHTML = "Used : " + res.used_credits;
        if(res.available &&  !res.is_transaction_tenant) {
        document.querySelector("#available-usage").innerHTML = "Available : " + res.available;
        }
        document.querySelector("#plan-type").innerHTML = "Plan Name : " + res.plan_name;
    }, 
    (err)=> {
    console.log(err);
    })

  18. getConsumerUsageByDate(startDate, endDate(optional))

    This function retrieves the total number of executions that were performed by the user for a specific date frame.

    Sample Code:

    var startDate = "YYYY-MM-DD"; // optional
    var endDate = "YYYY-MM-DD"; // optional
    window.Embed.getConsumerUsageByDate(startDate, endDate).then((resp)=> {
        listExecutions(resp)
    }, 
    (err)=> {
    console.log(err);
    })

  19. getExecutions(Object params)

    This function retrieves all executions with respect to the consumer/user. ‘params’ can be used to enable pagination functionality with the ‘skip’ and ‘limit’ properties.

    var params = { limit: 15, skip: 0 }
    window.Embed.getExecutions(params).then(function(res){
        showExecutionLogs(res.objects);
        viewPagination(res);
    }) 

    To filter execution logs:

    You can filter out specific execution logs based on date & time, integration name, and execution status. This is achieved by setting parameters (to_date, from_date, deployment_flow_uid, execution_status) respectively.

    getExecutionLogs(obj):

    Called: On initial render and by filterData( ) i.e. when Apply Filter button is clicked.

    Parameter: obj containing {skip, limit, from_date, to_date, deployment_flow_uid, execution_status} keys depending on the filter selected.

    Notes:

    • It is not mandatory to provide all keys present in the obj definition. You can provide keys relevant to your search.
    • If ‘to_date’ key is provided, it’s necessary to provide ‘from_date’ as well and vice versa.

    Functionality:
    Clears previous execution logs (if any)
    Loader util response
    Get filterObj i.e. {to_date, from_date, deployment_flow_uid, execution_status} from obj if key is passed.
    Get response from getExecutions(obj) and populate the response.

    Sample Code

    function getExecutionLogs(obj) {
     // clear previous execution logs
     // get deployment_flow_uid, execution_status, from_date, to_date from respective dropdown
     let filterObj = getDeploymentFlowUid_ExecutionStatus_FromDate_ToDate(obj)
     //calling API to get execution-logs as res
     window.Embed.getExecutions({
     skip: obj.skip || 0,
     limit: obj.limit || 15,
     ...filterObj,
     }).then(function (res) {
     showExecutionLogs(res.objects)
     enableApplyResetBtn()
     viewPagination(res, filterObj)
     })
     }

    getDeploymentFlowUid_ExecutionStatus_FromDate_ToDate(obj):

    Called: By getExecutionLogs(obj)

    Parameter: obj containing {skip, limit, from_date, to_date, deployment_flow_uid, execution_status} It is not mandatory to provide all keys present in the obj definition. You can provide keys relevant to your search.

    Functionality: Returns an obj {deployment_flow_uid, execution_status, from_date, to_date} if key exists, by calling returnKeyValueObjIfKeyExists(obj, key)

    Sample Code

    function getDeploymentFlowUid_ExecutionStatus_FromDate_ToDate(obj){
      let tempObj;
      tempObj = {
        ...(returnKeyValueObjIfKeyExists(obj,"deployment_flow_uid")),
        ...(returnKeyValueObjIfKeyExists(obj,"execution_status")),
        ...(returnKeyValueObjIfKeyExists(obj,"from_date")),
        ...(returnKeyValueObjIfKeyExists(obj,"to_date")),
     }
     return tempObj
    }

    returnKeyValueObjIfKeyExists(obj, key):

    Called: By getDeploymentFlowUid_ExecutionStatus_FromDate_ToDate(obj)

    Parameter: {obj, key}

    Functionality: Returns an object with key-value pair if key exists in the obj.

    Sample Code

    function returnKeyValueObjIfKeyExists(obj, key) {
       if (obj[key] !== undefined)
       return {[key]: obj[key]};
     }

  20. getExecutionLogs({bill_uid, limit, skip})

    This function retrieves the execution logs of particular execution. Bill uid can be found in response of getExecutions function.

    Sample Code:

    var bill_uid="bill_uid1"   
    
        window.Embed.getExecutionLogs({logUid:bill_uid, limit:Number(limit), skip:Number(skip)}).then(function(res) {
        var userstream_logs = res.objects.filter((log) => { return log.type != 'bill' });
        var activityLog = userstream_logs ? userstream_logs.sort() : [];
        var isLoading = true;   
        var modal = document.querySelector("#activity-logs-modal");
        var title = `Execution Logs: ${htmlEncode(obj.flow_name)}`;
        var modalHeader = document.querySelector('.modal-title');
        modalHeader.innerText = title;
        // modal.innerHTML += "<div class='modal-container'><div class='modal-header pbm'><h3>Execution Logs: "+obj.flow_name+"</h3></div><div class='modal-body'><table class='logs-table'><thead><th class='width-45'>Action</th><th>Start</th><th>End</th></thead><tbody id='logs-modal-body'></tbody></table></div><div class='modal-footer clearfix mtxl'><button class='btn secondary-btn' onclick='closeLogsModal()'>Close</button></div></div>";
        if(activityLog && activityLog.length){
            for(var i=0; i<activityLog.length; i++){
                var start_date = new Date(activityLog[i].time_stamp);
                start_date = start_date.toLocaleString().split(",");
                var end_date = new Date(activityLog[i].stop_time_stamp);
                end_date = end_date.toLocaleString().split(",");
                var message = activityLog[i].error ? activityLog[i].message_exp : activityLog[i].activity_name;
                logsRow.innerHTML += "<tr><td class='width-45'>"+message+"</td><td class='center-align'>"+start_date[1].trim()+"</td><td class='center-align'>"+end_date[1].trim()+"</td></tr>";
                isLoading = true;
            }           
        }else{
            logsRow.innerHTML += "<tr><td colspan='3' class='center-align'>No Logs</td></tr>";
            isLoading = true;
        }
        if(res.total > 200){
            viewPagination(res,'fromGetDetailedExecutionLogs', obj);
        }
        if(isLoading){
            setTimeout(function(){
                modal.style.display = "block";
                viewLogElement.style.pointerEvents = 'auto';
            }, 1000);
        }
    }, (err)=> {
        viewLogElement.style.pointerEvents = 'auto';
        console.log(err);
    })

  21. createProject()

    Note: If you are using the Embed SDK version 2.1.21 or above, you need not use this function. The Embed SDK automatically executes this function on your behalf whenever required.

    This function creates a project for your tenant account. Before initializing the solution use this function to create a project. If the workflow contains a custom connector then window.Embed.createProject(obj) requires the following object to be passed while calling the function. {custom_connector_exists, solution_uid, solution_version}

    Sample code for this function:

    function createProject(link, solution) {
    localStorage.removeItem('project')
    var projectCreatePayload = {};
    if(solution && solution.hasOwnProperty("custom_connector_exists") && solution.uid && solution.version) {
       projectCreatePayload = {
           custom_connector_exists : solution.custom_connector_exists,
           solution_uid : solution.uid,
           solution_version : solution.version
       }
    
    }
    window.Embed.createProject(projectCreatePayload).then((res) => {
       window.location = link;
    }, (err) => {
       console.log(err);
    })
    }

  22. getSolutionsByBotId()

    This function retrieves all active solutions added inside a bot.

  23. getBotTokenByBotId

    This function retrieves bot information.

  24. getConsumer(string consumer_uid)

    This function retrieves logged in consumer’s information.

    Sample Code:

    var consumer_uid = 'consumer_uid1'; // Default value is `me`
    Embed.getConsumer(consumer_uid).then((resp) => {
        var consumer_object = resp
    }, (err) => {
    console.log(err);})

  25. getSolution(solution_uid)

    This function retrieves active solution or template object.

    Sample Code:

    var solution_uid = "solution_uid1";
    Embed.getSolution(solution_uid).then((resp) => {
        var solution_object = resp;
    }, (err) => {
    console.log(err);})
    Solution object looks like this:
    {
    action_icons: ['wunderlist']
    context: "sandbox"
    created_at: "2019-09-23T08:08:17.278Z"
    environment: {project_params: Array(3)}
    name: "wunderlist solution"
    origin: "fl1bbbb41190879222069006"
    output: []
    published: true
    published_on: "2019-09-23T08:08:17.268Z"
    trigger_icon: "wunderlist"
    uid: "fl281b3493f53286088c6e471"
    updated_at: "2020-06-30T14:02:28.694Z"
    version: 2
    }

  26. getTenant(provider)

    This function checks whether OAuth is present or not with the specified provider. If OAuth is not present for the specified provider, then the function returns {tid: “builtio”} otherwise it returns metadata of the OAuth. Whenever you use addAuth function, this function checks internally if there is an oauth present with a given provider or not.

    Sample Code:

    window.Embed.getTenant(provider, identifier ).then((resp) => {
        var data = resp;
        if(data && data.hasOwnProperty('t') && data.t != "builtio"){\
        You can continue with tenant oauth creation process eg. (Embed.createUserTenantOauth() function);             
        }else{
        You can continue with auth process eg. (Embed.addAuth() function)
        }
    }, (err) => {
        console.log(err);
    })

  27. performOperation(operation_obj)

    To access this function, you need to enable the Bots feature for your tenant. This is a custom method to perform several operations.

  28. createUserTenantOauth(oauth_obj)

    This function allows users to create a new OAuth for a tenant.

    Sample Code

    var obj = {
        provider : provider,
        identifier: domain, // This is depend on connector ex. (for servicenow connector, identifier will be the domain of the servicenow instance)
        description : "description",
        params : {
            client_id : clientId,
            client_secret : clientSecret,
            redirect_uri : redirectURI // format -> `${authHost}/oauth/${provider}/tenant/${tenant_uid}/env/${env_uid}/identifier/${domain}/return`
            ... //other keys are depened on connector
        }
    }
    
    window.Embed.createUserTenantOauth(obj).then((resp) => {
        // once you get response of tenant Oauth creation, you can continue with auth process eg. (Embed.addAuth() function)
    }, (err) => {
        console.log(err);
    })

  29. setConnectorFields (payload)

    To access this function, you need to enable the Bots feature for your tenant. This function is used to store metadata of the user.

  30. getConnectorFields (payload)

    To access this function, you need to enable the Bots feature for your tenant. This function is used to fetch metadata of the user.

  31. getAuthtoken()

    This function retrieves logged in user’s auth token. If the user is not logged in, then the function returns ‘undefined’.

    Sample Code:

    var authtoken = window.Embed.getAuthtoken();

  32. createErrorLog(Object)

    This function adds custom error logs.

    Object must contain operation, module, and error key where-
    - operation - READ/WRITE/UPDATE/DELETE
    - module - any module (ex. Solution, Deployment)
    - error - Error message or object.

    Sample Code:

    Embed.createErrorLog({"operation": "READ", "module" : "CustomError", "error" : {“message” :"error encountered"}});

  33. getConsumerAuths({label, limit, next_sort_date, prev_sort_date}) (sdk-version: 2.1.41)

    This function retrieves the list of authorizations along with the following properties associated with them: {uid, project_uid, label, provider, method}

    Parameters
    - label: To search auth (partial/complete) (optional parameter)
    - limit: Number of authorizations to be fetched
    - next_sort_date/ prev_sort_date: To fetch next and previous authorization list for pagination respectively

    Sample Code

    function getConsumerAuths() {
    let name = "Marketo123456";
    let next_sort_date = "2022-10-11T10:38:20.237Z";
    var $element = document.getElementById('auth-list');
    window.Embed.getConsumerAuths({label: name, limit:15, next_sort_date}).then((resp) => {
        $element.innerHTML = '';
        let list = resp.items;
        listConsumerAuths(list);
        viewPagination(resp);
     }, (err) => {
        console.log("Error while fetching userauths", err);
     })
     }

  34. getConsumerConnections({label, limit, next_sort_date, prev_sort_date}) (sdk-version: 2.1.41)

    This function retrieves a list of connections along with the following properties associated with them: {uid, project_uid, label, provider, method}.

    Parameters
    - label: To search auth (partial/complete) (optional parameter)
    - limit: Number of connections to be fetched
    - next_sort_date/ prev_sort_date: To fetch next or previous connection list for pagination respectively

    Sample Code

    function getConsumerConnections() {
    let name = "Pagerduty123456";
    let next_sort_date = "2022-10-11T10:38:20.237Z";
    window.Embed.getConsumerConnections({label: name, limit:15, next_sort_date}).then((resp) => {
        let list = resp.items;
        listConsumerAuths(list);
        viewPagination(resp)
    }, (err) => {
        console.log("Error while fetching userauths", err);
    })
    }

  35. updateAuth({auth_uid, project_uid, label, provider, customAuthFormRender, scopeScreen, closeScopeScreen, method}, cb)
    (sdk-version: 2.1.41)

    This function updates the authorization associated with the specified auth_id.

    Parameters
    - auth_uid, project_uid, label, provider, method: These keys can be obtained using the getConsumerAuths() function
    - customAuthFormRender(): Renders custom authorization modal using renderForn()
    - scopeScreen(scopes): Creates modal for updating authorization with the provided scopes
    - closeScopeScreen(scopeElement): Closes modal created by scopeScreen() for the provided scope element
    - cb: Callback function

    Sample Code

    function updateAuth() {
    let auth_uid = 'au12345fbace123b1234d91c6cd698f5726dfdb';
    let project_uid = 'fl1a1f1cc12345aaa1d1ad12';
    let label = '"Trello_0123456789';
    let provider = 'trello';
    
    if( !auth_uid || !project_uid || !label || !provider) {
        console.log("Update auth parameter missing");
        return;
    }
    
    // Custom form to update auth depending on the schema
    function customAuthFormRender(cs, cb) {
        try {
          custom_auth_schema = JSON.parse(cs);
        } catch (e) {
        console.error("Custom auth schema is invalid.");
        return;
        }
        var $formElement = document.querySelector("#update_auth_form");
        window.Embed.renderForm($formElement, {schema: custom_auth_schema, value:{}, isCustomAuth: true});
        var cbSuccess = (data) => {
            let updateAuthModal = document.getElementById("update-auth-title-modal");
            updateAuthModal.innerHTML='';
            $formElement.innerHTML = '';
            window.Embed.off('form.submit', cbSuccess);
            return cb(data);
        };
        window.Embed.on('form.submit', cbSuccess)
        var cbFailed = () => {
            $formElement.innerHTML = '';
            window.Embed.off('form.cancel', cbFailed);
        } 
        window.Embed.on('form.cancel', cbFailed );
    }
    
    window.Embed.updateAuth({auth_uid, project_uid, label, provider, customAuthFormRender, scopeScreen, closeScopeScreen, method}, (err, resp) => {
        if(err) {
            showNotification('error', 'Auth update failed', 5);
        }
        if(resp) {
            showNotification('success', 'Auth updated successfully', 5);
            let $input = document.getElementById('auth_label');
            ($input) && getConsumerAuths($input.value);
        }
        closeUpdateAuthTitle();
    })
    }

  36. updateConnection({data, connection_uid, provider, project_uid }) (sdk-version: 2.1.41)

    This function updates the connection or account associated with the specified connection_uid. It verifies the data provided for connection before updation.

    Parameters
    - {connection_uid, provider, project_uid}: These keys can be obtained from using getConsumerAuths() function
    - data: Data can be obtained by using the render_IC_connection_form() or the renderForm() function.

    Sample Code

    // Create modal to update connection
    async function updateConnectionForm() {
    let auth_uid = "uconn123f851bfc4eb123a6148c123dc124534d1a7e97";
    let label = "Pagerduty_Connection_0123456789";
     let provider= "pagerduty_-1abcAZqw";
     let project_uid="fle3a9876a123ca1cb12345ddea5e9f6f";
    
    let connectorSchema = await Embed.getConnectorSchema(provider);
    if(connectorSchema && connectorSchema.form_schema) {
        let schema = connectorSchema.form_schema;
        // check if the provider is CloudStream Connector
        var isIC = isICConnector(provider);    
        try{
            if(isIC){
                schema = schema[0].fields;
            } else {
                schema = JSON.parse(schema);
            }
        } catch(e) { 
            console.log('Error while parsing connection schema - ',schema); 
            return null;
        };
        // Disable label property
        if(isIC) {
            schema[0].defaultValue = label;
            schema[0].propertyValue = label;
            schema[0].disabled = true;
        } else {
            schema.properties.label.disabled = true;
        }
        var $formElement = document.querySelector("#update_auth_form");
        // ================== Add IC form render function
        if(isIC) {
            render_IC_connection_form(schema, $formElement, (data) => {
                $formElement.innerHTML = '';
                $formElement.style.display = "none";
                return updateConnection({data: data, project_uid, connection_uid: auth_uid, provider});
    
            });
        } else {
            window.Embed.renderForm($formElement, {schema, value:{label}, isConnection: true});
            var cbSuccess =  (data) => {
                $formElement.innerHTML = '';
                $formElement.style.display = "none";
                removeEmbedFormListner();
                return updateConnection({data: data.data, project_uid, connection_uid: auth_uid, provider});
            };
    
            window.Embed.on('form.submit',cbSuccess)
            var cbFailed = () => {
                $formElement.innerHTML = '';
                removeEmbedFormListner();
            };
            function removeEmbedFormListner() {
                window.Embed.off('form.submit', cbSuccess);
                window.Embed.off('form.cancel', cbFailed);
            }
            window.Embed.on('form.cancel', cbFailed);
        }
        }
    }
    
    // Verify connection update success or failure
        function updateConnection({data, connection_uid, provider, project_uid }) {
        window.Embed.updateConnection({data, project_uid, connection_uid, provider})
        .then((resp) => {
            if(resp) 
                showNotification('success', 'Connection updated successfully', 5);
            else 
                showNotification('error', 'Connection update failed', 5);
        }, (err) => {
            console.log("Connection update error - ", err);
            showNotification('error', 'Connection update failed', 5);
        }
    }

  37. getDeploymentTags() (sdk-version: 2.1.44)

    This function retrieves the tags associated with all deployments.

    Sample Code

    window.Embed.getDeploymentTags().then((res) => {
        let deploymentTagsElement = document.getElementById("deployment_tags");
        // id of <select> tag used to select deployment/ integration tags
        if(res && res.length) {
        res.map((x) => {
            let option = document.createElement("option");
            option.value = x.name;
            option.innerText = x.name;
            deploymentTagsElement.appendChild(option);
            })
        }
    })

  38. restartDeployment({uid}) (sdk-version: 2.1.49)

    This function restarts a deployment when it fails, time outs, or stops. To use this function, you must first enable restart for the particular deployment (from solution.setRestartDeployment())

    Parameter

    • uid: UID of the deployment to be restarted (can be obtained from getExecutions())

    Sample Code

    let deploymentUID = '123456abcd' // can be obtained from Embed.getExecutions()
    window.Embed.restartDeployment({uid:deploymentUID}).then(function(res){
        window.location.reload();
    } ,(err) =>{
        console.log(err);
    })

  39. bulkRestartDeployment({uids}) (sdk-version: 2.1.67)

    This function restarts multiple deployments when they fail, time out, or stop. To use this function, you must first enable restart for each deployment (can be obtained from solution.setRestartDeployment()).

    Parameter

    • uids: Array of UIDs for the deployments to be restarted (can be obtained from getExecutions())

    Sample Code

    let deploymentUIDs = ['123456abcd', ‘9876qwert’] // can be obtained from Embed.getExecutions() 
    window.Embed.bulkRestartDeployment({uids:deploymentUIDs}).then(function(res){ 
    window.location.reload(); 
    } ,(err) =>{ 
        console.log(err); 
    }) 

  40. resumeDeployment({flow_uid, uid}) (sdk-version: 2.1.67)

    This function resumes a deployment when it stops. To use this function, you must first enable solution.setRestartDeployment() function for the deployment.

    Parameter

    • flow_uid: Flow UID of the deployment to be resumed (can be obtained from getExecutions())

    • uid: UID of the deployment to be resumed (can be obtained from getExecutions())

    Sample Code

    let deploymentFlowUID = '98765qwert' // can be obtained from Embed.getExecutions() 
    let deploymentUID = '123456abcd' // can be obtained from Embed.getExecutions() \
    window.Embed.resumeDeployment({flow_uid:deploymentFlowUID, uid:deploymentUID}).then(function(res){ 
    window.location.reload(); 
    } ,(err) =>{ 
        console.log(err); 
    }) 

Common Events

webMethods.io Embed SDK raises various events to notify the clients about its states. Event listeners can be attached and removed by using the ‘on’ and ‘off’ methods.

Built-in event

  1. window.Embed.on(‘logout’, function () {})

    This event is fired when a user successfully logs out from webMethods.io Embed tenant.

    Sample code for performing external logout activity:

     window.Embed.on('logout',function(){
             logoutUser();
       })

  2. window.Embed.on(“authCreation”,function(res){})

    This event is fired when a user successfully creates a new authorization.

    Sample code for showing Auth or Connection creation message:

    window.Embed.on('authCreation', (data) => {
               var data = data.data;
               if(!data || data.error){
                   showNotification('error', `Error while creating ${data && (data.data || {}).isConnection ? 'connection' : 'auth'}`, 5);
               } else {
                   showNotification('success', `${data && data.isConnection ? 'Connection' : 'Auth'} created successfully`, 5);
               }
           })

  3. window.Embed.on(“INVALID_AUTHTOKEN”,function(res){})

    This event is fired when user session time outs. It fires a logout event internally.

  4. window.Embed.on(“gateway_timeout”, function(data) {})

    This event is fired when a third-party service encounters gateway timeout.

    Sample code for showing gateway timeout messages:

    window . Embed . on ( 'gateway_timeout' , function (){
     showGatewayTimeoutMessage ();
    })

  5. window.Embed.on(‘ready’,function(){})

    This event is fired when the Embed SDK is initialised and ready to fetch data.

    Sample code for rendering the input form once the SDK is ready:

     window.Embed.on('ready', renderForm)

    Sample code is for validating the logged in user session on the ‘ready’ event:

    window.Embed.on('ready', () => {
          window.Embed.validateToken().then((res) => {
        if(!res.loggedIn) {
            window.Embed.logout();
               }
    },(err) => {
        console.log('err',err);
        window.Embed.logout();
         })
    })

    Sample React code to render the React app on HTML document on the ‘ready’ event:

    function start() {
         ReactDOM.render(<Router />, document.getElementById("root"));
    }
    window.Embed.on("ready", start);

  6. solution.on(‘form.submit.success’, (data)=> {})

    This event is fired when a deployment is successfully created.

    Sample code for showing successful integration creation message:

    solution.on ( "form.submit.success" , function ( resp ) {
     showNotification ( 'success' , 'Integration created
    successfully.' , 2 ,() => {
     redirectTOMyIntegrations ();
     })
     })

  7. solution.on(‘form.submit.error’, (err, status)=> {})

    This event is fired when the deployment creation process encounters some error.

    Sample code for showing error message during integration creation process:

    solution.on("form.submit.error", function (resp) {
           try{
               resp = JSON.parse(resp.data);
               resp = resp instanceof Array ? resp[0] : resp;
               if(typeof resp !== "string"){
                   resp.data = resp.message;
               }
           }catch(e) {
    
           }
           showNotification('error', typeof resp.data == "string" ? resp.data : 'Invalid data', 5);
       })

  8. solution.on(‘change’, function(){})

    This event is fired when any value is changed inside the deployment create/edit form.

    Sample code for changing data for any particular key:

       function changeFunction(data){
                 console.log('Field - ', data.data);
            }
           window.Embed.on('change', changeFunction);

  9. solution.on(‘form.ready’, function(){})

    This event is fired when the form is ready to render.

    Sample code for listening form ready event:

    function readyFunction(data){
     console.log(' Form
    is ready ');
     }
     solution.on(' form.ready ', readyFunction);

  10. solution.on(‘form.cancel’, function(){})

    This event is fired when any value is changed inside the deployment create/edit form.

    Sample code for listening form cancel click event:

    function cancelClicked(data){
                 console.log('Form cancel clicked’);
            }
          solution.on(‘form.cancel’, cancelClicked);

  11. Custom events

    You can add a custom event listener to the Embed object so that you can listen for it and perform certain actions when it gets fired.

    Add Custom events using the following functionality. Event listeners can be attached and removed by using ‘on’ and ‘off’ methods.

    1. on(eventName, Function)

      This events creates an entry for a new event and listen for it. Pass eventName as a string in the first parameter and function as a second parameter to execute the function you need to use to fire an event.

      Sample Code

      var functionCall = (data) => {console.log(data)}  // This function is executed by the Embed SDK once specific event is fired
      Embed.on(“eventName”, functionCall); // This line creates event listener in the Embed object. Entry is available to view in Embed._listeners key.

    2. fire(eventName, data)

      This event executes the event you are listening to. Pass eventName as a string in the first parameter and data that needs to be used for executing the function passed while creating the event.

      Sample Code

      var obj = { “a”: “b”, …. };
      Embed.fire(“eventName”, obj)

    3. off(eventName, Function)

      This event removes the entry for an event and stops listening to that event. Pass eventName as a string in the first parameter and name of the function in the second parameter.

      Sample Code

      Embed.off(“eventName”, functionCall) // Pass reference of the function as a second parameter

Templates

Apart from the generic functions and events listed above, webMethods.io Embed SDK also provides some specific functions and events for integrating workflow templates to your websites.

There are two approaches to integrate workflow templates to your website:

  1. Using built-in templates
  2. Creating custom templates

Using built-in templates

Given below is the list of functions and events used by webMethods.io SDK, to integrate built-in templates provided by webMethods.io Embed, to your website:

Functions

  1. solution.renderForm(String DOM_Selector, function callback) - requires login

    This function renders the import form as specified in the object schema. It attaches the form to the specified dom selector. All events are restricted to the dom selector itself and none are attached to the global space. This function is included in the solution instance.

  2. solution.setDeploymentDescription(string Description) (sdk-version: 2.1.44)

    This function sets description for the deployment of a specific solution. If description is not set for a deployment, the description of the associated solution is applied to that deployment by default.

    Sample code

    var deploymentDescription = “Sample Deployment Description”;
    solution.setDeploymentDescription(deploymentDescription || ‘’’’);

  3. solution.getDeploymentDescription() (sdk-version: 2.1.44)

    This function retrieves the description for the deployment of a specific solution.

    Sample code

    var deploymentDescription = solution.getDeploymentDescription();
    console.log(“Solution Deployment Description:”, deploymentDescription);

  4. solution.setDeploymentTags(arrayOfString Tags) (sdk-version: 2.1.44)

    This function sets deployment tags for a specific solution.

    Sample code

    var deploymentTagsArray = [‘tag1’’,”tag2”,”tag3”];
    solution.setDeploymentTags(deploymentTagsArray || []);

  5. solution.getDeploymentTags() (sdk-version: 2.1.44)

    This function retrieves the deployment tags of a specific solution.

    Sample code

    var deploymentTags = solution.getDeploymentTags(); </li>

Events

  1. form.submit.success

    This event is fired when the integration form is submitted successfully by the user. Listener is on the Solution object.

  2. form.submit.error

    This event is fired when the integration form submission throws an error. Listener is on the Solution object.

  3. validate

    This event is fired when an existing authorization or connection is tested by the user. Listener is on an Embed object.

  4. change

    This event is fired after the setValue function is called which notifies any input value in the integration form. Listener is on the Solution object.

  5. form.ready

    This event is fired after the form builder is ready to render a form. Listener is on the Solution object.

  6. form.cancel

    This event is fired after the cancel button is clicked. Listener is on the Solution object.

  7. authCreation

    This event is fired after creating an authorization or connection. Listener is on an Embed object.

  8. errorFields

    This event is fired if any field value is missing while creating deployment. Listener is on an Embed object.

Creating custom form renderer

Admins can create custom integration templates and publish them on to their website/applications. Given below is the list of functions and events used by webMethods.io SDK, to create custom solutions:

Functions

  1. new Embed.Solution(solution_id)

    Instantiates the template object of the specified template.

    It returns the template object associated with the specified ‘template_uid’, which is required to create a new integration form. The returned object contains the details of the operations the template is required to perform, for example, fetching lookup, creating OAuth, creating deployment etc.

    Sample Code:

    var solution = new window.Embed.Solution(solution_uid)
    solution.on(‘ready’, () => {
    renderForm(solution);
    })

    Above solution object has a _schema key which is json schema of the form. There are following type of field which you need to handle in your custom form renderer:

    • String
    • Number
    • Array
    • Object
    • Boolean

    Sample Code:

    renderField( $div, obj ) { //$div is DOM element and obj is individual field
        switch(obj.type) {
        case "string":
            if(obj.enum) {
                $div = new SelectBox({ element: $div, schema: obj, builderRef: this })
                break; 
            }
            if((obj.hasOwnProperty('auth')  || obj.hasOwnProperty('oauth'))) {
                obj.auth = obj.auth || obj.oauth;
                $div = new AuthBox({ element: $div, schema: obj, builderRef: this })
                break;
            }
            if(obj.hasOwnProperty("connection")) {
                $div = new ConnectionBox({element : $div, schema: obj, builderRef : this});
                break;
            }
            if(obj.hasOwnProperty("lookup")){
                $div = new LookupBox({ element: $div, schema: obj, builderRef: this })
                break;
            }
            if(obj.hasOwnProperty("cloudstream_lookup")){
                $div = new CloudStreamLookupBox({element : $div, schema : obj, builderRef : this})
                break;
            }
            $div = new TextBox({ element: $div, schema: obj, builderRef: this })
            break;
        case "boolean":
            obj.hasOwnProperty('default') ?  obj.enum =  [obj.default] : null;  //[true, false];
            obj.options = {
                enumTitles : obj.enum[0] === true ? ["True"] : ["False"]
            }
            $div = new SelectBox({ element: $div, schema : obj, builderRef: this});
            break;
        case "array":
            if(obj.format === "checkbox"){
                $div = new CheckBox({element: $div, schema : obj, builderRef: this});
            }else{
                $div = new ArrayBox({ element: $div, schema: obj, builderRef: this })
            }
            break;
        case "object":
            $div = this.renderObject($div, obj, obj.keyName + "");
            break;
        case "number":
            if(obj.enum) {
                $div = new SelectBox({ element: $div, schema: obj, builderRef: this })
                break; 
            }
            $div = new TextBox({ element: $div, schema: obj, builderRef: this, typeOfField : obj.type })
            break;
        default:
            console.log("x.type is not proper")
    }
    }
    
    renderObject($div, obj, parentKey) {
    for(let _o in obj.properties) {
        _o.keyName = parentKey+"."+_o;
        renderField($div, _o);
    }
    }
    
    ArrayBox(...) {//array field handler}
    SelectBox(...) {//select field handler}
    AuthBox(...){//auth field handler}
    ConnectionBox(...) {//connection field handler}
    LookupBox(...) {//lookup field handler}
    CloudStreamLookupBox(...) {//cloudstream lookup handler}
    TextBox(...) {//text field handler}
    CheckBox(...) {//checkbox field handler}

  2. solution.getFields()

    Returns an array of validation fields associated with the associated object.

    You can use this function to retrieve the properties and validations associated with different solution components.

    Sample Code:

    solution.getFields(); // This function returns array of object which consists of all fields in solution.

  3. solution.setValue(field_name,value)

    Sets a value for the specified field.

    Specify the field name along with the value you want to set for that field. The ‘field_name’ details can be fetched using the ‘.getFields’ function.

    Sample Code:

    solution.setValue(‘trigger.auth’, ‘auth1234556’’); //This function will set the value of the `trigger.auth` field.

  4. solution.getAuths(auth_object)

    Sets a value for the specified field.

    Returns an array of authorizations associated with the specified auth.

    You can use this function to retrieve the list of available authorizations associated with the specified field name. The ‘auth_object’ is fetched from the solution schema field.

    Sample Code:

    solution.getAuths(auth/connection object).then((resp) => {
    listUserAuths(resp)
    }, (err)=> {
    console.log(err)
    })

  5. embed.getConnectorSchema( provider)

    Returns the JSON schema of the specified field or provider.

    You can use this function to retrieve the complete JSON schema associated with the specified provider. The ‘provider’ can be fetched from the connector object or you can pass the object to solution.getAuthType function.

    Sample Code:

    solution.getConnectorSchema(‘pagerduty_provider’).then((resp) => {
    showConnectionForm(resp)
    }, (err)=> {
    console.log(err)
    })

  6. solution.getLookupData(lookup_object, page,searchObj)

    Returns the list of lookup fields associated with the specified field name.

    Use this function to retrieve the list of lookup values associated with the specified field in a trigger or action. The ‘lookup_object’ is fetched from the solution schema field. When using this function in a trigger, you need to provide the ‘trigger_id’ in the parent key. If you are using this function for an action, you can leave the parent key empty.

    Sample Code:

    var lookupObj = {...}; //Schema of lookup field
    var searchObj = {
    search: 'abc',
    searchid: 'abc'
    }; // SearchObj is optional
    var params = lookupObj.params; // You can modify the params as per your usecase.
    solution.getLookupData(lookupObj, params, searchObj).then((data) => { // must pass lookupObj reference as internally SDK is using the reference of the lookupObj
    //data has two keys: 1. results - list of options, 2. next_page - which contains information about next getLookupData call.
    listLookupField(data);
    },(err)=>{
    //check if any dependent field is not met its condition
    console.log(err);
    })

  7. solution.getICLookupData(lookup_object, searchString)

    Returns the list of lookup fields associated with the specified field name.

    Use this function to retrieve the list of lookup values associated with the specified field in a trigger or action. The ‘lookup_object’ is fetched from the solution schema field. When using this function in a trigger, you need to provide the ‘trigger_id’ in the parent key. If you are using this function for an action, you can leave the parent key empty.

    Sample Code:

    var lookupObj = {...}; //Schema of lookup field
    var searchObj = "abc" // searchObj is optional
    var params = lookupObj.params; // You can modify the params as per your usecase.
    solution.getICLookupData(lookupObj, params, searchObj).then((data) => { // must pass lookupObj reference as internally SDK is using the reference of the lookupObj
    //data has three keys: 1. results - list of options, 2. searchObj  3. params - next page information
    listICLookupField(data);
    },(err)=>{
    //check if any dependent field is not met its condition
    console.log(err);
    })

  8. embed.addAuth( {provider, label, scopeScreen, closeScopeScreen}, callback)

    Creates a new authorization for the specified provider.

    This function lets you create a new authorization for the specified provider. The ‘provider’ can be fetched from the connector object or you can pass the object to solution.getAuthType function. The ‘label’ is used to identify the created authorization and is fetched from the client side. The ‘scopeScreen’ is used to display the list of scopes and is handled by the client side. The ‘closeScopescreen’ is also handled by the client side. The ‘callback’ is fetched from the API response for auth creation request.

    Sample Code

    window.Embed.addAuth({
    provider,
    label,
    scopes: [],
    scopeModalFunction,
    closeScopeModalFunction
    });

    If Oauth Popup is enabled in Embed Tenant -> Settings -> Developer Tools -> OAuth popup, it opens a new tab in new browser window and performs auth process. If it is unchecked, then auth process takes place on the current browser tab.

    Once you complete the auth process, the authCreation event is fired.

  9. Embed.addConnection(data, provider)

    Creates a new connection for the specified provider.

    You can use this method to create a new connection and send the connection details for the specified provider. ‘data’ is handled by client side and the ‘provider’ can be fetched from the connector object or you can pass the object to solution.getAuthType function.

    Sample Code:

    var data = { data : value,  provider : "pagerduty", version : connection_schema.version || "v1"  };
    if(connection_schema.metadata ) {
    data.metadata = connection_schema.metadata;
    }
    window.Embed.addConnection(data).then((res) => {
    //Connection is created sucessfully.
    //Close connection modal
    }, (err) => {
    console.log(err);
    })

  10. solution.submitForm()

    Submits the integration form and creates a deployment in the background.

    Submit the integration form, which creates a deployment in the background and raises either ‘form.submit.success’ or ‘form.submit.error’ event.

    Sample Code:

    solution.submitForm()

  11. new Embed.solution()
    solution.init(deployment_id)

    Updates existing integration/deployment.

    You can update an integration using this function. For this you need to pass integration id in function parameter. You can extract the integration id from the response of the Embed.getMyIntegrations() or Embed.getMyDeployments()function.

    Sample Code:

    var solution = new window.Embed.Solution();
    solution.init(deployment_uid)
    solution.on(‘ready’, () => {
    renderForm();
    })

    Above solution object has a _schema key which is json schema of the form. Also use deployment_data key for saved value.

  12. solution.isDependencyFulfilled(lookup_obj)

    Validates the dependent lookup inputs and provides necessary data to fetch lookup data.

    Use this method to validate the input data for dependent lookup fields and subsequently send required parameters to send lookup request.

    Sample Code:

    var lookupObj = {...}; //Schema of lookup field
    var params = lookupObj.params; // You can modify the params as per your usecase.
    var {shouldFetch, depObj, errKey} = solution.isDependencyFulfilled(lookupObj, params);
    if(!shouldFetch) {
    console.log('Please select valid '+(errKey || (((lookupObj.lookup || {}).auth === "connection" ) ? 'connection' : 'authorization')));
    }

  13. solution.getAuthType(obj)

    Retrieves provider and type for auth and connection.

    Sample Code:

    solution.getAuthType(obj); // Output - {provider: ‘asana’, ‘type’: ‘auth’}

  14. solution.getName()

    Retrieves solution name.

    Sample Code:

    solution.getName(); // Output - Solution Name

  15. solution.testAuth(auth_uid)

    Tests the existing authorization associated with a specific solution. This fucntion calls validate event which can be captured using Embed listener;

    Sample Code:

    solution.testAuth(‘auth123’);
    window.Embed.on('validate', (data) => {
    let output = typeof data.data === "string" ? data.data :  typeof data.data === "object" ? data.data.result : null;
    if(!output){
        console.log('Invalid Response');
    }
    var result = "";
    if(output)
        result = output === "Auth validated successfully" || output.toLowerCase() === "connection validated successfully"   ? true : false;
    if(!result) {
        showNotification('error', (data.data || {}).key == 'connection' ? `Invalid connection` : `Invalid auth`, 5);
    } else {
        showNotification('success', titleCaseScript(output), 5);
    }
    })

  16. solution.upgradeForm()

    Allows consumers to upgrade their own deployment which belongs to a different solution.

  17. solution.generateJsonSchema() and solution.getSchema()

    Returns the JSON form Object using which you can make the custom form builder.

    Sample Code:

    solution.generateJsonSchema(); // output - solution schema

  18. solution.setMinLength(path, value)

    Allows you to make any particular field mandatory. - path(string): field path - value(Number): 0 for optional, 1 for mandatory

    Sample Code:

    solution.setMinLength(‘trigger.email_field’, 1); // output - Now trigger email_field is mandatory

  19. solution.getMinLength(path)

    Returns whether the field is mandatory or not.

    Sample Code:

    solution.getMinLength(‘trigger.email_field’); // output - 1 or 0

  20. solution.getValue(path:optional)

    Returns the form value.

    Sample Code:

    solution.getValue(‘trigger.email_field’); // output -abc@abc.com

  21. solution.getFieldSchema(path)

    Fetches the JSON schema of the field.

    Sample Code:

    solution.getFieldSchema(‘trigger.email_field’); // output -abc@abc.com

  22. solution.validate()

    Returns an array of validation errors associated with the template.

    It returns the details of the validations applied to the template.

    Sample Code:

    solution.validate(); // output - array of string which contains list of error fields

  23. solution.setRestartDeployment(boolean checked) (sdk-version: 2.1.49)

    Sets deployment restart as true/ false for the given solution.

    Sample Code:

    var restartDeploymentChecked = true;
    solution.setRestartDeployment(!!restartDeploymentChecked);

  24. solution.getRestartDeployment() (sdk-version: 2.1.49)

    Gets restart deployment value (boolean) for the given solution.

    Sample Code:

    var restartDeploymentChecked = solution.getRestartDeployment();
    console.log(“Solution Deployment Restart: ”, restartDeploymentChecked);

Events

webMethods.io Embed SDK raises various events to notify the clients about its states. Event listeners can be attached and removed by using ‘on’ and ‘off’ methods.

  1. form.submit.success

    This event is fired when the integration form is submitted successfully by the user. Listener is on the Solution object.

  2. form.submit.error

    This event is fired when the integration form submission throws an error. Listener is on the Solution object.

  3. validate

    This event is fired when an existing authorization or connection is tested by the user. Listener is on an Embed object.

  4. change

    This event is fired after the setValue function is called which notifies any input value in the integration form. Listener is on the Solution object.

  5. form.ready

    This event is fired after the form builder is ready to render a form. Listener is on the Solution object.

  6. form.cancel

    This event is fired after the cancel button is clicked. Listener is on the Solution object.

  7. authCreation

    This event is fired after creating an authorization or connection. Listener is on an Embed object.

  8. errorFields

    This event is fired if any field value is missing while creating deployment. Listener is on an Embed object.

  9. Add Custom events using below functionality:

    1. solution.on(eventName, Function)

      This creates an entry for a new event and listen for it. Pass eventName as a string in the first parameter and function as a second parameter to execute the function you need to use to fire the event.

      Sample Code:

      var functionCall = (data) => {console.log(data)}  // this is the function that is executed by SDK after specific event is fired.
      solution.on(“eventName”, functionCall); // This line creates an event listener in the Embed object. Entry is available to view in solution._listeners key.

    2. solution.fire(eventName, data)

      This executes the event you are listening to. Pass eventName as a string in the first parameter and data that need to be used for executing the function passed while creating the event.

      Sample Code:

      var obj = { “a”: “b”, …. };
      solution.fire(“eventName”, obj)

    3. solution.off(eventName, Function)

      This removes the entry for an event and not listen anymore for this particular event. Pass eventName as a string in the first parameter and the name of the function in the second parameter.

      Sample Code:

      Embed.off(“eventName”, functionCall) //pass reference of the function as a second parameter

Custom Solutions

Admins can create custom solutions and publish them on to their website/applications. Given below is the list of functions and events used by webMethods.io SDK to create custom solutions:

Functions

  1. new Embed.solution(solution_id)

    This function instantiates the solution object of the specified solution.

    It returns the solution object associated with the specified ‘solution_id’, which is required to create a new solution. The returned object contains the details of the operations the solution is required to perform, for example, fetching lookup, creating OAuth.

  2. solution.getFields()

    This function returns an array of fields associated with the solution object.

    You can use this function to retrieve the properties and validations associated with different solution components.

  3. solution.setValue(field_name,value)

    This function sets a value for the specified field.

    Specify the field name along with the value you want to set for that field. The ‘field_name’ details can be fetched using the ‘.getFields’ function.

  4. solution.getAuths(auth_object)

    This function returns an array of authorizations associated with the specified auth.

    You can use this function to retrieve the list of available authorizations associated with the specified field name. The ‘auth_object’ is fetched from the solution schema field.

  5. embed.getConnectorSchema(provider)

    This function returns the JSON schema of the specified field or provider

    You can use this function to retrieve the complete JSON schema associated with the specified provider. The ‘provider’ can be fetched from the connector object or you can pass object to solution.getAuthType function.

  6. solution.getLookupData(lookup_object, page, searchObj)

    This function returns the list of lookup fields associated with the specified field name.

    Use this function to retrieve the list of lookup values associated with the specified field in a trigger or action. The ‘lookup_object’ is fetched from the solution schema field.

    When using this function in a trigger, you need to provide the ‘trigger_id’ in the parent key. If you are using this function for an action, you can leave the parent key empty.

  7. solution.getICLookupData(lookup_object, searchString)

    This function returns the list of lookup fields associated with the specified field name.

    Use this function to retrieve the list of lookup values associated with the specified field in a trigger or action. The ‘lookup_object’ is fetched from the solution schema field. When using this function in a trigger, you need to provide the ‘trigger_id’ in the parent key. If you are using this function for an action, you can leave the parent key empty.

  8. embed.addAuth( {provider, label, scopeScreen, closeScopeScreen}, callback)

    This function creates a new authorization for the specified provider.

    It lets you create a new authorization for the specified provider. The ‘provider’ can be fetched from the connector object or you can pass the object to solution.getAuthType function. The ‘label’ is used to identify the created authorization and is fetched from the client side. The ‘scopeScreen’ is used to display the list of scopes and is handled by the client side. The ‘closeScopescreen’ is also handled by the client side. The ‘callback’ is fetched from the API response for auth creation request.

  9. Embed.addConnection(data, provider)

    This function creates a new connection for the specified provider.

    You can use this function to create a new connection and send the connection details for the specified provider. ‘data’ is handled by client side and the ‘provider’ can be fetched from the connector object or you can pass the object to solution.getAuthType function.

  10. solution.submitForm()

    This function submits the integration form and creates a solution in the background.

    You can use this function to submit the integration form, which creates a solution in the background and raises either ‘form.submit.success’ or ‘form.submit.error’ event.

  11. new Embed.solution()

    solution.init(deployment_id)

    This function updates existing integration.

    You can update an integration using this function. For this you need to pass integration id in function parameter. You can extract the integration id from the response of the Embed.getMyIntegrations() function.

  12. solution.isDependencyFulfilled(lookup_obj)

    This function validates the dependent lookup inputs and provides necessary data to fetch lookup data.

    Use this function to validate the input data for dependent lookup fields and subsequently send required parameters to send lookup request.

  13. solution.isICDependencyFulfilled(lookup_obj)

    This function validates the dependent lookup inputs and provides necessary data to fetch lookup data.

    Use this function to validate the input data for dependent lookup fields and subsequently send required parameters to send lookup request.

  14. solution.getAuthType(obj)

    This function retrieves provider and type for auth and connection.

  15. solution.getName()

    This function retrieves solution name.

  16. solution.testAuth(auth_uid)

    Tests the existing authorization associated with a specific solution.

  17. solution.upgradeForm()

    Allows consumers to upgrade their own deployment which belongs to a new solution.

  18. generateJsonSchema()

    Returns the JSON form Object using which you can make the custom form builder.

  19. setMinLength(path, value)

    Allows you to make any particular field mandatory.

    • path(string): field path
    • value(Number): 0 for optional, 1 for mandatory
  20. getMinLength(path)

    Returns whether the field is mandatory or not.

  21. getValue(path:optional)

    Returns the form value.

  22. getFieldSchema(path)

    Fetches the JSON schema of the field.

Events

webMethods.io Embed SDK raises various events to notify the clients about its states. Event listeners can be attached and removed by using the ‘on’ and ‘off’ methods.

  1. form.submit.success

    This event is fired when the integration form is submitted successfully by the user.

  2. form.submit.error

    This event is fired when the integration form submission is unsuccessful.

  3. solution.on(‘ready’, function(){})

    This event is fired when all the components related to the integration form are loaded and functions can be applied on the form.

Adding custom events

Yuu can add custom events using below functionality:

  1. on(eventName, Function)

    This creates an entry for a new event and listen for it. Pass eventName as a string in the first parameter and function as a second parameter to execute the function you need to use to fire the event.

  2. fire(eventName, data)

    This executes the event you are listening to. Pass eventName as a string in the first parameter and data that need to be used for executing the function passed while creating the event.

  3. off(eventName, Function)

    This removes the entry for an event and not listen anymore for this particular event. Pass eventName as a string in the first parameter and the name of the function in the second parameter.