Request Template platform 2.3

This was how the app was making a request on platform 2.2

            function getFreshchatChannels() {
                let freshchatUri = FRESHCHAT_URL + "/v2/channels?items_per_page=100";
                console.info('freshchatUri: ', freshchatUri);
                let header = {
                    "Authorization": "Bearer " + TOKEN,
                    "Accept": "application/json",
                    "Content-Type": "application/json"
                };
                let options = {
                    headers: header,
                    maxAttempts: 5,
                };
                client.request.get(freshchatUri, options)
                    .then(function(data) {
                    console.info('Channels data: ', data);
                    if(data.status === 200) {
                        const response = JSON.parse(data.response);
                        console.info('Channels response: ', response);
                        const channels = response.channels;
                        console.info('Channels: ', channels);

                        if(Array.isArray(channels)) {
                            channels.forEach(function(channel) {
                                if(channel.id && channel.name) {
                                    channelId2NameMap.set(channel.id, channel.name);
                                }
                            })
                        }
                        console.info('channelId2NameMap: ', channelId2NameMap);
                        
                        getFreshchatGroups();
                    } else {
                        freshChat.showNotify('error', 'Unable to retrieve channels information from Freshchat.');
                        return null;
                    }
                }, function (error) {
                    console.error('Error received Freshchat channels data: ', error);
                })
            }

Making requests on platform 2.3 using a request template.

 function getFreshchatChannels() {
                let freshchatUri = FRESHCHAT_URL + "/v2/channels?items_per_page=100";
                console.info('freshchatUri: ', freshchatUri);

                // Updated Request: invoking Template
                client.request.invokeTemplate("getFreshchatChannels", {
                    context: {
                        path: FRESHCHAT_URL,
                        TOKEN: TOKEN
                    },
                })

                .then(function(data) {
                    console.info('Channels data: ', data);
                    if(data.status === 200) {
                        const response = JSON.parse(data.response);
                        console.info('Channels response: ', response);
                        const channels = response.channels;
                        console.info('Channels: ', channels);

                        if(Array.isArray(channels)) {
                            channels.forEach(function(channel) {
                                if(channel.id && channel.name) {
                                    channelId2NameMap.set(channel.id, channel.name);
                                }
                            })
                        }
                        console.info('channelId2NameMap: ', channelId2NameMap);
                        
                        getFreshchatGroups();
                    } else {
                        freshChat.showNotify('error', 'Unable to retrieve channels information from Freshchat.');
                        return null;
                    }
                }, function (error) {
                    console.error('Error received Freshchat channels data: ', error);
                })
            }

request.json

    "getFreshchatChannels": {
        "schema": {
            "method": "GET",
            "protocol": "https",
            "host": "<%=iparam.subdomain %>.freshchat.com",
            "path": "<%= context.path %>",
            "headers": {
                "Authorization": "Bearer <%= context.TOKEN %>",
                "Accept": "application/json",
                "Content-Type": "application/json"
            }
        },
        "options": {
            "maxAttempts": 5
        }
    },

manifest.json

      "requests": {
        "getRelatedCase": {},
        "getFreshchatChannels": {},
        "getFreshchatGroups": {},
        "Freshchat": {},
        "FreshchatPost": {},
        "InstanceURL": {},
        "getCaseforChangeOwner": {},
        "getCaseRecordType": {},
        "findSalesforceCase": {},
        "getLiveChatButtonId": {},
        "getLiveChatDeployment": {},
        "createLiveChatVisitor": {},
        "getUser": {},
        "getInstanceUrl": {}
     }```

Getting Error:
![Error|690x394](upload://mYDwAQTJFwChobpcLoIdsKIQNau.png)
app.js:1902 Error received Freshchat channels data:  
{headers: {…}, errorSource: 'APP', response: 'Request template not found', status: 404}
errorSource
: 
"APP"
headers
: 
[[Prototype]]
: 
Object
response
: 
"Request template not found"
status
: 
404

Can you share the complete manifest.json that you have used? Are you getting the template not found error only for this template or for any other ones as well?

Thanks for reaching out Kaustav, I have provided my manifest.json file also I am getting this for all the templates/Requests.

Also after that which I feel is because of request template not found error I am getting this Error which might help more.

Hey @thimayarohit,

From the requests.json,

"host": "<%=iparam.subdomain %>.freshchat.com",
"path": "<%= context.path %>",

And app code,

The error is from host and path substitutions,

  • As the host is a value from iparams subdomain can you confirm if the value is set in iparams?
  • The path value contains the domain host https://<domain>.freshchat.com, what I understand from your code (platform 2.2) is that path would have to be /v2/channels?items_per_page=100 which is passed from context.
client.request.invokeTemplate("getFreshchatChannels", {
     context: {
            path: "/v2/channels?items_per_page=100",
            TOKEN: TOKEN
     },
})

Let me know if this helps!

Thanks for reaching out Jones as mentioned I have updated the code to your suggestions:

requests.json

    "getFreshchatChannels": {
        "schema": {
            "method": "GET",
            "protocol": "https",
            "host": "bclcsandbox.freshchat.com",
            "path": "<%= context.path %>",
            "headers": {
                "Authorization": "Bearer <%= context.TOKEN %>",
                "Accept": "application/json",
                "Content-Type": "application/json"
            }
        },
        "options": {
            "maxAttempts": 5
        }
    }
app.js
                client.request.invokeTemplate("getFreshchatChannels", {
                    context: {
                        path: "/v2/channels?items_per_page=100",
                        TOKEN: TOKEN,
                    },
                })

Still getting the same Errors please let me know if something is wrong here!

Hey @thimayarohit,

Can we ensure the previous version of the addon is removed?

To ensure that any previous versions of the addon are removed from the system, you can execute the command rm -rf ~/.fdk to delete the .fdk directory. Afterward, you can try running the application again using the command fdk run.

If the issue persists or if you encounter any further problems, please let me know, and I’ll be glad to assist you further.

Hey, Logesh Narayanan thanks for pointing it out your solutions seem to be working!

@Logesh_Narayanan
When I am passing the host manually its working fine!

    "getFreshchatChannels": {
        "schema": {
            "method": "GET",
            "protocol": "https",
            "host": "bclcsandbox.freshchat.com",
            "path": "/v2/channels?items_per_page=10",
            "headers": {
                "Authorization": "Bearer <%= context.TOKEN %>",
                "Accept": "application/json",
                "Content-Type": "application/json"
            }
        },
        "options": {
            "maxAttempts": 5
        }
    },

But as soon as I pass it via context variable:

client.request.invokeTemplate("getFreshchatChannels", {
                    context: {
                        path: "/v2/channels?items_per_page=100",
                        TOKEN: TOKEN,
                        // FRESHCHAT_HOST = "bclcsandbox"
                        FRESHCHAT_HOST: FRESHCHAT_HOST
                    },
                })

 "getFreshchatChannels": {
        "schema": {
            "method": "GET",
            "protocol": "https",
            "host": "<%= context.FRESHCHAT_HOST %>.freshchat.com",
            "path": "/v2/channels?items_per_page=10",
            "headers": {
                "Authorization": "Bearer <%= context.TOKEN %>",
                "Accept": "application/json",
                "Content-Type": "application/json"
            }
        },
        "options": {
            "maxAttempts": 5
        }
    },

I am getting this error:
{status: 400, headers: {…}, response: ‘error while substituting templates.’, errors: {…}, errorSource: ‘APP’, …}

Thanks in advance!

@thimayarohit

In the templating host, the usage of context is not supported. Instead, you can utilize the template via iparams by modifying the “host” value as follows:

"host": "<%=iparam.subdomain %>.freshchat.com"

When I looked the code base we had iparams.html already setup so I just added another one to get freshchat domain which is bclc and bclcsandbox.


<script type="text/javascript">
  function getConfigs(configs) {
    if (configs["settings"]) {
      if (configs["settings"]["orgType"] === "test") {
        $("#t1").attr("checked", false);
        $("#t2").attr("checked", true);
      } else {
        $("#t2").attr("checked", false);
        $("#t1").attr("checked", true);
      }

      if (configs["settings"]["domainType"] === "bclcsandbox") {
        $("#d1").attr("checked", false);
        $("#d2").attr("checked", true);
      } else {
        $("#d2").attr("checked", false);
        $("#d1").attr("checked", true);
      }

      $("input[type=radio][name=domain_type]:checked").prop(
        "checked",
        configs["settings"]["domainType"]
      );

      $("input[type=radio][name=org_type]:checked").prop(
        "checked",
        configs["settings"]["orgType"]
      );
    }
  }

  function validate() {
    return true;
  }

  function postConfigs() {
    var settings = {
      orgType: $("input[type=radio][name=org_type]:checked").val(),
      domainType: $("input[type=radio][name=domain_type]:checked").val()
    };
    return { settings: settings,  };
  }
</script>

<body>
  <div class="form">
    <div class="intelli-details">
      <h3>INTEGRATION SETTINGS</h3>
      <div id="app-settings">
        <div class="row clearfix">
          <div style="float: left; width: 25%">
            Select the type of Salesforce organization
          </div>
          <div style="float: left; width: 75%">
            <label id="org_type_for_authorize">
              <input id="t1" name="org_type" type="radio" checked value="login" /><label for="t1">Production</label>
              <br /><br />
              <input id="t2" name="org_type" type="radio" value="test" /><label for="t2">Sandbox</label>
            </label>
          </div>
        </div>

        <div class="row clearfix">
          <div style="float: left; width: 25%">
            Select the type of freshchat domain 
          </div>
          <div style="float: left; width: 75%">
            <label id="domain_type_for_authorize">
              <input id="d1" name="domain_type" type="radio" checked value="bclc" /><label for="d1">Production</label>
              <br /><br />
              <input id="d2" name="domain_type" type="radio" value="bclcsandbox" /><label for="d2">Sandbox</label>
            </label>
          </div>
        </div>

      </div>
    </div>
  </div>
  </div>

Inorder to use that in request.json I did

"getFreshchatChannels": {
        "schema": {
            "method": "GET",
            "protocol": "https",
            "host": "<%=iparam.domainType %>.freshchat.com",
            "path": "/v2/channels?items_per_page=100",
            "headers": {
                "Authorization": "Bearer <%= context.TOKEN %>",
                "Accept": "application/json",
                "Content-Type": "application/json"
            }
        },
        "options": {
            "maxAttempts": 5
        }
    },

This was my implementation but I am now when in my local server testing it with fdk run getting error on getting freshchat channels saying this:

{status: 502, headers: {…}, response: ‘Error in establishing connection’, errorSource: ‘APP’, attempts: 1}

even if I manually type bclcsandbox.freshchat.com into the host I am getting this Error so I was just wondering why it is as then only I could test if my <%=iparam.domainType %> is working or not.

Thanks…

To verify the functionality, you can retrieve the iparams by referring to the documentation provided at https://developers.freshdesk.com/v2/docs/installation-parameters/#retrieve

Salesforce Query Failing…

            function getAgentInfo() {
                $("#case_loader").show()
                $("#info_from_sf").hide()
                client.data.get("loggedInAgent")
                    .then(
                        function (data) {
                            // Agent
                            console.info('Agent data: ', data);
                            const freshChatAgent = new SFDC.FreshChatAgent(data.loggedInAgent.first_name,
                                data.loggedInAgent.last_name,
                                data.loggedInAgent.first_name + ' ' + data.loggedInAgent.last_name,
                                data.loggedInAgent.email,
                                data.loggedInAgent.phone);
                            console.info('Agent: ', freshChatAgent);

                            // Save to variable
                            selfApp.freshchatAgent = freshChatAgent;

                            // Get User from Salesforce
                            let query = "SELECT+Id,+Email,+Name+" + "FROM+User+" +
                                "WHERE+Email+=+'" + encodeURI(freshChatAgent.email) + "'+LIMIT+1";

                            

                            let url = freshChat.SALESFORCE_URL + '/services/data/v46.0/query/?q=' + query;
                            console.info('URL: ', url);
                            if (orgType == "test") {
                                
                                return client.request.invokeTemplate("getAgentInfo", {
                                    context: {
                                        path: '/services/data/v46.0/query?q=',
                                        query: query
                                    },
                                })
                            } else if(orgType == "login") {
                                return client.request.invokeTemplate("getAgentInfoProd", {
                                    context: {
                                         path: '/services/data/v46.0/query?q=',
                                        query: query
                                    },
                                })
                            } else {
                                return "Can't Get Agent Info"
                            }
                            // console.log(freshChat.SALESFORCE_URL)

                            // Return Salesforce User
                            // return client.request.get(url, options);
                        },
                        function (error) {
                            throw new Error(JSON.stringify(error));
                        }
                    )
                    .then(data => {
                        const response = JSON.parse(data.response);
                        console.info('Salesforce User: ', response);
                        if (response.totalSize === 0) {
                            console.warn('No User matches in Salesforce.');
                            // Store Salesforce User as NULL
                            selfApp.salesforceUser = null;
                            // Display attention
                            selfApp.windowHeight += 32;
                            client.instance.resize({ height: selfApp.windowHeight });
                            $("#user_info").append($("<p></p>").text('No User matches in Salesforce.'));
                            checkWindowHeight();
                            // Get Contact
                            getContactInfo();
                            // Get a conversation Id
                            getConversationId();
                        } else {
                            console.info('User is matched in Salesforce');
                            // Store User in global variable
                            selfApp.salesforceUser = response.records[0];
                            checkWindowHeight();
                            // Get Contact
                            getContactInfo();
                            // Get a conversation Id
                            getConversationId();
                        }
                    })
                    .catch(error => {
                        $("#case_loader").hide();
                        $("#info_from_sf").show();
                        console.error('Connection error. Get Salesforce User is failed.');
                        throw new Error(JSON.stringify(error));
                    })
            }
    "getAgentInfo": {
        "schema": {
            "method": "GET",
            "protocol": "https",
            "host": "bclc--stgqa.sandbox.my.salesforce.com",
            "path": "<%= context.path %>",
            "headers": {
                "Authorization": "OAuth <%= access_token %>"
            },
            "query": {
                "query": "\"<%= context.query %>\""
            }
        },
        "options": {
            "maxAttempts": 5,
            "isOAuth": true
        }
    },

Hey @Logesh_Narayanan Can you please have a look on this I converted this request into request template but getting an error with query.

I have also passed the query into the path itself where the error is little different that is


still failed please let me know if there is any correct way of doing it.

also tried passing query as “query”: “<%= context.query %>” still no result.

Thanks.

This topic was automatically closed 6 days after the last reply. New replies are no longer allowed.