Integration Builder scripting reference

The Integration Builder includes an editor that allows you to modify the default transformation scripts for your inbound and outbound integrations.

For information on working with scripts in Flow Designer custom steps and HTTP triggers, see Work with scripts in custom steps.

Scripting Language

Transformation scripts are written in JavaScript (JDK version 11) and should be compliant with ECMAScript 6. For security reasons, the instantiation of Java classes from within the scripting runtime is explicitly disallowed for all scripts running in the cloud. (Instantiation is allowed for scripts running on the xMatters Agent. which must be compliant with JDK version 8 and ECMAScript 5.1.)

Scripting Features

Incoming request object

The request object is used to describe the HTTP request posted to the integration service URL. You can use the transformation scripts to access the request headers, parameters, body, etc. The easiest way to examine the content of an incoming request is to send an HTTP request to your integration and then view the details in the Activity panel. In outbound integration scripts, the request object is referred to as the callback.

Request object properties
Property Description
body

This is the body of the request posted to the integration service URL, and usually contains the JSON or XML payload of an HTTP POST.

  • If the body contains JSON, you can use JSON.parse(request.body) in the script to convert it to a JavaScript object.
  • If the body contains XML, you can use one of the included XML libraries to manipulate the data.
  • If the body is in a query parameter, you can use request.parameters.
headers The HTTP headers of the incoming request. Note the Content-Type parameter that defines the payload type.
parameters

A JavaScript object featuring key-value pairs for any querystring parameters

If the Content-Type in the header is application/x-www-form-urlencoded, this section also contains the POST body parameters.

requestId The unique identifier (UUID) assigned to this request by the integration service when the request is received. This identifier is returned in the response, making it possible to match a request with the results of the script processing.
xtrace

An xMatters internal use ID that allows tracking of the request through the system.

The following is a sample request object:

{
	"body": "<incident importance=\"High\">\n    <ticket>16931</ticket>\n    <summary>Mail server is down</summary>\n    <recipients>\n        <username>bsmith</username>\n        <username>mmcbride</username>\n    </recipients>\n</incident>",
	"headers": {
		"Accept": "*/*",
		"Authorization": "Basic lmht9e46Yo9tc3xleA==",
		"Content-Length": "217",
		"Content-Type": "application/xml",
		"Host": "lugh.xmatters.com:8080",
		"User-Agent": "curl/7.40.0"
	},
	"method": "POST",
	"parameters": {},
	"remoteAddr": "127.0.0.1",
	"requestId": "afc9498a-ba47-418b-912f-d977091b7d2a",
	"timestamp": 1440001619011,
	"url": "http://lugh.xmatters.com:8080/integrations/6FE66C95-81C0-4DDC-B932-0D3609E234BA",
	"xtrace": "afc9498a-ba47-418b-912f-d977091b7d2a"
}

^ Back to top

 

Form and trigger objects

When working with scripts for "Transform content to create a new xMatters event" integrations, you can use the form object to refer to the default form chosen when building the integration. The form object has a single method, POST, which accepts the trigger object as an argument, and posts it to xMatters to create an event. Both the form and trigger objects are predefined and available from within the script. The trigger object should be equivalent to the request body used to trigger an event using the REST API. You can use the trigger object to set the recipients, priority, form properties, response options, conference bridge status, response counts and callbacks. It accepts the format described in the REST API help.

The following example illustrates how to use these objects to:

  • add recipients in addition to those specified in the payload or form, and target particular devices,
  • use or replace information from the form or payload,
  • join an existing conference bridge,
  • add additional response options beyond those specified in the form, and
  • trigger an event.
//Add hard-coded recipients to the recipients targeted by the form:
var recipients = [];
recipients.push({'id': 'ajoshi', 'recipientType' : 'PERSON'});
recipients.push({'id': 'mmcbride|Home Email', 'recipientType' : 'DEVICE'});
trigger.recipients = recipients;
 
//Add recipients from the payload to the recipients targeted by the form (make sure the payload includes recipients):
var recipients = [];
for (var i in payload.users)
{
var userId = payload.users[i].userId;
recipients.push({'id': userId});
}
trigger.recipients = recipients;
 
//Target specific devices for all targeted users, for example, Work Email:
var targetDeviceNames = [];
targetDeviceNames.push({"name" : "Work Email"});
 
//Set a property to overwrite the information from the payload:
trigger.properties.System = "Oracle database";
 
//Set a property to use the information from the payload:
trigger.properties['Incident ID'] = payload.properties.ticketnumber;
 
// Set the event priority:
trigger.priority = "High";
 
//Join an existing xMatters conference bridge:
conference.bridgeId = "3882920";
conference.type = "BRIDGE";
trigger.conference = conference;
 
//Include a new response option with existing response options:
var responseOptions = []
responseOptions.push({"id" : "295a2d1c-b738-4a34-af71-406b0e28e6d8"});
responseOptions.push({"id" : "051940e5-c20d-4e15-be6b-f753bf124e9f"});
responseOptions.push({"number": 4,
"text": "Reject",
"description": "I cannot help",
"prompt": "Reject",
"action": "RECORD_RESPONSE",
"contribution": "NEGATIVE",
"promptForComments": false
});
 
//Trigger the event
form.post(trigger);

^ Back to top

 

HTTP Client requests

Integration scripts can make outbound HTTP requests to an HTTP endpoint using the HTTP client. In the scripts, the outgoing request must specify one of the endpoints by its name, and may include the request method (GET, POST, etc.), a path to append to the URL, and any request headers, parameters, or body data.

The HTTP client

You can use the HTTP client from any transformation script. To make a request, use the global HTTP object's request function to create a request object, then use that object's write method to perform the request. A successful request will return a response object that you can inspect for details such as response headers, response body, and response status.

The following example illustrates a GET request using the HTTP object's request function and write method:

var params = request.parameters;
 
// Prepare the HTTP request
var req = http.request({
  'endpoint' : 'weatherAPI',
  'method' : 'GET',
  'path' : '/data/2.5/weather?q=' + params['location'],
  'headers' : {
    'x-api-key' : 'a3b5f9ca-5fea-4cf6-ae38-e6c1e4afeba9'
  }
});
 
// Send the request and retrieve the response
var resp = req.write();
 
// Post the form, if the request succeeded
if (resp.statusCode == 200) {
  var currentWeather = JSON.parse(resp.body);
  console.log("Current weather in " + currentWeather['name'] + " is " + currentWeather['weather'][0]['description']);
  trigger.properties['Location'] = currentWeather['name'];
  trigger.properties['Description'] = currentWeather['weather'][0]['description'];
  trigger.properties['Weather'] = currentWeather['weather'][0]['main'];
  var recipients = [];
  recipients.push({'id': 'mmcbride', 'recipientType' : 'PERSON'});
  trigger.recipients = recipients;
  form.post(trigger);
} else {
  console.log("Unable to post event: failed to get current weather conditions for " + params['location']);
}
 

HTTP request object and write function

The following function returns an HTTP request object that can later be sent using its write() function:

http.request(options)

The request function accepts a JavaScript object representing its options. The following table describes the available options:

Option Type Required Purpose
endpoint string yes

Name of the pre-configured endpoint (case-sensitive) that the request is targeting.

NoteSlack endpoints require an additional function call to add the Slack token to API requests.

method string   HTTP request method to use; default is GET
path string   Path to append to the URL defined in the pre-configured endpoint. Querystring parameters may be included.
headers object   HTTP headers to send with the request.
autoEncodeURI boolean/string  

By default, the Integration Builder automatically encodes some characters in the URI (for example, spaces and slashes). This helps us standardize the URLs and create default configurations for our built-in and packaged integrations that have the best chance of succeeding wherever they find themselves.

However, we recommend that you override this default behavior and manually encode special characters. That way, you can make sure you're sending exactly the request you intend — and not leaving it up to a machine to interpret.

To override this behavior, include the autoEncodeURI property and set it to false.

autoAppendCharset boolean/string  

By default, the Integration Builder automatically appends Charset=UTF-8 to the 'Content-Type' request header parameter, if provided. For example, the following request:

 
var apiRequest = http.request({
  'endpoint': 'xMatters',
  'path': '/',
  'method': 'POST',
  'headers': {
    'Content-Type': 'application/json'
  }
});
 

will result in a request where the 'Content-Type' value will be 'application/json; charset=UTF-8' (this is the same behavior as setting autoAppendCharset=true):

 
> GET https://example.xmatters.com/ HTTP/1.1
> Content-Type: application/json; charset=UTF-8
 

You can override the default behavior if you want to provide a different Charset parameter. To override the default Charset value, include the autoAppendCharset parameter and set it to false. For example, the following request:

 
var apiRequest = http.request({
  'endpoint': 'xMatters',
  'path': '/',
  'method': 'POST',
  'headers': {
    'Content-Type': 'application/json'
  },
  'autoAppendCharset': false,
});
 

will result in a request where the 'Content-Type' value is the exact value specified by the user with no modification by the Integration Builder:

 
> GET https://example.xmatters.com/ HTTP/1.1
> Content-Type: application/json

The request.write() function sends the HTTP request and returns the response if the request succeeds. Success includes any completed HTTP request, even if the response is a 404 "Not Found or 500 "Server Error". A failure means the HTTP request was not able to be made all; for example, due to an invalid host name or the connection refused by the remote server.

request.write([data])
 

If the HTTP request is a POST or other type that sends a request body, that body may be sent as the optional data parameter. If data is not a string, it will be encoded as a string using JSON.stringify. If the data is not intended to be sent as JSON, transform the body into a string and set the correct Content-Type header on the request object.

// Prepare the HTTP request
var req = http.request({
  'endpoint' : 'myEndPoint',
  'method' : 'POST',
  'path' : 'path/to/my/service',
  'autoEncodeURI': false,
  'headers': {
    'Content-Type': 'application/json'
  }
});
 
// Prepare the HTTP request body
var data = {};
data.ticket = {};
data.ticket.subject = 'Update from xMatters';
 
// Submit the request and capture the response
var response = req.write(data);

 

Response object

If the HTTP request is successful, the request.write() function returns an object describing the HTTP response with the following properties:

Property Data Type Description
httpVersion string HTTP version used to make the request; usually HTTP/1.1
statusCode integer HTTP status, such as 200, 404, or 500
statusMessage string The description of the statusCode, such as "OK", "Not Found", or "Server Error"
headers object The response headers
body string The response content

^ Back to top

 

HTTP/HTTPS webhooks

xMatters makes HTTP webhooks by sending a POST request to the specified URL, and passes information about the event as a JSON object in the request body. This section describes the content of the JSON payload that you can extract and use in your web application. For more information about webhooks in the Integration Builder, see Outbound integration triggers.

This same data format is used for trigger outputs in Flow Designer and for the request.body payload when an outbound integration calls a script.

The release of Flow Designer incorporated a redesign of the way payloads and properties are structured for HTTP requests. The following sections describe the changes and the new payload structures. For a description of the properties available in each trigger, see Flow triggers.

New JSON payload structures

The webhooks contain the same properties as before, but now each payload has a new, top-level object corresponding to the system activity of that trigger type. For example, the event comment webhook now contains an annotated object that includes all of the event information, the content of the comment, and details about the user who made the comment. These objects were added to make more information available about the activity, such as the timestamp and the person who caused the activity to happen (where applicable). They also include the type of activity that caused the webhook to fire, which is important for those webhooks that can fire for multiple reasons. Also, for ease of reference, the new objects include embedded objects that can be referenced directly in the Integration Builder scripts.

The Integration Builder parses out these top-level objects and their embedded objects and displays the available properties for each outbound integration type in the sidebar of the script editor. The legacy structures and payloads are still functional, but should be considered deprecated and anyone still using them is encouraged to update their scripts to the new structure. To help integrators update existing scripts, the following sections provide a comparison of the properties displayed in the sidebar of the script editor before the release of Flow Designer and afterward. They also provide examples of the JSON payloads for webhooks in outbound integration triggers.

Notes:

  • The new JSON payloads provide dates and time in ISO-8601 format (e.g.: 2019-01-15T18:03:16.580Z).
  • If you created an outbound integration in the Integration Builder, the new JSON payload will include all of the event properties. The legacy payloads contain only those properties with the Include in Outbound Integrations option enabled.
  • Some properties in the new structure are currently null. This is due to the limited amount of data available when a webhook is created, either because the triggering event does not include that data or because it is not available except by querying the database. These properties will be populated as additional triggers and features become available.

How to use the new payloads with the xMatters Agent

The latest versions of the xMatters Agent (v1.4.0 or later) support the new payloads; there's nothing additional you need to do. If you're creating an integration to run on an older version of the xMatters Agent, you need to parse the payload before you can access it.

Add the parse command to your script. For example:

var payload = JSON.parse(request.body);

You can then access the objects in the payload. For example:

payload.statusChanged.at

Event objects

All webhooks include the following properties in the event object. For descriptions and examples of these properties, see Flow triggers.

New Legacy

EVENT OBJECTS

event.id

event.eventId

event.status

event.created

event.priority

event.targetedRecipients

event.initiator

event.properties

| event.properties.<propertyName>

COMMON PROPERTIES

date

eventIdentifier

eventProperties

| <propertyName>

^ Back to top

 

Device delivery

Device delivery webhooks are created when a notification is delivered to a recipient. They contain the delivery status and the user and device the notification was delivered to.

The trigger object is called deliveryStatusUpdated, and includes the embedded notification object. For descriptions and examples of the available properties, see Flow triggers.

New Legacy

NOTIFICATION OBJECTS

notification.deliveryStatus

notification.recipient.id

notification.recipient.name

notification.recipient.targetName

notification.recipient.owner.id

notification.recipient.owner.firstName

notification.recipient.owner.lastName

notification.recipient.owner.targetName

 

DELIVERYSTATUSUPDATED OBJECTS

deliveryStatusUpdated.at

deliveryStatusUpdated.auditType

deliveryStatusUpdated.deliveryStatusType

deliveryStatusUpdated.deliveryStatusMessage

DELIVERY OUTBOUND INTEGRATIONS

deliveryStatus

device

deviceId

eventType

message

recipient

Example payload

This webhook shows that a notification was successfully delivered to the Work Email device of mmcbride. The form properties are included in the event.properties object.

{
  "date": "18-11-15 18:57:41.108",
  "deliveryStatus": "Delivered",
  "deliveryStatusUpdated": {
    "at": "2018-11-15T18:57:41.108Z",
    "auditType": "NOTIFICATION_DELIVERED",
    "by": null,
    "deliveryStatusMessage": "Notification delivered",
    "deliveryStatusType": "LIVE_NOTIFICATION_PROVIDER_DELIVERED",
    "id": "268e7c8c-920d-43d5-beab-677cb05baafd",
   "notification": {
      "deliveryStatus": "DELIVERED",
      "event": {
        "id": "683dc2ad-0542-40c3-b8c7-0f9be17f3ad4",
        "eventId": "1209018",
        "status": "ACTIVE",
        "created": "2019-05-02T21:08:49.930Z",
        "priority": "MEDIUM",
        "targetedRecipients": [
          "mmcbride|Work Email"
        ],
        "initiator": "admin",
        "properties": {
          "customer_impacting": true,
          "Severity": "Medium",
          "System": "na3-dev-linux-data"
        }
      },
      "recipient": {
        "deviceId": "200005",
        "deviceType": null,
        "id": "8e67ce4a-0ffd-4b4f-bb0e-2575dc819f6e",
        "name": "Work Email",
        "owner": {
          "firstName": null,
          "id": "e3d52e21-c278-4898-9a27-65779e1086b5",
          "lastName": null,
          "recipientType": "PERSON",
          "targetName": "mmcbride"
        },
        "recipientType": "DEVICE",
        "targetName": "mmcbride|Work Email"
      }
    }
  },
  "device": "Work Email",
  "deviceId": 200005,
  "deviceUUID": "8e67ce4a-0ffd-4b4f-bb0e-2575dc819f6e",
 "eventIdentifier": 227003,
  "eventProperties": [ ],
  "eventType": "LIVE_NOTIFICATION_PROVIDER_DELIVERED",
  "message": "Notification delivered",
  "recipient": "mmcbride"
}
Delivery status types

The following table describes the values that may appear in the deliveryStatusUpdated.deliveryStatusType field.

Device Delivery Status Event Type Description
DELIVERED LIVE_NOTIFICATION_DEVICE_DELIVERED The notification was delivered to the device. The notification is considered delivered.
LIVE_NOTIFICATION_PROVIDER_DELIVERED The notification was delivered to the provider that will forward the notification to the device. The notification is considered delivered.
LIVE_NOTIFICATION_DEVICE_VOICEMAIL_CALLBACK The notification was delivered to the device and reached voice mail. xMatters left a voice mail message with call-back information because the voice mail option was set to "Callback Info Only". The notification is considered delivered.
LIVE_NOTIFICATION_DEVICE_VOICEMAIL_CONTENT The notification was delivered to the device and reached voice mail. xMatters left a voice mail message with the content of the notification because the voice mail option was set to "Message Content Only". The notification is considered delivered.
LIVE_NOTIFICATION_DEVICE_VOICEMAIL_CONTENT_AND_CALLBACK The notification was delivered to the device and reached voice mail. xMatters left a voice mail message with call-back information and the content of the notification because the voice mail option was set to "Content and Callback Info". The notification is considered delivered.
LIVE_NOTIFICATION_DEVICE_VOICEMAIL_HANG_UP The notification was delivered to the device and reached voice mail. xMatters did not leave a voice mail message because the voice mail option was set to "Do Not Leave Message". The notification is considered delivered.
FAILED CNS_FAILED The xMatters CNS service cannot deliver the notification. This could be caused by the provider or the CNS service.
LIVE_NOTIFICATION_CNS_FAILED_DELIVERED The notification was not delivered to the provider. A message that describes the error is included in the message field.
LIVE_NOTIFICATION_CNS_FAILED_DELIVERED_WITH_CODE The notification was not delivered to the provider. A message that describes the error and an error code from the provider is included in the message field.
LIVE_NOTIFICATION_DEVICE_ATTEMPT_FAILURE The notification was not delivered. A message that describes the error is included in the message field.
LIVE_NOTIFICATION_DEVICE_ATTEMPT_FAILURE_FAX_OR_MODEM_DETECT The notification was not delivered because a fax or modem was detected. The message field states whether it detected a fax or modem.
LIVE_NOTIFICATION_DEVICE_ATTEMPT_FAILURE_PROVIDER_RESPONDED The notification was not delivered, and the provider responded with an error. The provider's error message is included in the message field.
LIVE_NOTIFICATION_FAILURE_WITH_ERROR_CODE The notification failed. An error code from the provider is included in the message field.
LIVE_NOTIFICATION_VOICEMAIL_RETRY

The notification was delivered to the device and reached voice mail. xMatters did not leave a voice mail message because the voice mail options are set to "Retry". The notification is not considered delivered.

The message field describes when xMatters will attempt to retry this notification.

DEVICE_NOTIFICATION_PERMANENT_FAILED The notification cannot be delivered to the device. A message that describes the error is included in the message field.
PERSON_NO_NOTIFIABLE_DEVICES The recipient of the notification has no devices that can be notified.
PERSON_NO_DEVICES_AFTER_FILTERING The recipient of the notification has no devices that can be notified after device filters were applied.
UNCHANGED LIVE_NOTIFICATION_DEVICE_ATTEMPT_DISCONNECT

The notification was delivered but the call was disconnected before playback was completed.

^ Back to top

 

Escalations

Escalation webhooks are created when an escalation in a group occurs. They include the group containing the shift with the escalation, the reason for the escalation, the user that escalated the event (if applicable), the type of escalation, the recipients the event escalated from, and the recipients the event escalated to.

The trigger object is called escalated, and includes the embedded escalation object. For descriptions and examples of the available properties, see Flow triggers.

New Legacy

ESCALATION OBJECTS

escalation.reason

escalation.esclationType

escalation.group.id

escalation.group.status

escalation.group.targetName

escalation.from[i].id

escalation.from[i].recipientType

escalation.from[i].status

escalation.from[i].targetName

escalation.to[i].id

escalation.to[i].recipientType

escalation.to[i].status

escalation.to[i].targetName

 

ESCALATED OBJECTS

escalated.at

escalated.by.id

escalated.by.firstName

escalated.by.lastName

escalated.by.targetName

ESCALATION OUTBOUND INTEGRATIONS

escalation.byUser.id

escalation.byUser.recipientType

escalation.byUser.status

escalation.byUser.targetName

escalation.escalationType

escalation.eventId

escalation.from[i].id

escalation.from[i].recipientType

escalation.from[i].status

escalation.from[i].targetName

escalation.group.id

escalation.group.recipientType

escalation.group.status

escalation.group.targetName

escalation.id

escalation.reason

escalation.to[i].id

escalation.to[i].recipientType

escalation.to[i].status

escalation.to[i].targetName

Example payload

This example shows the body of a webhook that occurred when Brian Jennings' response manually triggered a peer escalation in the IT Helpdesk group. The event escalated from Brian Jennings to Mary McBride and the NOC Group.

{
  "date": "18-11-16 17:56:16.287",
  "escalated": {
    "at": "2018-11-16T17:56:16.287Z",
    "auditType": "NOTIFICATION_ESCALATED",
    "by": {
      "firstName": null,
      "id": "9f3bc0b3-bf58-40c9-9e10-909b7554a69a",
      "lastName": null,
      "recipientType": "PERSON",
      "targetName": "bjennings"
    },
    "escalation": {
      "escalationType": "PEER",
      "event": {
        "id": "683dc2ad-0542-40c3-b8c7-0f9be17f3ad4",
        "eventId": "1209018",
        "status": "ACTIVE",
        "created": "2019-05-02T21:08:49.930Z",
        "priority": "MEDIUM",
        "targetedRecipients": [
          "IT Helpdesk"
        ],
        "initiator": "admin",
        "properties": {
          "customer_impacting": true,
          "Severity": "Medium",
          "System": "na3-dev-linux-data"
        }
      },
      "from": [
        {
        "firstName": null,
        "id": "9f3bc0b3-bf58-40c9-9e10-909b7554a69a",
        "lastName": null,
        "recipientType": "PERSON",
        "targetName": "bjennings"
        }
      ],
      "group": {
        "id": "ebbabbd2-7eaf-4a8c-89cd-de2e063eff46",
        "recipientType": "GROUP",
        "targetName": "IT Helpdesk"
      },
      "reason": "ACTIVE",
      "to": [
        {
        "firstName": null,
        "id": "e3d52e21-c278-4898-9a27-65779e1086b5",
        "lastName": null,
        "recipientType": "PERSON",
        "targetName": "mmcbride"
        }
        {
        "id": "r3g98q21-f288-9365-9a27-63676e10f8j3",
        "recipientType": "GROUP",
        "targetName": "NOC Group"
        }
      ]
    },
    "id": "25e2522f-8692-4f0d-a7bf-fa1aad80b562"
  },
  "escalation": {
    "byUser": { },
    "escalationType": "PEER",
    "eventId": 228002,
    "from": [ ],
    "group": { },
    "id": "25e2522f-8692-4f0d-a7bf-fa1aad80b562",
    "reason": "ACTIVE",
    "to": [ ]
  },
  "eventIdentifier": 228002,
  "eventProperties": [ ]
}

^ Back to top

 

Event comment webhooks

Event comment webhooks are created when a user comments on an event, either when they respond to notifications in their email, the xMatters mobile app or Inbox, or when they add comments directly to the Tracking report or using the xMatters REST API. They include the user that added a comment, the event the comment was added to, and the value of the comment.

The trigger object is called annotated, and includes the embedded annotation object. For descriptions and examples of the available properties, see Flow triggers.

New Legacy

ANNOTATION OBJECTS

annotation.author.id

annotation.author.firstName

annotation.author.lastName

annotation.author.targetName

annotation.comment

annotation.response.response

ANNOTATED OBJECTS

annotated.at

COMMENT OUTBOUND INTEGRATIONS

author.firstName

author.id

author.lastName

author.recipientType

author.targetName

comment

event.eventId

event.id

Example payload

This example shows the body of a webhook that occurred when Victor Martinez commented "Already on site" on an event using the Tracking report in the web user interface.

{
  "annotated": {
    "annotation": {
      "author": {
        "firstName": "Victor",
        "id": "4ec847cd-ae22-4443-bbef-43d0e11c1501",
        "lastName": "Martinez",
        "recipientType": "PERSON",
        "targetName": "vmartinez"
      },
      "comment": "Already on site",
      "event": {
        "id": "683dc2ad-0542-40c3-b8c7-0f9be17f3ad4",
        "eventId": "1201249",
        "status": "ACTIVE",
        "created": "2019-05-02T21:08:49.930Z",
        "priority": "MEDIUM",
        "targetedRecipients": [
          "Dev Group"
        ],
        "initiator": "admin",
        "properties": {
          "customer_impacting": true,
          "Severity": "Medium",
          "System": "na3-dev-linux-data"
        }
      }
    },
    "at": "2018-11-15T23:25:39.920Z",
    "auditType": "EVENT_ANNOTATED",
    "by": {
      "firstName": "Victor",
      "id": "4ec847cd-ae22-4443-bbef-43d0e11c1501",
      "lastName": "Martinez",
      "recipientType": "PERSON",
      "targetName": "vmartinez"
    },
    "id": "74c0a722-8ace-4691-8fcf-143405b8f2f7"
  },
  "author": { },
  "comment": "Already on site",
  "date": "18-11-15 23:25:39.920",
  "event": { },
  "eventIdentifier": 228000,
  "eventProperties": [ ],
  "response": {}
}

^ Back to top

 

Event status updates

Event status webhooks are created when an event is initiated or terminated, or when the status of an event changes. They include the type of event status change that triggered the webhook and information about the user who initiated the status change.

The trigger object is called statusChanged. For descriptions and examples of the available properties, see Flow triggers.

New Legacy

STATUSCHANGED OBJECTS

statusChanged.at

statusChanged.by.id

statusChanged.by.firstName

statusChanged.by.lastName

statusChanged.by.targetName

statusChanged.auditType

STATUS OUTBOUND INTEGRATIONS

status

username

Example payload

This example shows the body of a webhook that occurred when Sam Johnson created an event.

{
  "date": "18-11-15 18:03:16.580",
  "eventIdentifier": 226014,
  "eventProperties": [ ],
  "status": "active",
  "statusChanged": {
    "at": "2018-11-15T18:03:16.580Z",
    "auditType": "EVENT_CREATED",
    "by": {
      "firstName": "Samantha",
      "id": "4ec847cd-ae22-4443-bbef-43d0e11c1501",
      "lastName": "Johnson",
      "recipientType": "PERSON",
      "targetName": "sjohnson"
    },
      "event": {
        "id": "683dc2ad-0542-40c3-b8c7-0f9be17f3ad4",
        "eventId": "1209018",
        "status": "ACTIVE",
        "created": "2019-05-02T21:08:49.930Z",
        "priority": "MEDIUM",
        "targetedRecipients": [
          "mmcbride|Work Email"
        ],
        "initiator": "sjohnson",
        "properties": {
          "customer_impacting": true,
          "Severity": "Medium",
          "System": "na3-dev-linux-data"
        }
    },
    "id": "bab5c26a-8dd3-4172-9c8e-3f43f6c92ca5"
  },
  "username": "sjohnson"
}

^ Back to top

 

Responses

Response webhooks are created when a recipient responds to a notification. They include information about the person who responded, the device they responded on, their response, and any comments they made when they responded to the notification.

The trigger object is called respondedTo, and includes the embedded response object. For descriptions and examples of the available properties, see Flow triggers.

New Legacy

RESPONSE OBJECTS

response.deviceName

response.response

 

RESPONDEDTO OBJECTS

respondedTo.at

respondedTo.by.id

respondedTo.by.firstName

respondedTo.by.lastName

respondedTo.by.targetName

respondedTo.auditType

RESPONSE OUTBOUND INTEGRATIONS

annotation

device

recipient

response

Example payload

This example shows the body of a webhook that occurred when Mary McBride responded with Accept using an email device and added the comment "I'm on my way".

{
  "annotation": "",
  "date": "18-11-15 22:26:19.681",
  "device": "Work Email",
  "eventIdentifier": 227011,
  "eventProperties": [ ],
  "recipient": "mmcbride",
  "respondedTo": {
    "at": "2018-11-15T22:26:19.681Z",
    "auditType": "RESPONSE_RECEIVED",
    "by": {
      "firstName": null,
      "id": "4ec847cd-ae22-4443-bbef-43d0e11c1501",
      "lastName": null,
      "recipientType": "PERSON",
      "targetName": "mmcbride"
    },
    "id": "68add091-7500-470b-a98a-15ef01c03e49",
    "response": {
      "deviceName": "Work Email",
      "event": {
        "id": "683dc2ad-0542-40c3-b8c7-0f9be17f3ad4",
        "eventId": "1209018",
        "status": "ACTIVE",
        "created": "2019-05-02T21:08:49.930Z",
        "priority": "MEDIUM",
        "targetedRecipients": [
          "mmcbride|Work Email"
        ],
        "initiator": "admin",
        "properties": {
          "customer_impacting": true,
          "Severity": "Medium",
          "System": "na3-dev-linux-data"
        }
      },
      "notification": null,
      "recipient": {
        "deviceId": null,
        "deviceType": null,
        "id": null,
        "name": "Work Email",
        "owner": {
          "firstName": null,
          "id": "4ec847cd-ae22-4443-bbef-43d0e11c1501",
          "lastName": null,
          "recipientType": "PERSON",
          "targetName": "mmcbride"
        },
        "recipientType": "DEVICE",
        "targetName": "mmcbride|Work Email"
      },
      "response": "Accept"
    }
  },
  "response": "Accept"
}

^ Back to top

 

Targeted recipient failures

Targeted recipient failures webhooks are created when xMatters cannot immediately notify anyone for an event associated with the selected form. They include the type of targeting attempt, who could not be targeted, and the total number of targeted recipients.

The trigger object is called targetingFailed, and includes the embedded targeted object. For descriptions and examples of the available properties, see Flow triggers.

New Legacy

TARGETED OBJECTS

targeted.recipients[i].id

targeted.recipients[i].recipientType

targeted.recipients[i].status

targeted.recipients[i].targetName

targeted.totalRecipients

targeted.triggerType

 

TARGETINGFAILED OBJECTS

targetingFailed.at

TARGETED RECIPIENT FAILURES OUTBOUND INTEGRATIONS

targeted.recipients[i].id

targeted.recipients[i].recipientType

targeted.recipients[i].status

targeted.recipients[i].targetName

targeted.totalRecipients

targeted.triggerType

Example payload

This example shows the body of a webhook that occurred when xMatters could not notify Sara Lawson, the only targeted recipient for a notification.

{
  "date": "18-11-16 10:21:54.000",
  "eventIdentifier": 228004,
  "eventProperties": [ ],
  "targeted": {
    "recipients": [ ],
    "totalRecipients": 1,
    "triggerType": "INITIAL EVENT"
  },
  "targetingFailed": {
    "at": "2018-11-16T10:21:54.000Z",
    "auditType": "NOTIFICATION_NO_RECIPIENT",
    "targeted": {
      "event": {
        "id": "683dc2ad-0542-40c3-b8c7-0f9be17f3ad4",
        "eventId": "1209018",
        "status": "ACTIVE",
        "created": "2019-05-02T21:08:49.930Z",
        "priority": "MEDIUM",
        "targetedRecipients": [
          "slawson"
        ],
        "initiator": "admin",
        "properties": {
          "customer_impacting": true,
          "Severity": "Medium",
          "System": "na3-dev-linux-data"
        }
      },
      "recipients": [
        {
          "id": "d5848ec6-ff8f-40c4-94a6-b411a146a85f",
          "recipientType": "PERSON",
          "targetName": "slawson"
        }
      ],
      "totalRecipients": 1,
      "triggerType": "INITIAL EVENT"
    }
  }
}

^ Back to top

Logging

You can use the console object to write messages from the script to the log file in the Activity panel.

For example:

console.log("About to post to xMatters");

Stringify

If you want to write out the value of a JavaScript object, use JSON.stringify to serialize it to JSON; otherwise, it will appear in the log as "[object Object]".

For example:

// To log a JavaScript object in a readable format:
console.log(JSON.stringify(trigger));

 

^ Back to top

 

Shared Libraries

Shared libraries allow utility functions written in JavaScript code to be factored out of integration scripts and shared between inbound and outbound integrations in the same workflow.

The following example illustrates a shared library called 'String Utilities' that contains several functions and a variable. For functions or variables to be available from transformation scripts, they must be assigned to properties of the exports object that is available within the shared library:

/**
 * Remove trailing and leading whitespace from a string
 */
function trim(str) {
  return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}
 
/**
 * Remove trailing whitespace from a string
 */
var removeTrailingWhitespace = function(str) {
  return str.replace(/\s\s*$/, '');
};
 
// This function will not be available to integration scripts because
// it is not included in the exports below
 function ltrim(str) {
  return str.replace(/^\s\s*/, '');
}
 
var EMPTY_STRING = '';
 
// Export a function by name
exports.trim = trim;
// Export a function that was assigned to a variable
exports.rtrim = removeTrailingWhitespace;
// Export a value
exports.EMPTY_STRING = EMPTY_STRING;
// Export a function without assigning to a variable
exports.isBlank = function(str) {
  return (str == null || trim(str) == EMPTY_STRING);
};
 

To use functions that are defined in a shared library in your transformation script, import the shared library using the require() function:

// Import the shared library by name (case-sensitive)
var StringUtils = require('String Utilities');
 
var data = JSON.parse(request.body);
 
// Reference exported functions and values using the variable
// returned from the require function
var targetName = StringUtils.trim(data.username);
if (StringUtils.isBlank(targetName)) {
  console.log("no username given");
  targetName = StringUtils.EMPTY_STRING;
}

You can also use the require() function to import shared libraries into another shared library. For more information on creating shared libraries, see Shared libraries.

Library names are case sensitive.

^ Back to top

 

Constants

Integration developers can use constants to help non-technical users manipulate variables within integration scripts. Constants can be defined and implemented within the scripts when the integration is created, and users can update the values for the constants without needing to edit the scripts.

For more information about creating and managing constants, see Constants.

The following examples illustrate how to reference a constant from within the transformation script:

// Access and log a constant
console.log(constants.constantName);
console.log(constants.NameOfConstant);
 
// Access and log a constant with a non-compatible name
console.log(constants["constant-name"]);
console.log(constants["Date and Time Constant"]);
 
// Access and log a built-in constant
console.log(constants.builtin.baseUrl);
 
// Log all constants
console.log(JSON.stringify(constants));
 
// Access a constant containing JSON information
var jsonobj = JSON.parse(constants.json);
console.log("Hello, " + jsonobj.firstname + " " + jsonobj.lastname);
 
// Access a constant containing XML 
var xmlobj = JXON.parse(constants.xml);
console.log(JSON.stringify(xmlobj));
 
// Evaluate the code within a constant
eval(constants.evaluableCode);

^ Back to top

 

XML manipulation

The Integration Builder includes the following libraries that allow you to manipulate XML payloads. These are pure-JavaScript libraries sourced from "npm" (the package manager for Node.js), and packaged for use by the Nashorn engine using "browserify".

Library Description
XMLUtils.DOMParser

This is an implementation of the W3C DOM parser specification. The source library is XMLDOM (https://github.com/jindw/xmldom).

The DOMParser is a low-level parser used by the JXON and xpath libraries below, but can also be used directly.

XMLUtils.xpath This library allows you to read values from an XML DOM using the xpath syntax. The source library is xpath (https://github.com/yaronn/xpath.js).
XMLUtils.JXON

This library can be used to convert an XML document object into a native JavaScript object for further manipulation. The source library is jxon (https://github.com/tyrasd/jxon).

The Integration Builder provides a simplifying wrapper object for XMLUtils.JXON that takes an XML-formatted string and returns a JavaScript object using a single method, parse.

The wrapper takes this:

var obj = XMLUtils.JXON.build(new XMLUtils.DOMParser().parseFromString(xml));
 

And allows you to do this:

var obj = JXON.parse(xml);
 

By default, JXON case-folds all tag and attribute names to lowercase. For example, both <username> and <USERNAME> would be converted to a property called username in the JavaScript. To retain the exact case of tags and attributes, enable the following option in the script prior to calling JXON.parse:

XMLUtils.JXON.config({'lowerCaseTags': false});

Examples

The following examples illustrate how to use the included libraries to manipulate incoming XML payloads.

Incoming XML Manipulation
<incident importance="High">
    <ticket>1234</ticket>
    <summary>Mail server is down</summary>
    <recipients>
        <username>bsmith</username>
        <username>mmcbride</username>
    </recipients>
</incident>

Using DOMParser

var xml = request.body;
 
var doc = new XMLUtils.DOMParser().parseFromString(xml);
 
trigger.properties['Incident ID'] = doc.getElementsByTagName("ticket")[0].firstChild.data;
 
trigger.properties.Summary = doc.getElementsByTagName("summary")[0].firstChild.data;
 
var recipients = [];
var recips = doc.getElementsByTagName("username");
for (var i = 0; i < recips.length; i++) {
    recipients.push({"targetName": recips.item(i).firstChild.data});
}
trigger.recipients = recipients;
 
trigger.priority = doc.getElementsByTagName("incident")[0].getAttribute("importance");
 
form.post(trigger);

Using xpath:

var str = request.body;
// Build the XML document from the request
var doc = new XMLUtils.DOMParser().parseFromString(str, 'text/xml');
 
// Get the ticket number
var ticket = XMLUtils.xpath.select('//ticket/text()', doc)[0].data;
trigger.properties['Incident ID'] = ticket;
console.log("Ticket: " + ticket);
 
// Get the summary
var summary = XMLUtils.xpath.select('//summary/text()', doc)[0].data;
trigger.properties.Summary = summary;
console.log("Summary: " + summary);
 
// Loop over the recipients objects
var recipients = XMLUtils.xpath.select('//recipients/username', doc);
trigger.recipients = [];
for (var i in recipients) { var recipientUsername = recipients[i].firstChild.data; console.log("Adding recipient " + recipientUsername); trigger.recipients.push({"id": recipientUsername}); } // Get the priority var importance = XMLUtils.xpath.select('//incident/@importance', doc)[0].value; console.log("Priority: " + importance); trigger.priority = importance; // Post the trigger to the form form.post(trigger);

Using JXON:

var xml = request.body;
var obj = JXON.parse(xml);
console.log(JSON.stringify(obj));
/* The following data gets logged:
{
    "incident": {
        "@importance": "High",
        "recipients": {
            "username": [
                "bsmith",
                "mmcbride"
            ]
        },
        "summary": "Mail server is down",
        "ticket": 1234    }
}
*/
var data = obj.incident;
trigger.properties['Incident ID'] = data.ticket;
trigger.properties.Summary = data.summary;
var recipients = [];
for (var i in data.recipients.username) {
    recipients.push({"targetName": data.recipients.username[i]});
}
trigger.recipients = recipients;
trigger.priority = data['@importance'];
form.post(trigger);
<soap:Envelope
 xmlns:soap="http://www.w3.org/2003/05/soap-envelope"
 xmlns:sch="http://www.xmatters.com/webservices/schema#5.5.47">
   <soap:Header/>
   <soap:Body>
      <sch:AddEvent>
         <sch:user>user1010</sch:user>
         <sch:password>tester</sch:password>
         <sch:clientTimestamp xsi:nil="true"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>
         <sch:clientIP xsi:nil="true"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>
         <sch:clientOSUser xsi:nil="true"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>
         <sch:company>mustafar</sch:company>
        <sch:eventTokens>
            <sch:eventToken>
               <sch:name>Incident ID</sch:name>
               <sch:value>12345</sch:value>
            </sch:eventToken>
            <sch:eventToken>
               <sch:name>Impact</sch:name>
               <sch:value>High</sch:value>
            </sch:eventToken>
            <sch:eventToken>
               <sch:name>Summary</sch:name>
               <sch:value>testing SOAP endpoint</sch:value>
            </sch:eventToken>
         </sch:eventTokens>
      </sch:AddEvent>
   </soap:Body>
</soap:Envelope>

Using xpath with namespace:

var doc = new XMLUtils.DOMParser().parseFromString(request.body);
var select = XMLUtils.xpath.useNamespaces({"sch": "http://www.xmatters.com/webservices/schema#5.5.47"});
var tokens = select('//sch:eventTokens/sch:eventToken', doc);
 
// Iterate the event tokens to build the form properties
for (var i in tokens) {
  var nameToken = select('sch:name/text()', tokens[i])[0].data;
  var valueToken = select('sch:value/text()', tokens[i])[0].data;
  console.log("Adding property: " + nameToken + " = " + valueToken);
  trigger.properties[nameToken] = valueToken;
}
 
// Extract the target name from the incoming request and add to the trigger
var targetName = select('//sch:user/text()', doc)[0].data;
console.log("Adding Recipients: " + targetName);
var recipients = [];
recipients.push({
    'targetName': targetName
});
trigger.recipients = recipients;
console.log(JSON.stringify(trigger));
 
// Post the form to xMatters
form.post(trigger);

^ Back to top