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 = {
        email : , //
        domain : , // Settings -> Developer Tools -> Domain
        plan : “,
        account : “,
        }
        var jwt = jsonwebtoken.sign(user, API_KEY);

      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 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('email', 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.

  2. login(String jwt_signed_token)

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

    Code snippet for JWT token generation:

    const token = "YOUR_API_KEY"// Retrieve the identifier by navigating to Settings > Developer Tools > API KEY in the Embed Admin Portal
    const user_obj = 
              {
                email : "email id of the user",
                domain: "domain from where the request is originating", // Settings > Developer Tools > Domain
                plan: "plan code", // If you want to assign a particular plan to the user
                account: "account_id" // If you want add user under a particular account
              }
      const signed = jwt_signing(user_obj,token); 
    
    //Please use hmac256 encryption algorithm 

    Note: plan code and account_id can be found under the Plans and Accounts tabs, respectively, in the Embed Admin portal.

  3. isActive(Object flow | String flow_uid) - requires login

    This function returns whether the specified workflow is active or not.

  4. setActive(Object flow | String flow_uid, Boolean status) - requires login

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

  5. deleteDeployment(Object flow| String flow_uid) - requires login

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

  6. getMyIntegrations() - requires login

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

  7. getConnectors()

    This function retrieves a list of connectors/services from the set of available integration templates.

  8. getTemplatesByConnector()

    This function retrieves a list of all integration templates associated with the specified connector/service.

  9. getTemplates([String field_name1, String field_name2])
    Retrieves a list of all integration templates/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.
  10. getDeploymentIcons(Object flow, String|Number size)

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

  11. getIcon(Object obj, String|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. 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.

  13. getAuths(provider, searchPattern) - requires login

    This function fetches all auths associated with the currently logged-in user for the specified provider.

  14. validateToken()

    This function checks whether the user is logged in or not.

  15. 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 will return the execution statistics for all deployments. Optionally, ‘params’ can be used to enable pagination functionality with the ‘skip’ and ‘limit’ properties.

  16. getConsumerUsage()

    This function retrieves the total number of executions.

  17. getConsumerUsageByDate(startDate, endDate(optional))

    This function retrieves the total number of executions for a specific date or time frame.

  18. getExecutions(Object params)

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

  19. getExecutionLogs(String log_uid)

    This function retrieves the execution logs.

  20. createProject()

    Note: If you are using the Embed SDK version 2.1.21 or above, you need not use this function. The Embed SDK will automatically execute 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);
    })
    }

  21. getSolutionsByBotId()

    This function retrieves all solutions added inside a bot.

  22. getBotTokenByBotId

    This function retrieves bot information.

  23. getConsumer

    This function retrieves consumer information.

  24. getSolution(solution_id)

    This function retrieves solution object.

  25. getTenant(provider)

    This function checks whether OAuth is present or not with the specified provider. If OAuth is not present for the specifiedprovider, then the function will return {tid: “builtio”} otherwise it will return metadata of the OAuth.

  26. 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.

  27. createUserTenantOauth(oauth_obj)

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

  28. 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.

  29. 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.

  30. getAuthtoken()

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

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. logout

    This event is fired when the SDK logouts the user successfully.

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.

  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.

  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.

  4. 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();
       })

  5. 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);
               }
           })

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

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

  7. 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 ();
    })

  8. 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);

  9. 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 ();
     })
     })

  10. 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);
       })

  11. 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);

  12. 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);

  13. 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);

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 will attach 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.

Events

  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 throws an error.

  3. validate

    This event is fired when an existing authorization or connection is tested by the user.

  4. change

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

  5. form

    This event is fired after the form builder is ready.

  6. authCreation

    This event is fired after creating an authorization or connection.

  7. errorFields

    This event is fired if any field value is missing while creating deployment.

Creating custom templates

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 templates:

Functions

  1. new Embed.Solution(template_uid)

    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, etc.

  2. solution.validate()

    Returns an array of validation errors associated with the template.

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

  3. solution.getSchema()

    Returns the complete JSON schema for the template object.

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

  4. solution.setValue(field_path,value)

    Sets a value for the specified field.

    Specify the path of the field along with the value you want to set for it. The ‘field_path’ details can be acquired using the ‘.getSchema’ function, and the nested fields can be specified using the ‘.(dot)’ notation.

    For example, .setValue(trigger.field_name,value) OR .setValue(action_id.field_name.field_name,value)

  5. Embed.addAuth( auth_object, callback)

    Creates a new authorization (OAuth) in your integration form.

    Create a new authorization for the specified trigger or action. The auth_object is fetched from the solution schema field.

  6. solution.submitForm()

    Submits the integration form, creating an integration in the background and raises either ‘form.submit.success’ or ‘form.submit.error’ event.

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.

  2. form.submit.error

    This event is fired when the integration form submission throws an error.

  3. .on(‘ready’)

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

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 will create a solution in the background and will raise 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 will belong 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 will create 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 will execute 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 will remove 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.