Create a ServiceNow Webhook

Copy this pre-configured script and paste it into your ServiceNow Business Rule.

  1. In ServiceNow, navigate to System Definition → Business Rules.
  2. Click New to create a new Business Rule.
  3. Configure the Business Rule settings (see documentation for details).
  4. Paste this script into the Script field on the Advanced tab:
    // ==================================================
    // Risotto Webhook Integration for ServiceNow
    // ==================================================
    // This Business Rule sends data to Risotto when a
    // record is created or updated in the incident table.
    // ==================================================
    
    function getJournalEntriesWithAuthors(recordSysId, elementType) {
        var entries = [];
        var gr = new GlideRecord('sys_journal_field');
        gr.addQuery('element_id', recordSysId);
        gr.addQuery('element', elementType);
        gr.orderBy('sys_created_on');
        gr.query();
    
        while (gr.next()) {
            var entrySysId = gr.getValue('sys_id');
            var entryText = gr.getValue('value');
            var entryCreatedOn = gr.getValue('sys_created_on');
            var authorUserName = gr.getValue('sys_created_by');
    
            // Query sys_user table to get author details
            var authorName = authorUserName;
            var authorEmail = null;
    
            try {
                var userGR = new GlideRecord('sys_user');
                userGR.addQuery('user_name', authorUserName);
                userGR.query();
    
                if (userGR.next()) {
                    if (userGR.getValue('name')) {
                        authorName = userGR.getValue('name');
                    }
                    if (userGR.getValue('email')) {
                        authorEmail = userGR.getValue('email');
                    }
                }
            } catch (e) {
                gs.error('[Risotto] Error querying sys_user table: ' + e.message);
            }
    
            var entry = {
                sys_id: entrySysId,
                type: elementType,
                text: entryText,
                created_on: entryCreatedOn,
                author: {
                    name: authorName,
                    email: authorEmail,
                    user_name: authorUserName
                }
            };
            entries.push(entry);
        }
    
        return entries;
    }
    
    (function executeRule(current, previous) {
        try {
            // Initialize REST Message
            var r = new sn_ws.RESTMessageV2();
    
            // ==================================================
            // CONFIGURATION (Pre-configured for your organization)
            // ==================================================
    
            var WEBHOOK_URL = 'https://api.tryrisotto.com/org/org_northwind/events/servicenow';
            var WEBHOOK_SECRET = '3f6c1d8e-27b4-4a9e-b0f5-9c2e7a41d6b3';
    
            // ==================================================
            // END CONFIGURATION
            // ==================================================
    
            r.setEndpoint(WEBHOOK_URL);
            r.setHttpMethod('POST');
            r.setRequestHeader('X-Webhook-Secret', WEBHOOK_SECRET);
            r.setRequestHeader('Content-Type', 'application/json');
    
            // Build payload with record data
            var sys_id = current.getValue('sys_id');
            var recordData = {
                sys_id: sys_id,
                number: current.getValue('number'),
                short_description: current.getValue('short_description'),
                description: current.getValue('description'),
                state: current.getValue('state'),
                priority: current.getValue('priority'),
                impact: current.getValue('impact'),
                urgency: current.getValue('urgency')
            };
    
            // Include caller information if available
            if (current.caller_id) {
                recordData.caller_id = {
                    email: current.caller_id.email ? current.caller_id.email.toString() : null,
                    name: current.caller_id.name ? current.caller_id.name.toString() : null
                };
            } else {
                recordData.caller_id = null;
            }
    
            // Include comments and work notes combined and sorted chronologically
            var comments = getJournalEntriesWithAuthors(sys_id, 'comments');
            var workNotes = getJournalEntriesWithAuthors(sys_id, 'work_notes');
    
            var allEntries = comments.concat(workNotes);
            allEntries.sort(function(a, b) {
                if (a.created_on < b.created_on) return -1;
                if (a.created_on > b.created_on) return 1;
                return 0;
            });
    
            recordData.journal_entries = allEntries.length > 0 ? allEntries : null;
    
            var payload = {
                record: recordData,
                table_name: current.getTableName()
            };
    
            // Optional: Add assigned_to information
            if (current.assigned_to) {
                payload.record.assigned_to = {
                    email: current.assigned_to.email ? current.assigned_to.email.toString() : null,
                    name: current.assigned_to.name ? current.assigned_to.name.toString() : null,
                    user_name: current.assigned_to.user_name ? current.assigned_to.user_name.toString() : null
                };
            }
    
            // Optional: Add assignment_group information
            if (current.assignment_group) {
                payload.record.assignment_group = {
                    name: current.assignment_group.name ? current.assignment_group.name.toString() : null
                };
            }
    
            // Execute the REST call
            var payloadJson = JSON.stringify(payload);
            r.setRequestBody(payloadJson);
            var response = r.execute();
    
            var httpStatus = response.getStatusCode();
            var responseBody = response.getBody();
    
            // Log the result
            if (httpStatus == 200) {
                gs.info('[Risotto] Webhook sent successfully for ' + current.getValue('number'));
            } else if (httpStatus == 401 || httpStatus == 403) {
                gs.error('[Risotto] Authentication failed (status ' + httpStatus + ') for ' +
                        current.getValue('number') + '. Please verify webhook secret is correct.');
            } else if (httpStatus >= 500) {
                gs.error('[Risotto] Server error (status ' + httpStatus + ') for ' +
                        current.getValue('number') + '. Response: ' + responseBody);
            } else {
                gs.warn('[Risotto] Unexpected response status ' + httpStatus +
                       ' for ' + current.getValue('number') + '. Response: ' + responseBody);
            }
    
        } catch(ex) {
            gs.error('[Risotto] Exception while sending webhook for ' +
                    current.getValue('number') + ': ' + ex.message);
        }
    })(current, previous);
  5. Save and activate the Business Rule.
Important Notes
  • This script is pre-configured with your organization ID and webhook secret
  • Do not share this script publicly as it contains sensitive authentication information
  • If you need to regenerate the webhook secret, you'll need to update the Business Rule with the new script