- Subscribe to RSS Feed
- Mark as New
- Mark as Read
- Bookmark
- Subscribe
- Printer Friendly Page
- Report Inappropriate Content
Hello community, in this post I will be covering how to integrate Microsoft Dynamics with ServiceNow. In this integration we will set up automated task creation in ServiceNow when tasks are created in Dynamics. With this set up, many other automated unidirectional workflows can be created to sync Dynamics data with data in ServiceNow.
Requirements
- Microsoft Dynamics CRM Spoke installed
- a Windows laptop/pc or access to a Windows remote/virtual machine
Dynamics Account Creation
This step is optional if you already have a Microsoft administrator account with the @onmicrosoft.com suffix. If not, we'll be creating a free Microsoft Developer account in order to obtain a @onmicrosoft account.
First head over to the Microsoft Developer site and sign up for an account. Be sure to set up the account with the default settings, no need to go the custom route. Once taken to the dashboard, copy the Administrator email shown on your dashboard. We'll be using this to sign up for a free Dynamics Sales trial.
Sign up for Dynamics Trial
Head over to the Dynamics site and sign up for a free trial using the administrator account you obtained after signing up for the developer account. You'll be prompted to provide a phone number and required to download and set up a Microsoft Authenticator App. Make sure you use the admin@onmicrosoft along with a real phone number for these steps in order to be able to login to these accounts.
Set up Azure Portal
Next, we'll need to set up Azure to allow API access to our Microsoft applications. First, login to the Azure portal using your administrator account. When you're redirected to the dashboard, search for and select App registrations in the search bar at the top of the page.
When you come to this screen, click the Register an application button in the center to register a new application. Feel free to name the application anything you'd like. Under Support account types select the 3rd option - Accounts in any organizational directory. Next, under the Redirect URI select Web in the dropdown and add https://<YOUR-INSTANCE>.com/oauth_redirect.do as the redirect URL.
In order to have access to our dynamics app we'll need to open up API permissions. Under the Manage column on the left-hand side of the page select the API Permissions link. Under Configured permissions click the + Add a permission link. When the right-hand slider page opens select the Microsoft Graph tile. In the search bar, search for and check these permissions:
- User.ReadWrite.All
- Contacts.ReadWrite
- openid
- profile
- offline_access
- user_impersonation
At the bottom of the screen click the blue Add permissions button to add these permissions. We also need to add permissions for the Dynamics CRM. Click the + Add a permission link again and when the permissions page slider opens, select the Dynamics CRM tile, check the user_impersonation permission, and click the Add permissions button at the bottom.
Create Application Registry in ServiceNow
Our next course of action will be to create an Application Registry record to register Microsoft Dynamics as an OAuth provider. First, head to System OAuth > Application Registry. At the top right section of the page click New. When redirected to the next page select the Connect a third-party OAuth Provider option.
Now we'll need to fill out the record:
- Name: this can be anything you like, eg. "Dynamics CRM OAuth Provider"
- Client ID: this is the "Application (client) ID" found in the Azure portal for your application
- Client Secret: this is the client secret value that you saved earlier
- Default Grant type: set this to Authorization Code
- Authorization URL: copy the following URL and replace the bolded section in the URL with your dynamics application's URL (it should looks something like "org123abc"; https://login.microsoftonline.com/common/oauth2/authorize?resource=https://<YOUR-DYNAMICS-APP>.crm.dynamics.com
- Token URL: https://login.microsoftonline.com/common/oauth2/v2.0/token
- Redirect URL: https://<YOUR-SERVICENOW-INSTANCE>.service-now.com/oauth_redirect.do
Now save the record and remain on this page.
After the record has been saved select the OAuth Entity Scopes tab at the bottom of the record. Create a new record and fill both the name and OAuth scope fields with this url, again replacing the bolded section with your dynamics application url: https://<YOUR-DYNAMICS-APP>.crm.dynamics.com/user_impersonation
Create Credentials
Next we'll need to create credentials for the Dynamics Spoke. Head to All > Connections & Credentials > Credentials. At the top right of the screen click New to create a new credentials record.
- Name: Anything you like, eg. "Dynamics Credentials"
- Active: true
- OAuth Entity Profile: this is the application registry record you just created in the previous step
- Order: 100
After saving the record click the Get OAuth Token link underneath the Related Links section. You may get a popup that asks for you to sign into a Microsoft account. Make sure you sign in with the admin@onmicrosoft account that you used to sign up for the Dynamics free trial earlier*.
After you login (or if you were already logged in), the popup should disappear and you will see an error type message at the top of the record screen that says "OAuth Access token is available but will expire soon at xxxx-xx-xx xx:xx:xx. Verify the OAuth configuration and click the Get OAuth Token link below to request a new token." If you see this - excellent! You've successfully configured the Microsoft Dynamics Credentials in ServiceNow.
*Note: If you currently use Microsoft for work or you have another Microsoft account that is signed in, you may have to open a private browser or log out of the currently logged in account if it's not the admin@onmicrosoft account you've been using for this integration. If you're continuing to have issues, I'd highly recommend trying this step in a private browser - I've had trouble with multiple different Microsoft accounts being logged in and not being able to log into the right account in this step.
***This next portion deviates from the ServiceNow documentation for setting up the Microsoft Dynamics CRM Spoke. The purpose of this tutorial is strictly for DEMO purposes only and not a guide for implementation.
Create ServiceNow Webhook Endpoint
In order to receive and handle events that happen in Microsoft Dynamics, we'll need to create the endpoint in our ServiceNow instance for Dynamics to send the events to. There is already an existing endpoint that comes with the installation of the requisite plugins for this Dynamics integration. However, in this guide I will be creating my own endpoint in order to expedite the setup of this integration. Again, this is purely for demo purposes only, in a typical implementation following the ServiceNow documentation is of utmost importance to achieve the expected results.
Search for Scripted REST APIs in the filter navigator and click the relevant module. At the top right portion of the screen click the New button to create a new record. Fill out the name as something relevant, such as Custom Dynamics Webhook. Once you click out of the input, the API Service name will be auto-filled. Save the record.
While still on the record, at the bottom of the screen click the Resources tab and create a new resources record. This is where our logic will go to handle the Dynamics event. Fill out the record as shown below:
- Name: webhook
- HTTP method: POST
- Click the Security tab:
- Requires authentication: FALSE (unchecked)
- Script:
(function process( /*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) { // Log webhook received gs.info("Dynamics webhook received"); // extract the JSON body from the request var requestBody = request.body.data; // Check against the body to make sure it's a "Create" action from Dynamics if (requestBody["MessageName"] == "Create") { // Check against the body to make sure it's a "task" from Dynamics if (requestBody["PrimaryEntityName"] == "task") { // create an empty object to hold our "task" fields var taskFields = {}; // extract the array of different fields from the body var attributes = requestBody["InputParameters"][0]["value"]["Attributes"]; // loop over each field and add it to the taskField object attributes.forEach(function(attribute) { if (typeof attribute.value == "string") { taskFields[attribute.key] = attribute.value; } }); } } })(request, response);
Feel free to walk through the script above to understand what exactly it's doing. In short, we're extracting the information we need from the Dynamics Webhook payload so that we can then forward the info to a subflow to handle for processing.
We'll be adding more to this script later as we'll need to create that exact subflow part next. Save the record.
Create ServiceNow Webhook Subflow
Now that we're able to receive the webhook from Dynamics and have extracted the information, we need to do something with that information. I like creating subflows because they're easy to configure and easy to change if you need to update anything. Additionally, they're extremely powerful and can do almost anything you could do with code.
Head to All > Process Automation > Flow Designer. Click New at the top right portion of the screen and click Subflow.
Fill out the name as something relevant to what it's doing, in this case we'll be creating a new task so something like "Create Task from Dynamics Webhook" and leave the rest of the inputs as they are and click Submit.
Once in the Flow Designer editor, click the Subflow Inputs & Outputs link and add a new output named "Description". Once finished click Done.
Under the Actions header click the Add an Action, Flow Logic, or Subflow link, select Action and then search for "Create Task" and select that action.
Once the action is added, fill it out as shown below:
- Table: Task (sn_customerservice_task)
- Field Values
- Description: input>description (Under the "Subflow inputs" header on the right-hand side of the screen, click and drag the "description" bubble into the input to the right of the "Description" field.
Click Done.
Now click Publish at the top right portion of the screen.
Once published, click the ellipsis button (the 3 dots) and then click Create code snippet. A modal will appear with a code snippet that will execute this subflow. Copy everything between lines 3 and 18.
Next, navigate back to our Scripted Rest Resource we named "webhook" (this can be found in the Scripted REST API we named "Custom Dynamics Webhook" under the "Resources" tab) and paste the code you copied to the script field in this record at line 27.
We'll next need to make one edit which will be on line 31 where it shows: inputs["description"] = ;
We're going to add taskFields.description; after the "=" on line 31.
If you'd rather, feel free to copy the entire script below but make sure that you update line 34 with the name of your subflow where it says <INSERT-YOUR-SUBFLOW-ID>. You can find that on line 11 in the "Create code snippet" modal we popped open earlier while creating the subflow in Flow Designer.
(function process( /*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {
// Log webhook received
gs.info("Dynamics webhook received");
// extract the JSON body from the request
var requestBody = request.body.data;
// Check against the body to make sure it's a "Create" action from Dynamics
if (requestBody["MessageName"] == "Create") {
// Check against the body to make sure it's a "task" from Dynamics
if (requestBody["PrimaryEntityName"] == "task") {
// create an empty object to hold our "task" fields
var taskFields = {};
// extract the array of different fields from the body
var attributes = requestBody["InputParameters"][0]["value"]["Attributes"];
// loop over each field and add it to the taskField object
attributes.forEach(function(attribute) {
if (typeof attribute.value == "string") {
taskFields[attribute.key] = attribute.value;
}
});
// call subflow
try {
var inputs = {};
inputs['description'] = taskFields.description; // String
// Execute Synchronously: Run in foreground. Code snippet has access to outputs.
var result = sn_fd.FlowAPI.getRunner().subflow('<INSERT-YOUR-SUBFLOW-ID>').inForeground().withInputs(inputs).run();
var outputs = result.getOutputs();
// Current subflow has no outputs defined.
} catch (ex) {
var message = ex.getMessage();
gs.error(message);
}
}
}
})(request, response);
Download Windows Plugin Registration Tool
**Section headers colored green are to be done in your Windows machine (if not already in it) or in your virtual Windows machine.
In order to configure our Dynamics webhooks we'll need to download the Windows Plugin Registration (PRT) tool. I'll be honest, this step became rather involved when first walking through this integration. For whatever reason this tool was very difficult to find and download but the below step should work without issue. The difficult part will be locating it's installation folder, but we'll cover that in a bit.
To download the PRT we'll have to open up a PowerShell command line. To do that you can search for "powershell" in the Windows search bar and click "Run as administrator" when that result pops up.
Next, copy the below script (the entire thing), paste it into the PowerShell window, and then hit "Enter" on your keyboard. You'll see a bunch of things happening in the PowerShell window, all that's going on is the downloading and installation of the PRT.
$sourceNugetExe = "https://dist.nuget.org/win-x86-commandline/latest/nuget.exe"
$targetNugetExe = ".\nuget.exe"
Remove-Item .\Tools -Force -Recurse -ErrorAction Ignore
Invoke-WebRequest $sourceNugetExe -OutFile $targetNugetExe
Set-Alias nuget $targetNugetExe -Scope Global -Verbose
##
##Download Plugin Registration Tool
##
./nuget install Microsoft.CrmSdk.XrmTooling.PluginRegistrationTool -O .\Tools
md .\Tools\PluginRegistration
$prtFolder = Get-ChildItem ./Tools | Where-Object {$_.Name -match 'Microsoft.CrmSdk.XrmTooling.PluginRegistrationTool.'}
move .\Tools\$prtFolder\tools\*.* .\Tools\PluginRegistration
Remove-Item .\Tools\$prtFolder -Force -Recurse
##
##Download CoreTools
##
./nuget install Microsoft.CrmSdk.CoreTools -O .\Tools
md .\Tools\CoreTools
$coreToolsFolder = Get-ChildItem ./Tools | Where-Object {$_.Name -match 'Microsoft.CrmSdk.CoreTools.'}
move .\Tools\$coreToolsFolder\content\bin\coretools\*.* .\Tools\CoreTools
Remove-Item .\Tools\$coreToolsFolder -Force -Recurse
##
##Download Configuration Migration
##
./nuget install Microsoft.CrmSdk.XrmTooling.ConfigurationMigration.Wpf -O .\Tools
md .\Tools\ConfigurationMigration
$configMigFolder = Get-ChildItem ./Tools | Where-Object {$_.Name -match 'Microsoft.CrmSdk.XrmTooling.ConfigurationMigration.Wpf.'}
move .\Tools\$configMigFolder\tools\*.* .\Tools\ConfigurationMigration
Remove-Item .\Tools\$configMigFolder -Force -Recurse
##
##Download Package Deployer
##
./nuget install Microsoft.CrmSdk.XrmTooling.PackageDeployment.WPF -O .\Tools
md .\Tools\PackageDeployment
$pdFolder = Get-ChildItem ./Tools | Where-Object {$_.Name -match 'Microsoft.CrmSdk.XrmTooling.PackageDeployment.Wpf.'}
move .\Tools\$pdFolder\tools\*.* .\Tools\PackageDeployment
Remove-Item .\Tools\$pdFolder -Force -Recurse
##
##Download Package Deployer PowerShell module
##
./nuget install Microsoft.CrmSdk.XrmTooling.PackageDeployment.PowerShell -O .\Tools
$pdPoshFolder = Get-ChildItem ./Tools | Where-Object {$_.Name -match 'Microsoft.CrmSdk.XrmTooling.PackageDeployment.PowerShell.'}
move .\Tools\$pdPoshFolder\tools\*.* .\Tools\PackageDeployment.PowerShell
Remove-Item .\Tools\$pdPoshFolder -Force -Recurse
##
##Remove NuGet.exe
##
Remove-Item nuget.exe
Once the application is finished installing the PRT, we'll need to open it up and configure our Dynamics webhooks. Finding the PRT will be different for you but in my case I had to open a folder window and back out of each folder until I got to my User folder. In there was a folder called "Tools", with a folder called "PluginRegistration" inside that folder. Once you open the PluginRegistration folder there will be a file called "PluginRegistration.exe" with a green icon to the left of the name. Double-click that file and the PRT should open up.
When the PRT opens, we'll need to login using our admin@onmicrosoft credentials. First, check the "Display list of available organizations" box and click login. Next, punch in your admin email and password. You should get a popup that prompts you to sign into Microsoft and may also ask you to authenticate using Microsoft Authenticator.
Once signed in we can register a new webhook.
Configure Dynamics Webhooks
We're getting close! Now we need to configure Dynamics so that it knows where to send a webhook when events in Dynamics occur.
At the top of the screen in the PRT, click the "Register" button and select "Register New Web Hook".
Once the modal pops open, fill in the details:
- Name: ServiceNow (you can name it anything you like)
- Endpoint URL: https://<YOUR-INSTANCE>.service-now.com/api/<YOUR-WEBHOOK-ENDPOINT>
- Authentication: HttpHeader
In this case, we don't need to pass any properties in the box below the above-mentioned inputs. In a real-world scenario, this would be the spot to put something like a ClientID that you would then check in the ServiceNow webhook endpoint script we created earlier in order to validate the incoming Dynamics webhook. Since we're skipping that part in favor of simplicity's sake and because this is for demo purposes only, you can click save and we'll move onto the next step.
Now we need to define what will trigger this Dynamics webhook. In the left-hand column you'll see a list of other webhooks and activities that come default with the Dynamics instance. Find the webhook you just created and click to highlight it. Next, at the top click "Register" again, and then click "Register new step".
When the modal pops up, fill in the details as shown below:
- Message: Create
- Primary Entity: task
- Event Handler: (Webhook) ServiceNow (this should be filled in by default and have the webhook we just created, if isn't, use the dropdown for this field to find the webhook you created in the previous step)
For any fields I haven't mentioned you can leave them blank or if they're already pre-filled by default leave be. Once finished, click Register New Step at the bottom.
Test it all out!
We've just about done it. Now you'll need to go into your Dynamics instance and test out our flow. Once you're in Dynamics, on the top right corner of the page you should see a plus (+) button. Click that button and then select Activities, and select Task. This will open a new window where you can create a new Task, be sure to fill out the description as that was the only field we mapped to ServiceNow. Once the Task is created in Dynamics, head back into your ServiceNow instance and confirm that a new ServiceNow task has been created.
Congrats! You just integrated ServiceNow with Microsoft Dynamics!
- 7,951 Views
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.