# ServiceNow

Configure ServiceNow integration with Risotto

Risotto integrates with ServiceNow to provide bidirectional ticket synchronization. This allows you to manage incidents in either system while keeping them synchronized.

> **Warning:** You must have the `admin` role or appropriate permissions in ServiceNow to set
> up this integration, create Business Rules, and generate API credentials.

## Prerequisites

Before setting up the ServiceNow integration, ensure you have:

- Admin access to your ServiceNow instance
- A ServiceNow instance URL (e.g., `https://yourcompany.service-now.com`)
- Ability to create integration users and set passwords
- Permission to create Business Rules in ServiceNow

## Setup Process

1. **Create ServiceNow Integration User**

   In your ServiceNow instance, create a dedicated integration user for Risotto.

   1. Navigate to **User Administration > Users**
   2. Click **New** to create a new user
   3. Fill in the required details:
      - User ID: `risotto_integration`
      - First name: `Risotto`
      - Last name: `Integration`
      - Set a strong password
   4. Assign the necessary roles (at minimum: `itil`, `rest_service`)
   5. Save the user record

   > **Tip:** Creating a dedicated integration user helps with auditing and security management.

   > **Note:** **Alternative Authentication Method**: ServiceNow also supports API keys for inbound REST requests (Washington D.C. release and later). API keys provide easier management without password expiration concerns. See the [ServiceNow API Key Authentication Guide](https://www.servicenow.com/community/developer-advocate-blog/inbound-rest-api-keys/ba-p/2854924) for setup instructions.

2. **Configure ServiceNow in Department Settings**

   In your Risotto dashboard, configure ServiceNow integration at the department level.

   1. Go to **Settings**.
   2. Under **Departments**, click the department you want to enable ServiceNow for, then click **Ticket Sync**.
   3. Click **Add ticket sync**.
   4. Select **ServiceNow**.
   5. In the **Configure ServiceNow for \<department>** dialog, fill in these fields:
      - **Instance URL**: Your ServiceNow instance URL (e.g., `https://dev12345.service-now.com`)
      - **Username**: The integration user username (e.g., `risotto_integration`)
      - **Password**: The integration user's password
   6. Click **Save**.

   *Product example: The Configure ServiceNow for IT dialog, with the instance URL, the integration user's username and password, and Save.*

   7. Risotto opens the **Create a ServiceNow Webhook** dialog. Click **Copy Script** and keep the script for the Business Rule step.

   *Product example: The Create a ServiceNow Webhook dialog: the Business Rule steps, the pre-configured script, and Copy Script.*

   8. Make sure **External ticket sync enabled** is on.

   Risotto syncs with the `incident` table and uses ServiceNow's standard incident states. See [State Mapping](#state-mapping).

   > **Warning:** The script contains your webhook secret. Do not share it. To see the script again, open the **Connected** menu on the department's **ServiceNow** card, choose **Configure...**, and click **Save**.

   > **Note:** The integration uses Basic Authentication with the ServiceNow Table API. Credentials are stored encrypted in Risotto.

3. **Configure ServiceNow Business Rule**

   Set up a Business Rule in ServiceNow to send webhook notifications to Risotto for real-time updates.

   1. In ServiceNow, navigate to **System Definition > Business Rules**
   2. Click **New** to create a new Business Rule
   3. Configure the basic settings:
      - **Name**: `Risotto Incident Sync`
      - **Table**: `Incident [incident]`
      - **Active**: Checked
      - **Advanced**: Checked
   4. Set when to run:
      - **When**: `after`
      - **Insert**: Checked
      - **Update**: Checked
   5. Add filter conditions (click **Add Filter Condition**):
      - **Comments** `changes` OR
      - **Work notes** `changes` OR
      - **Assigned to** `changes`
   6. In the **Script** field, paste the script you copied from the **Create a ServiceNow Webhook** dialog. It already contains your organization ID and webhook secret.
   7. Save the Business Rule

4. **Test Risotto → ServiceNow Sync**

   After completing Steps 1-2, you can test one-way synchronization from Risotto to ServiceNow.

   1. Create a ticket via Risotto (in Slack or the Dashboard)
   2. Navigate to ServiceNow and verify the incident appears there
   3. Change the ticket's status in Risotto, for example to **Resolved**
   4. Verify the incident's state changes in ServiceNow

   > **Note:** At this stage, you have **one-way sync only** (Risotto → ServiceNow). Incidents created or updated in ServiceNow will **not** sync to Risotto until you complete Step 3 (Business Rule setup).

5. **Test ServiceNow → Risotto Sync**

   After completing Step 3 (Business Rule), test bidirectional synchronization.

   1. Create an incident in ServiceNow
   2. Verify it appears in Risotto within a few seconds
   3. Add a comment or work note in ServiceNow
   4. Verify the comment appears in Risotto
   5. Update the incident status in ServiceNow
   6. Verify the status changes in Risotto

   > **Tip:** Check ServiceNow System Logs (**System Logs > System Log > All**) for webhook execution logs. Look for "Risotto webhook sent successfully" messages.

## Features

Once configured, the ServiceNow integration provides:

- **Bidirectional Sync**: Incidents created in either system are synchronized to the other
- **State Synchronization**: ServiceNow states (New, In Progress, On Hold, Resolved, Closed) map to Risotto ticket statuses
- **Comment Sync**: Work notes and comments added in ServiceNow appear in Risotto
- **Additional field sync**: A department's [additional ticket fields](https://www.tryrisotto.com/docs/dashboard/settings/departments#syncing-field-values-to-jira-or-servicenow) can be mapped to ServiceNow columns, and their values are pushed to the incident when it is created or updated
- **Automatic Responses**: Risotto can automatically respond to ServiceNow incident updates

## Field Mappings

The ServiceNow integration automatically maps fields between the two systems:

### ServiceNow → Risotto

| ServiceNow Field      | Risotto Field      | Notes                   |
| --------------------- | ------------------ | ----------------------- |
| `number`              | External ticket ID | For example, INC0010001 |
| `short_description`   | Title              | Ticket title            |
| `description`         | Description        | Ticket description      |
| `state` (1,2,3,6,7,8) | Status             | See state mapping below |

### State Mapping

**ServiceNow → Risotto:**

- 1 (New) → `open`
- 2 (In Progress) → `in_progress`
- 3 (On Hold) → `waiting_for_response`
- 6 (Resolved) → `resolved`
- 7 (Closed) → `closed`
- 8 (Canceled) → `closed`

**Risotto → ServiceNow:**

- `in_progress` → 2
- `waiting_for_response` → 3
- `waiting_for_support` → 2
- `waiting_for_approval` → 2
- `resolved` → 6
- `closed` → 7

## Business Rule Setup

The ServiceNow Business Rule sends webhook notifications to Risotto when incidents are created or updated. Follow these steps to configure it:

### Configuration Requirements

The Business Rule script requires three configuration values:

1. **RISOTTO_ORG_ID**: Your Risotto organization ID
2. **WEBHOOK_SECRET**: Your ServiceNow webhook secret

The script in the **Create a ServiceNow Webhook** dialog already contains both values. Risotto shows this dialog each time you save the department's ServiceNow settings. To get the script again, open the **Connected** menu on the department's **ServiceNow** card, choose **Configure...**, and click **Save**.

3. **RISOTTO_API_URL**: Usually `https://api.tryrisotto.com` (only change for custom/on-premise instances)

### Business Rule Configuration

When creating the Business Rule in ServiceNow, configure these settings:

| Field                 | Value                                                               |
| --------------------- | ------------------------------------------------------------------- |
| **Name**              | `Risotto Incident Sync`                                             |
| **Table**             | `Incident [incident]`                                               |
| **Active**            | ☑️ Checked                                                          |
| **Advanced**          | ☑️ Checked                                                          |
| **When**              | `after`                                                             |
| **Insert**            | ☑️ Checked                                                          |
| **Update**            | ☑️ Checked                                                          |
| **Filter Conditions** | Comments `changes` OR Work notes `changes` OR Assigned to `changes` |

### Business Rule Script

Copy and paste this script into the **Script** field of your Business Rule, then update the three configuration values at the top:

```javascript
(function executeRule(current, previous) {
  // ==================================================
  // Risotto Webhook Integration for ServiceNow
  // ==================================================
  // This Business Rule sends incident data to Risotto
  // whenever an incident is created or updated.
  // ==================================================

  try {
    // Initialize REST Message
    var r = new sn_ws.RESTMessageV2();

    // ==================================================
    // CONFIGURATION - UPDATE THESE VALUES
    // ==================================================

    // 1. Replace with your Risotto organization ID
    var RISOTTO_ORG_ID = "YOUR_ORG_ID_HERE";

    // 2. Replace with your webhook secret from Risotto
    var WEBHOOK_SECRET = "YOUR_WEBHOOK_SECRET_HERE";

    // 3. Risotto API endpoint (usually no change needed)
    var RISOTTO_API_URL = "https://api.tryrisotto.com";

    // ==================================================
    // END CONFIGURATION
    // ==================================================

    // Construct webhook URL
    var webhookUrl =
      RISOTTO_API_URL + "/org/" + RISOTTO_ORG_ID + "/events/servicenow";

    r.setEndpoint(webhookUrl);
    r.setHttpMethod("POST");

    // Set required headers
    r.setRequestHeader("X-Webhook-Secret", WEBHOOK_SECRET);
    r.setRequestHeader("Content-Type", "application/json");

    // Build payload with incident data
    var payload = {
      record: {
        sys_id: current.getValue("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
        caller_id: current.caller_id
          ? {
              email: current.caller_id.email
                ? current.caller_id.email.toString()
                : null,
              name: current.caller_id.name
                ? current.caller_id.name.toString()
                : null
            }
          : null,
        // Include comments and work notes for syncing
        comments: current.comments ? current.comments.toString() : null,
        work_notes: current.work_notes ? current.work_notes.toString() : null
      }
    };

    // 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
      };
    }

    // Optional: Add assignment_group information
    if (current.assignment_group) {
      payload.record.assignment_group = {
        name: current.assignment_group.name
          ? current.assignment_group.name.toString()
          : null
      };
    }

    // Convert payload to JSON string
    r.setRequestBody(JSON.stringify(payload));

    // Execute the REST call
    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 incident " +
          current.getValue("number") +
          " (sys_id: " +
          current.getValue("sys_id") +
          ")"
      );
    } else {
      gs.warn(
        "Risotto webhook returned status " +
          httpStatus +
          " for incident " +
          current.getValue("number") +
          ". Response: " +
          responseBody
      );
    }
  } catch (ex) {
    gs.error(
      "Error sending webhook to Risotto for incident " +
        current.getValue("number") +
        ": " +
        ex.message
    );
  }
})(current, previous);
```

### Verifying the Setup

After saving the Business Rule:

1. Check ServiceNow System Logs (**System Logs > System Log > All**) for execution logs
2. Look for log entries:
   - ✅ **Info**: "Risotto webhook sent successfully..." (indicates success)
   - ⚠️ **Warning**: HTTP status codes 400+ indicate errors
   - ❌ **Error**: Script execution errors
3. Create a test incident and verify it appears in Risotto within a few seconds

> **Tip:** The Business Rule will trigger whenever an incident is created or updated,
> including when comments or work notes are added.

## Request Sources

Once a department syncs with ServiceNow, you can also turn incidents created in ServiceNow into Risotto tickets:

1. Go to **Settings > Request Sources** and click **Manage in ServiceNow**.
2. On the **Requests** tab, in the **ServiceNow assignment groups** section, click **Add Assignment Group**.
3. In the **Add ServiceNow Assignment Group** dialog, pick the **Department**. Only departments with ServiceNow ticket sync are listed.
4. Enter the **Assignment Group** name as ServiceNow shows it, or leave it blank to listen to all assignment groups.
5. Click **Add Request Source**.

*Product example: The Add ServiceNow Assignment Group dialog, with the IT department, the Service Desk assignment group, and Add Request Source.*

Each assignment group then has its own **Silent mode**, **Continue over DM**, and **Department** settings. See [Request Sources](https://www.tryrisotto.com/docs/dashboard/settings/request-sources#freshservice-and-servicenow).

## Troubleshooting

### Tickets not syncing from Risotto to ServiceNow

- Verify your ServiceNow instance URL is correct and includes `https://`
- Ensure the integration user has the required roles (`itil`, `rest_service`)
- Check that the username and password are entered correctly in Risotto
- Test the credentials by logging into ServiceNow with the same username/password
- Check network connectivity - ensure Risotto can reach your ServiceNow instance

### Incidents not syncing from ServiceNow to Risotto

- Verify the Business Rule is active and configured correctly
- Check ServiceNow System Logs for webhook execution logs
- Ensure the Business Rule triggers on Insert and Update operations
- Verify the `RISOTTO_ORG_ID` and `WEBHOOK_SECRET` are correctly configured in the script
- Test the webhook URL manually using ServiceNow's REST Message testing tool
- Check that the webhook URL is accessible from ServiceNow (not blocked by firewall)
- Review the filter conditions on the Business Rule

### Comments not syncing

- Ensure the Business Rule has the filter condition: `comments CHANGES OR work_notes CHANGES`
- Verify the Business Rule is set to trigger on Update operations
- Check that the `comments` and `work_notes` fields are included in the webhook payload
- Review ServiceNow System Logs for webhook execution when adding comments

### Webhook returns 401 error

- Verify the `WEBHOOK_SECRET` in the Business Rule matches the one in Risotto
- Check that the `X-Webhook-Secret` header is being sent correctly
- Copy the script again: on the department's **ServiceNow** card, open the **Connected** menu, choose **Configure...**, and click **Save**. Paste the new script into the Business Rule

### Webhook returns 404 error

- Verify the organization ID in the webhook URL is correct
- Check that the endpoint path is `/org/{org_id}/events/servicenow`
- Ensure the `RISOTTO_API_URL` is set correctly (default: `https://api.tryrisotto.com`)

### Status not mapping correctly

- Review the state mapping table above
- ServiceNow uses numeric state values (1-8); Risotto maps the standard incident states
- Custom state values may need custom handling

## Security Best Practices

- Create a dedicated integration user with minimum required permissions
- Use a strong password for the integration user
- Store the webhook secret securely - it acts as API authentication
- Regularly rotate the integration user password
- Monitor integration user activity in ServiceNow audit logs
- Use HTTPS for all API communications (default)
- Review ServiceNow System Logs regularly for unusual webhook activity

## ServiceNow API Details

The integration uses the ServiceNow Table API:

- **Endpoint**: `/api/now/table/incident`
- **Authentication**: Basic Auth (username/password)
- **Methods Used**:
  - `POST` - Create incident
  - `PUT` - Update incident (by sys_id)
  - `GET` - Retrieve incident
- **Response Format**: `{"result": {...}}` wrapper

Risotto automatically handles API authentication and request formatting.

Source: https://www.tryrisotto.com/docs/integrations/ticketing/servicenow
