Integrate Twilio Studio, Twilio Flex, and ServiceNow for Agent Interactions

August 17, 2021
Written by
Reviewed by

Integrate Twilio Studio, Twilio Flex, and ServiceNow for Agent Interactions

Twilio is a trusted provider in the telecommunications industry, helping customers navigate the complexities of the ever-changing communications ecosystem. We've heard a lot of feedback about the value of integrating ServiceNow and Twilio to manage incident notifications and escalations.

In other tutorials, we've shown steps you can take towards integrating ServiceNow with Twilio to add communications and incident updates. In this post, I'll go a step further and show you a full ServiceNow and Twilio integration which adds Twilio's Flex Contact Center and lets end-users transition to a live channel.

Follow along to learn to integrate Twilio Studio and Flex with ServiceNow for omnichannel, bi-directional messaging, real-time incident updates, and live agent escalation.


ServiceNow and Twilio integrations

This post is Twilio's recommended Run integration with ServiceNow. You can learn more about the ServiceNow use case on the Twilio website.

ServiceNow Crawl Walk Run Integrations with Twilio

If you only need ServiceNow-Managed 1-Way SMS, Voice, and Conferencing, you can follow our tutorial on how to create a notification system from ServiceNow using their Notify plugin – Crawl.

If you'd like to do contextual outbound notifications and update ServiceNow in real-time via SMS or Voice, but don’t need to integrate Twilio Flex, see our bi-directional incident management framework to integrate Twilio with ServiceNowWalk.


Prerequisites

Ensure you have the following accounts and tools set up, and that you’re logged into them, before you continue:

What's included?

  • 4 Functions - Mechanisms used to connect Twilio Studio and Twilio Flex plugins to ServiceNow: Get User, Add Comment, Create Ticket, Task Event
  • 2 Studio Flows - Sample studio flows for Voice and SMS.
  • 1 Flex Plugin - A sample plugin that presents customer information to the agent in Flex and raises events about the records being worked.
  • ServiceNow Code & Configuration -ServiceNow Studio offers scripted REST APIs, ServicePortal Pages, Navigation Modules, System Properties, and other useful features that you can use to quickly and easily package applications and deploy them straight from GitHub.

Configure the ServiceNow instance

First, we’re going to work through how to set up your ServiceNow instance so we can start integrating with Twilio. These steps will clone the ServiceNow Package, which contains the Flex iFrame and a number of Scripted REST API functions.

Create a new GitHub repository

Note: ServiceNow Studio Import used to allow for anonymous GitHub imports, but that is no longer an option.

We need a way to import and update our source code in a repository where we can authenticate ourselves.

  1. Login to your GitHub account.
  2. Navigate to your Repositories and click the New button.
  3. Call the new repository servicenow-studio-application (or really anything you like ... you just need the URL in the next step).
  4. Make it private (unless you want others to have access).
  5. Skip the Initialization check boxes.

A screenshot of the "Create a New Repository" page in GitHub

Once the repository has been created, copy the URL from your Internet browser's address bar. You'll use it to clone the repository locally, as shown in the next section.

Set up Git version control locally

Now that we've created an empty GitHub repository, let's use Git's mirror flag to clone an existing repository with the ServiceNow application we want to install.

Ensure that Git has been set up on your local machine and that you’ve successfully connected Git to GitHub. Copy the URL associated with your new GitHub repository from the GitHub Step above.

  1. Open a new terminal window.
  2. Execute the following commands in the terminal.

Note: It is best to do this without a VPN running to avoid conflicts with corporate git repositories. Additionally, attempting to cd into the git file may throw an error that says "fatal: this operation must be run in a work tree". This is expected behavior and can be safely ignored, but the step cannot be skipped.

git clone --mirror https://github.com/quickstark/servicenow-studio-application -b main
cd servicenow-studio-application.git 
git push --mirror <THE URL OF YOUR NEW REPOSITORY you created earlier>

You can now delete the cloned repository after pushing to your GitHub account by running the following command in your terminal window:

rm -rf servicenow-studio-application.git

Connect ServiceNow and GitHub

Login to your ServiceNow Instance. In the ServiceNow Navigator, search for Credentials and click the New button.

A screenshot of the Connections & Credentials navigation bar in the ServiceNow dashboard

On the next screen, select "Basic Auth Credentials".

A screenshot of the Credentials navigation bar in the ServiceNow dashboard

On the next screen, enter your GitHub credentials. (Note: Depending on your GitHub security settings such as 2FA, you may need to generate a single-use password.)

Import the code into ServiceNow Studio

Login to your ServiceNow Instance. Navigate to System Applications > Studio in the Application Navigator.

A screenshot of the System Applications navigation bar in the ServiceNow dashboard

Clicking Studio should automatically pop up the following Select Application screen. On this screen, click Import From Source Control.

A screenshot of the Select Application window in the ServiceNow dashboard

 

A screenshot of the Import Application window
  1. In the URL field, use the URL from the GitHub repository you created earlier.  It should be something like https://github.com/<your GitHub handle>/servicenow-studio-application. (The URL shown in the screenshot above is only for illustrative purposes.)
  2. Enter "main" in the Branch field. 
  3. Select the GitHub credentials you created in the prior step.
  4. Click the Import button. This should connect to your GitHub Repository and set up the ServiceNow side of the integration.
  5. You should now be able to Select Application.
  6. Close ServiceNow Studio, and refresh the ServiceNow home page to pull this code into the Application Navigator!

Because you imported the application code using GitHub, any changes you make to the Scripted APIs can be kept in sync with GitHub. This is very useful if you forget to refresh your ServiceNow instance and need to rebuild this integration or want to enhance it in the future.

Setup the ServiceNow Service Account

We need to create a Service Account to allow access to the Scripted REST APIs we imported into ServiceNow from Twilio Functions in the previous tutorials of this series. (We’ll set these Functions up later on.) If you already created a Service Account during Part 2 of this series, you may elect to use that instead. Just remember to adjust the username and other important metadata in the subsequent steps where this Service Account is used.

Create a Service Account

Navigate to User Administration > Users in the Application Navigator.

A screenshot of the User Administration navigation bar in the ServiceNow dashboard

Click the New button.

A screenshot of the User Administration navigation bar in the ServiceNow dashboard

Update the following fields with the values below:

  • User ID = twilio.flex
  • First Name = Twilio
  • Last Name = Flex
  • Password = <Any> (Remember this password! You will need to add it to your .env file in a later step.)
  • Web Service Access Only = Checked

Click Submit.

A screenshot of the New User Record window

 

Setup the ServiceNow Users

In addition to a Service Account, we also need to modify a couple of ServiceNow user accounts to successfully test our application end-to-end. For example, we need to modify the user accounts of the person logging the incidents and the agent who is responding.

The End User Account

  1. Navigate back to User Administration > Users in the ServiceNowApplication Navigator.
  2. Enter “bud in the Go to Name search box and press Enter. (“Bud” is the first name of a pre-loaded example user.)
  3. Select bud.richman to edit, then enter the following data, which will be passed to the agent:
    • Title = <Something Important Sounding>
    • Mobile Phone = Your cell number in E.164 format, such as +12145552222
  4. Click the Update button and close the user record.

A screenshot of the user selection window in the ServiceNow dashboard

 

The Agent User

  1. Enter admin in the User ID Search box and press Enter.
  2. Click into the admin record and update the following fields:

    • First Name = <Your First Name>
    • Last Name = <Your Last Name>
    • Email = <Your Email Address>
  3. Click Update.

A screenshot of the User Selection window in the ServiceNow dashboard
ServiceNow System Properties

 

Enter your Twilio Flex Runtime Environment name and click Save. Make sure you DO NOT include .twil.io.

ServiceNow Configuration

 

Configure the Twilio settings

Great work! You should now have the Twilio Flex package deployed in ServiceNow. In this section, we’ll walk through our setup on the Twilio side. By the end, you’ll have the ability to retrieve a ticket’s status, add ticket comments, create new tickets, and contact an agent — all via SMS and Voice.

Download the Code

  1. Navigate to https://github.com/quickstark/servicenow-twilio-functions.
  2. Download the ZIP file (green button labeled “Code”).
  3. This will download a zip file of everything you’ll need for the remaining steps.
  4. If the zip file doesn’t unzip automatically, unzip it into a logical place such as a designated git folder). Going forward, we will refer to this as your “deployment folder”.

The zip file you just downloaded contains a Twilio Serverless Package consisting of:

  • A Twilio Flex Plugin containing the hooks for Task Dispatch within Flex
  • The Twilio Functions needed to fetch, create, and update ServiceNow Tickets
  • The Twilio Studio Flows in JSON format (for importing later)

We are combining the Twilio Flex Plugin and Serverless Functions into one package. If you want more details about how to do this for other projects, check out the Streamline Your Flex Plugin & Functions Development Using VS Code tutorial on the Twilio blog.

Enable Flex CORS

Starting June 29th, 2021, all Flex applications created before March 3rd, 2021 are required to register their valid URLs under Twilio Flex's Allowed URLs list in order to embed Flex as an iframe. Read more in our documentation, Securely embed Flex as an iframe.

  1. Navigate to Flex Settings.
  2. Scroll to the bottom of the page.
  3. In the section titled Embed Flex as an iframe, add your ServiceNow Instance URL (it will be in the form https://devXXXXX.service-now.com).
  4. Click the Save button.

Create the Twilio Serverless .env File

In a conventional Twilio Serverless Project Initialization, the Twilio CLI would create a .env file for us, but because we normally exempt .env from GitHub (via a .gitignore file) we’ll need to create one.

  1. Navigate to the default folder inside the deployment folder.
  2. Duplicate the .env.example file using VSCode or your IDE/Text editor of choice.
  3. Rename the duplicated .env.example file to .env.
  4. Inside that .env file, add the Twilio and ServiceNow attributes shown below. You can find your Twilio Account SID and Auth Token in the Twilio Console.
  • ACCOUNT_SID=<Twilio Flex Project Account SID>
  • AUTH_TOKEN=<Twilio Flex Project Auth Token>
  • SERVICE_NOW_API_ROOT=https://devXXXXX.service-now.com/api/x_8725_servicenow/twilio_flex/ (Replace XXXXX in the SERVICE_NOW_API_ROOT with the 5-6 digit id from your own ServiceNow instance. You should see this in the URL bar.)
  • SERVICE_NOW_USERNAME=twilio.flex
  • SERVICE_NOW_PASSWORD=<ServiceNow Service Account Password>

Note: Twilio will inject the Account SID and Auth Token into the Function’s Context during runtime, but for local testing and consistency with the twilio serverless:init command, we’ll add the Account SID and Auth Token to the file.

Deploy the Twilio Serverless Functions

Navigate into the default folder within the deployment folder. Run the following command to deploy the Twilio Serverless Functions:

twilio serverless:deploy --service-name=default --override-existing-project

The combination of the --service-name=default flag and the --override-existing-project flag allows you to deploy your functions to the existing service container. A new Environment will be created consistent with the process outlined here, and your functions and assets will be deployed in association with that Environment.

The output of running the deploy command should provide details about the service. Copy the value for the domain as we’ll need this in the next step.

A screenshot of the CLI window

Modify the Flex Plugin env.dev File

We also need to modify an .env file for the Flex Plugin to host the BASE URL for our Serverless Functions.

If you forgot to copy the domain from the prior step, you can find the path of the Serverless Functions you deployed by visiting Functions in the Twilio Console, clicking “default”, and looking for the Serverless Path (in this example, “default-5501-dev.twil.io”)

A screenshot of the Serverless functions selection tool in the Twilio Console

To modify or create the Flex .env file:

  1. Navigate to the root of your deployment directory. (If you are still within the default folder, go up one level using the command cd ..)
  2. You should see a .env.dev file there already. If you don't have one, create one.
  3. Open .env.dev and modify the value of the SERVERLESS_BASE variable to your Serverless Package URL. If you created an empty .env.dev file, add SERVERLESS_BASE=<Your Serverless URL>.
  4. For this example, the file would have a single line reading: SERVERLESS_BASE=https://default-5501-dev.twil.io.

Deploy the Flex Plugin

Deploying the Flex plugin requires a different set of commands than deploying Twilio Serverless Functions, as you’ll see below. We’ll release our plugin via the CLI, but you can also manage releases in the Plugins section within Flex if you prefer.

Navigate to the root of the deployment folder. Ensure you are using the correct Twilio environment. You can check by running the following CLI commands:  

twilio profiles:list
twilio profiles:use <profile>

Ensure the dependencies are installed. To do this, run:

npm install

Run the following command:

twilio flex:plugins:deploy --changelog "ServiceNow Init" --description "ServiceNow Flex Plugin"

Or, if the CLI isn’t acknowledging your profile, you can explicitly specify it by running the following command:

twilio flex:plugins:deploy --changelog "ServiceNow Init" --description "ServiceNow Flex Plugin" -p <profile>

A screenshot of the Twilio CLI

The deploy step should result in an output command for releasing the plugin. It will automatically track your release version with every subsequent deployment. Copy the output of the command and modify the description.

twilio flex:plugins:release --plugin ServiceNowPlugin@0.0.1 --name "Sample Release 1625589503337" --description "Test Release"

Deploy Studio Flows

In this section, you will import, update, and publish 2 Studio flows. The updates involve pointing the Flow’s Function Widgets to the Twilio Serverless Functions we deployed above.  

Import the Voice Flow

Navigate to the Twilio Studio Dashboard. Click + to create a new Studio Flow, then name the flow ServiceNow Voice (or whatever name you prefer), and click Next.

A screenshot of the New Flow window

Scroll to the bottom of the next pop-up and select the Import from JSON template, then click Next.

A screenshot of the Import From JSON window

Open <deployment_folder>/studio_flows, and open the voiceflow.json file in your favorite code editor.  Copy the contents of the file, and replace the contents of the textarea.

A screenshot of the New Flow JSON definition

 

Once imported, we will need to make a few modifications to connect certain widgets to the unique resources in your environment. Locate the 4 Functions Widgets in the imported Studio Flow. (See the example images below for the GetUserFromPhone Function Widget.)

A diagram of the workflow

 

A screenshot of the Run Function configuration window

Update the widgets with the following information:

  • The GetUserFromPhone widget needs to point to the /get_user function
  • The AddCommentToTicket widget needs to point to the /add_comment function
  • The NewTicketCreate widget needs to point to the /new_ticket function
  • The SendCallToAgent widget should have:
  • Workflow = Assign to Anyone
  • Channel = Voice

Click Save after making all changes to the 4 widgets listed above, then click Publish at the top of the screen.

Import the Messaging Flow

  1. Navigate to the Studio Dashboard.
  2. Click + to create a new Studio Flow, then name the flow ServiceNow Messaging (or whatever name you prefer) and click Next.
  3. Repeat the steps from the “Import the Voice Flow” section above, except this time select the <deployment_folder>/studio_flows, and open the messagingflow.json file.

The same functions need to be updated as in the Voice Flow:

  • The GetUserFromPhone widget needs to point to the /get_user function
  • The AddCommentToTicket widget needs to point to the /add_comment function
  • The NewTicketCreate widget needs to point to the /new_ticket function
  • The SendMessageToAgent widget should have:
  • Workflow = Assign to Anyone
  • Channel = SMS

Click Save after making all changes to the 4 widgets listed above, then click Publish at the top of the screen.

Update pointers to Studio

Finally, we need to make a few updates to ensure your Twilio Phone number is pointing to these new Flows.

Point to Voice Flow

  • Navigate to the Active Numbers page in the Twilio Console.
  • Click the phone number that came with your Flex Project. It should be labeled Flex Phone Number.
  • Update the A Call Comes In option to point to your new ServiceNow Voice Flow.

Point to Messaging Flow

  • Navigate to the Messaging page in the Twilio Console.
  • In the Incoming Message Handlers section, update the line with Channel = sms to point to the ServiceNow Messaging Flow you created in the prior step. This page will automatically save when you change the value.

Testing

Great work! You now have Twilio and ServiceNow integrated, and you’re ready to check that everything is working well together.

Once logged into ServiceNow, navigate to Service Desk > Twilio Flex Workspace in the Application Navigator.  This will load Flex embedded in the Service Portal.

A screenshot of the Twilio Flex UI within the ServiceNow dashboard

Click the Login with Twilio link, and you should be logged in automatically.

A screenshot of the Twilio Flex UI within the ServiceNow dashboard

Change your status to Available.

A screenshot of the Twilio Flex UI within the ServiceNow dashboard

Call or text the number you got with your Twilio account (you can find that here) and once you reach a path which speaks to an agent, you should see the call or message pop up in Flex.

A screenshot of the Twilio Flex UI within the ServiceNow dashboard

Once you accept the task by clicking the green check mark (✅) the appropriate ticket record should pop open on the right!

A screenshot of the Twilio Flex UI within the ServiceNow dashboard showing a new incident

 

Troubleshooting

  • If you have issues with the Integration returning 500 errors from ServiceNow, this is often an indication that your ServiceNow Development instance is hibernating. Please login to the ServiceNow Developer Console and wake up your instance.  An example error message would be: Unexpected token < in JSON at position 0 in "https://dev85449.service-now.com/api/x_8725_servicenow/twilio_flex/find_user_phone"
  • If your mobile number isn’t found or if you have it provisioned more than once, the error control logic should notify you of either scenario. If you still aren’t receiving an initial “menu” this may be an indicator you have a stuck Task. Please go to Flex in the Twilio console and run a System Check.
  • ServiceNow seems to have a knack for triggering password managers. When editing users, it may inadvertently fill your ServiceNow Developer credentials into user fields which can cause the integration to break. If this happens you’ll usually be unable to save the user record.

That’s It!

You now have an MVP agent-enabled ServiceNow integration and you even learned about a few useful tools to aid in your future integration pursuits. As Chris Feehan, Principal Solutions Engineer at Twilio, mentioned in Streamline Your Flex Plugin & Functions Development Using VS Code, now the work begins to improve on this integration so that it works for you and your business.

Hopefully, this tutorial has demystified the ways you can approach integrating Twilio and ServiceNow. I can't wait to see what you build!

Dirk Nielsen is a Solutions Architect at Twilio who spends time working in Javascript/React, Python and entirely too much time Photoshopping cats. You can find Dirk at dnielsen [at] twilio.com.