How to send the JSON metadata to the 3rd party system

nikhitha24
Tera Guru

Hi Team,

 

Can someone please help me on the below requirement

 

I have written script include for the REST API to send the JSON metadata to the 3rd party system and for that i have written business rule when an record is created and update it needs to send the json to them.

 

The below script is not working can someone please help me on this.

 

Script Include:

In this script i need add one more condition like if dev it need to send there devinstance same like uat and prod

 
var IntegrationAPI = Class.create();
IntegrationAPI.prototype = {
    initialize: function() {
        this.log = gs;
        this.clientId = gs.getProperty("client.id");
        this.clientSecret = gs.getProperty("client.secret");
        this.tokenURL = gs.getProperty("token.url");
    },
    instance: function() {
        var abcdev = "https://abcdev.service-now.com/";
        var abcqa = "https://abcqa.service-now.com/";
        var abcuat = "https://abcuat.service-now.com/";
        var abc = "https:/abc.service-now.com/";

        switch (true) {
            case this.instanceURL.indexOf('dev') != -1:
                gs.log("Environment: Development", "IntegrationAPI");
                return abcdev;
            case this.instanceURL.indexOf('qa') != -1:
                gs.log("Environment: QA", "IntegrationAPI");
                return abcqa;
            case this.instanceURL.indexOf('uat') != -1:
                gs.log("Environment: UAT", "IntegrationAPI");
                return abcuat;
            default:
                gs.log("Environment: Production", "IntegrationAPI");
                return abc;
        }
    },

 
    fetchOAuthToken: function() {
        try {
            var restMessage = new sn_ws.RESTMessageV2();
            restMessage.setHttpMethod("POST");
            restMessage.setEndpoint(this.tokenURL);

            restMessage.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            var authHeader = "Basic " + GlideStringUtil.base64Encode(this.clientId + ":" + this.clientSecret);
            restMessage.setRequestHeader("Authorization", authHeader);

            var requestBody = {
                grant_type: "client_credentials",
                scope: "md_apim"
            };
            restMessage.setRequestBody(this.encodeFormData(requestBody));

            var response = restMessage.execute();
            var responseBody = response.getBody();
            var httpStatus = response.getStatusCode();

            if (httpStatus == 200) {
                var parsedResponse = JSON.parse(responseBody);
                return parsedResponse.access_token;
            } else {
                gs.error("Failed to fetch OAuth token. Status: " + httpStatus + " Response: " + responseBody, "IntegrationAPI");
                return null;
            }
        } catch (ex) {
            gs.error("Error fetching OAuth token: " + ex.message, "IntegrationAPI");
            return null;
        }
    },
 
    encodeFormData: function(data) {
        var formData = [];
        for (var key in data) {
            formData.push(encodeURIComponent(key) + "=" + encodeURIComponent(data[key]));
        }
        return formData.join("&");
    },

  
    sendabcMetadata: function(abcRecord) {
        if (JSUtil.nil(abcRecord)) {
            gs.error("Invalid abc record.", "IntegrationAPI");
            return;
        }

        var baseURL = this.endPoint();
        var endpoint = gs.getProperty("api.endpoint.path", baseURL + "api/default_endpoint"); /
        var contentType = "application/json";

        var abcGr = new GlideRecord("abc table"); // Query the table
        abcGr.addQuery("abc", abc.getValue("number")); /
        abcGr.query();

        while (abcGr.next()) {
            var payload = {
                 Number: abcGr.getValue("number"),
               CloseDate: abcGr.getValue("close_date")
               
            };

            this.RESTMessage("POST", endpoint, contentType, payload, "sendabcMetadata");
        }
    },

    // RESTMessage function
    RESTMessage: function(method, endpoint, contentType, body, methodName) {
        try {
            var restMessage = new sn_ws.RESTMessageV2();
            restMessage.setHttpMethod(method);
            restMessage.setEndpoint(endpoint);

            var authToken = this.fetchOAuthToken();
            if (!authToken) {
                gs.error("Cannot proceed without a valid OAuth token.", "IntegrationAPI");
                return;
            }
            restMessage.setRequestHeader("Authorization", "Bearer " + authToken);
            restMessage.setRequestHeader("Content-Type", contentType);

            if (!JSUtil.nil(body)) {
                restMessage.setRequestBody(JSON.stringify(body));
            }

            var response = restMessage.execute();
            var responseBody = response.getBody();
            var httpStatus = response.getStatusCode();

            if (httpStatus >= 200 && httpStatus < 300) {
                gs.info("REST Message successful. Status: " + httpStatus + " Response: " + responseBody, "IntegrationAPI");
            } else {
                gs.error("REST Message failed. Status: " + httpStatus + " Response: " + responseBody, "IntegrationAPI");
            }
        } catch (ex) {
            gs.error("Error in RESTMessage - " + methodName + ": " + ex.message, "IntegrationAPI");
        }
    },

    type: 'IntegrationAPI'
};

 

 

Business rule :

(function executeRule(current, previous /*null when async*/) {
    try {
        // Initialize the script include
        var Integration = new IntegrationAPI();

        // Pass the current record to the sendabcMetadata function
        Integration.sendabcMetadata(current);
    } catch (ex) {
        gs.error("Error in Business Rule 'Integration': " + ex.message);
    }
})(current, previous);

 

As i have written this need help on this.

 

Thank you.

1 REPLY 1

Abbas_5
Tera Sage
Tera Sage

Hello @nikhitha24,

Please refer to the link below:
https://www.servicenow.com/community/developer-forum/how-to-send-data-to-third-party-application-fro...

 

If it is helpful. please mark it as helpful and accept the correct solution. In future by refer to this solution it will helpful to someone.

Thanks & Regards,

Abbas Shaik