Implementing Lead Landing Page with Flow (in 10 min. or less)

Microsoft Flow, along with Logic Apps, Power Apps and CDS has revolutionized integration with Microsoft Dynamics 365.
I have been working with Dynamics products since 2005 and when comparing the resources required back then to hook up a landing page to Dynamics, I estimate that modern solutions require less than 5%.
In addition, you don’t have to be an expert developer to implement simple integration scenarios, as declarative mechanisms like Flow and Logic Apps can handle the heavy lifting.    

In this post I’ll walkthrough the process of Implementing a Lead Landing Page with Flow while writing the minimum amount of required code.

The ingredients:

  1. Microsoft Flow Handle Landing Page Lead triggered by HTTP request, creating a Lead record in Microsoft Dynamics 365 instance using Flow built in Dynamics Create Record Action.
  2. HTML page implementing landing page UI along with JavaScript code sending Lead data to the Handle Landing Page Lead Flow.

Prerequisites:

  1. Have access to Microsoft Dynamics 365 online instance and Flow environment residing in the same tenant

Walkthrough:

  1. Create a ‘Handle Landing Page Lead’ Flow 

    Start a Flow from scratch and create a Request trigger. Once saved,  the URL value will be filled automatically.

    Start a Flow from scratch and create a Request trigger. Once saved,  the URL value will be filled automatically.

    Next, add a Parse JSON action and paste in the following schema

    {
        “type”: “object”,
        “properties”: {
             “topic”: {
                “type”: “string”
              },
              “firstName”: {
                 “type”: “string”
              },
              “lastName”: {
                 “type”: “string”
              },
              “email”: {
                 “type”: “string”
              },
              “mobilePhone”: {
                 “type”: “string”
              }
         }
    }

    Next, add a Parse JSON action and paste in the following schema

    Next, add Dynamics Create Record action. Select your target Dynamics 365 instance and map to the Lead entity.
    Map the previous Parse JSON action output values as Lead attributes.

    Next, add Dynamics Create Record action

    Finally, add a parallel branch element. Add two HTTP Response actions, one handling Lead creation success and the other for failure.
    Both returning code 200, each returning the respective message in the response body.
    Click each response ellipsis and set the ‘Configure run after’ option to handle the
    previous step success and failure respectively. 
    Finally, save the Flow.

    Finally, add a parallel branch element

    Click each response ellipsis and set the ‘Configure run after’ option to handle the

  2. Create HTML Landing page

    Create the following HTML page. Replace the flowRequestURL variable value with Flow Request Action URL generated in the first step.

    <html>
    <head>
        <meta charset="utf-8" />
        <title>Implementing Lead Landing Page with Flow</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    </head>
    <body style="font-family:'Segoe UI';background-color:lightskyblue">
            <b>Contact us</b>
            <table>
                <tr>
                    <td><label>Topic</label></td>
                    <td><input type="text" id="topic" name="topic" placeholder="insert topic"></td>
                </tr>
                <tr>
                    <td><label>First Name</label></td>
                    <td><input type="text" id="firstName" name="firstName" placeholder="insert first name"></td>
                </tr>
                <tr>
                    <td><label>Last Name</label></td>
                    <td><input type="text" id="lastName" name="lastName" placeholder="insert last name"></td>
                </tr>
                <tr>
                    <td><label>Email Address</label></td>
                    <td><input type="text" id="email" name="email" placeholder="insert email address"></td>
                </tr>
                <tr>
                    <td><label>Mobile Phone</label></td>
                    <td><input type="text" id="mobilePhone" name="mobilePhone" placeholder="insert mobile phone number"></td>
                </tr>
                <tr>
                    <td colspan="2">
                        <input value="Send" type="button" onclick="sendRequest()">
                    </td>
                </tr>
            </table>    
        <br />
        <div id="messageArea"></div>
    
        <script type="text/javascript">
    
            // Send new Lead request to Microsoft Flow
            sendRequest = function () {
    
                //set Flow request URL - available once Flow Request step is saved 
                var flowRequestURL = "https://FLOWREQUESTURL";
    
                //set Lead object
                var leadData = {
                    topic: $("#topic").val(),
                    firstName: $("#firstName").val(),
                    lastName: $("#lastName").val(),
                    email: $("#email").val(),
                    mobilePhone: $("#mobilePhone").val()                
                };
    
                //send request
                var req = new XMLHttpRequest();
                req.open("POST", flowRequestURL, true);
                req.setRequestHeader("Accept", "application/json");
                req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
                req.onreadystatechange = function () {
                    if (this.readyState == 4) {
                        req.onreadystatechange = null;
                        //handle success
                        if (this.status == 200) {
                            $("#messageArea").text(this.response);
                        }
                        //handle failure
                        else {
                            $("#messageArea").text(this.response);
                        }
                    }
                }
                //send request
                req.send(window.JSON.stringify(leadData));
            }
        </script>
    </body>
    </html>
    

Test your landing page by submitting a new Lead. If all works as expected, it will be instantly created in your Dynamics 365 instance.

Test your landing page by submitting a new Lead

If all works as expected, it will be instantly created in your Dynamics 365 instance.

Auto Backup Dynamics 365 Solution using Flow & Dropbox

Harnessing the scaffold suggested in my last post, I would like to suggest a simple way to automatically backup Dynamics 365 solution with Flow/Logic Apps.

The following Flow will allow you to copy Dynamics 365 solution file into Dropbox account on schedule for backup or any other purpose.

You can download the scaffold Flow solution here and import into your Flow environment. Then, update the necessary details according to the following walkthrough. The last Dropbox related Action is not included, you’ll add it yourself.


Prerequisites

  1. Access to Microsoft Dynamics 365 online instance and Flow environment
  2. Register Microsoft Dynamics 365 online instance in Azure AD and have the Application Id key ready.Make sure you set the oauth2AllowImplicitFlow as described here.
  3. Have an accessible Dropbox account.

Walkthrough

Here is the full Flow collapsed Flow:

full Flow collapsed Flow

  1. Download the scaffold Flow solution here and import into your Flow environment
  2. Edit the imported Flow and set the following variables with values to match your environment:
    1. Client id & Dynamics 365 instance URL

      Client id & Dynamics 365 instance URL

    2. Set Dynamics 365 instance user name and password

      Set Dynamics 365 instance user name and password

    3. Set the target Dynamics 365 solution unique name and state the Dropbox target folder name (where the solution file will be created).
      Set false is the target solution is unmanaged, true otherwise

      Set the target Dynamics 365 solution unique name and Dropbox target folder where the solution file will be created.

    4. Add the Dropbox ‘Create File’ Action after the Parse JSON Action:
      Authenticate to your Dropbox account to allow creating the solution File in the target folder

      Authenticate to your Dropbox account to allow creating the solution File in the target folder

Once the Flow is activated, the target solution file will be created on schedule in the target Dropbox folder

Once the Flow is activated, the target solution file will be created on schedule in the target folder

Executing Web API Calls from Flow/Logic Apps

While writing my previous post regarding Flow as a scheduling mechanism,  I stumbled across this post demonstrating how to execute Web API calls from Flow.

Why would you want to execute Web API calls from Flow/Logic Apps?
While Microsoft Flow/Logic Apps support basic Dynamics 365 operations, there are many missing functions that can simplify common integration scenarios between these platforms: executing Custom Actions, triggering Processes, handling metadata and issuing complex queries.
Some of these problems can be worked around using the Command Pattern, but using the Web API from within Flow/Logic Apps provides a simple and powerful integration mechanism.  

In this post, I’ll demonstrate how to authenticate and execute Web API functions and actions from Flow (a similar process can be used with Logic Apps):

  • Execute a FetchXML query
  • Execute a Custom Action

The requirement used to demonstrate is again the automated weekly evaluation of Leads: once a week, any Lead which is older than 5 days and not rated hot is disqualified.
With this implementation approach, Flow is used for scheduling, query for target business records and applying a Dynamics 365 Custom Action to each business record. 

Prerequisite

  1. Have access to Microsoft Dynamics 365 online instance and Flow environment
  2. Register Microsoft Dynamics 365 online instance in Azure AD and have the Application Id key ready.
    Make sure you set the oauth2AllowImplicitFlow as described here.

Walkthrough

  1. Download and import Solutions

    Download and import this Flow solution into your Flow workspace.

    image

    image

    image

    Download, import and publish this unmanaged solution into your Dynamics 365 instance. It contains one Custom Action that will be executed from Flow using Web API. 

  2. Set Flow Settings

    Edit the newly imported Flow

    image

    Set the following keys with values to match your environment

    image

    image

    image

  3. Note the following settings

    This variable holds FetchXML query to retrieve the target Lead records.

    This variable holds FetchXML query to retrieve the target Lead records.

    This variable holds the target entity name as it is used with Web API

    This variable holds the target entity name as it is used with Web API

    This variable holds the target Custom Action to handle each Lead.
    Note that for unbound Custom Action, the Microsoft.Dynamics.CRM should be removed.

    This variable holds the target Custom Action to handle each Lead

    This action requests a token used to authenticate to Web API

    This action requests a token used to authenticate to Web API

    This action executes the FetchXML query

    This action executes the FetchXML query
    This action parses the query resulting records.
    If you change the FetchXML query to support a different entity or attributes, make sure you also change the JSON schema to support it

    This action parses the query result

    This action executes the target Custom Action for each Lead record returned by the query

    This action executes the Custom Action for each Lead record returned by the query

  4. Test your Flow

    After a successful run, Flow will display the number of affected records.
    In Dynamics 365, these records should appear as disabled now.

    image

    If your Flow fails on the RequestOAuth2Token action, try this solution

Implementation Notes 

  • I prefer authenticating using an Application Id and Secret via an App user rather than plain user credentials. 

Execute a Recurring Job in Microsoft Dynamics 365 with Flow

I have written about executing recurring jobs in Dynamics 365 few times in the past. Over time, I suggested different scheduling mechanisms such as Microsoft Dynamics Workflow Timeout step or Azure Scheduler, as the pattern I suggested allows changing the scheduling mechanism without impacting other solution parts.

Asynchronous Batch Process Pattern

Flow can be also used as a scheduling mechanism, one that does not require coding like Azure Function,  as it has a built in integration with Microsoft Dynamics 365 Online.
Once invoked on schedule, the executing component query Dynamics 365 for target business records and apply some business logic (Process) to each business record.

In this post I would like to demonstrate a solution for executing a recurring job in Microsoft Dynamics 365 using Flow as the scheduling component.

Sample business requirement

Weekly Leads Evaluation: once a week, disqualify all Leads that are more than 5 days old and are not rated ‘Hot’.
Add a note to each Lead record to indicate that it was disqualified by an automated process.

Walkthrough

  1. Download, Import and publish the ABP unmanaged solution.
  2. Create the Action component: Disqualify Lead Workflow

    This Workflow Rule will be applied to each valid target business record. It simply attaches a Note and changes the Lead record state to Disqualified. It can be a/synchronous, but you may want to start with a asynchronous execution to monitor the process execution.
    Make sure you define the process as an on-demand process with no automated triggers.

    Create the Action component: Disqualify Lead Workflow

  3. Define Target Business Records Query

    Using the Advanced Find, define a new query to retrieve all Lead records where Created On date is older than 5 days and are not rated ‘Hot’.
    Click to Edit Columns button and remove all possible columns to maximize the query efficiency.
    Click the Download Fetch XML button and open the resulting file with some text editor. Copy the FetchXML query text to the clipboard

    Define Target Business Records Query

  4. Create a Batch Process Record

    This record is used to orchestrate by holding a FetchXML query to define the target business records and also the Action process which will be applied on the the target business records.
    If you imported an unmanaged solution, find the Batch Process entity and set it to appear in the Settings area.
    Create a Batch Process record and paste the FetchXML query text into the Target Records textbox.
    Name the record ‘Weekly Leads Evaluation Process’.
    Select the Disqualify Lead Workflow (created in step 2) in the Process Lookup field and save the record.
    Copy the Reference Token value for the next step.

    Create a Batch Process Record

  5. Define Flow Rule

    In your tenant, navigate to the Flow area and create an empty Flow named Weekly Leads Evaluation.
    Define a Recurrence Trigger to trigger the batch process

    Define a Recurrence Trigger to trigger the batch processDefine a Recurrence Trigger to trigger the batch process

    Next, define a List records action.
    In the Filter Query text box, paste the Batch Process Reference Token value and precede it with dyn_referencetoken eq (e.g. dyn_referencetoken eq ‘LOGY8Y1W6’).

    Next, define a List records action

    Define Update record action which will automatically wrap it with Apply to each wrapper. Add a Condition before the Update Action to verify that the Flow operates only if the Batch Process record status is Scheduled. 

    Define Update record action which will automatically wrap it with Apply to each wrapper

  6. Activate

    Change the Batch Process record status to Scheduled and save.
    Activate the Flow Rule.
    You can monitor the Flow activation by navigating to the Run History area.

    You can monitor the Flow activation by navigating to the Run History area

    For each run, you can see the completion status (success/failure) and failure reason

    For each run, you can see completion status (success/failure) and failure reason

Similarly, you can now add additional scheduled batch processes. 

Implementation Details

Microsoft Dynamics 365 – Send SMS using Flow

Looking at the list of traditional CRM activities I always miss the SMS, being a common and effective type of communication between organizations and customers.

Sending SMS triggered by Microsoft Dynamics 365 events (e.g. Case created) used to be a developer’s task. You had to write Plugin or Custom Workflow Activity code to access the SMS provider web service and maintain it as endpoints sometime change.

With Flow you can integrate applications in a declarative manner so an event in one application will trigger an action in another application along with custom conditional logic and even wait capabilities (similar to Dynamics 365 internal Workflow Wait step). 

In this post, I’ll walkthrough the process of setting up SMS sending without coding using Flow and Twilio (SMS provider).

  1. Prerequisites

    Before advancing make sure you have the following:

    a. Microsoft Dynamics 365 instance (trial will do)
    b. Twilio account (trial will do – click +sign up in Twilio home page)

  2. Setting up Twilio account

    a. In your Twilio Account console, click ‘Get a number’ button under the build menu

    Setting up Twilio account

    b. In the dialog, choose the suggested number or select a different one.
    c. Go to the Home tab and note the Account SID and Auth Token keys, you will need these later

    Setting up Twilio account

  3. Setting up Flow

    a. Login to your Office 365 environment and click the Flow tile

    Setting up Flow 

    b. In My Flows tab click the ‘+ Create from blank’

    image

    c. In the search box, type in Dynamics and from the results list select the ‘Dynamics 365 – When a record is created’ trigger 

    Setting up Flow

    d. In the Organization Name select the name of your Dynamics 365 instance. In the entity name dropdown select the entity for which the Flow will listen

    Setting up Flow

    e. Click the ‘New Step’ button and then ‘Add an action’

    Setting up Flow

    f. Search and Select the Twilio – Send Text Message (SMS) action

    Setting up Flow

    g. Feed in a name for your Twilio account (for future Flows) and keys from your Twilio Home tab: Account SID goes into the Account ID box, Auth token goes to the Access Token box

    Setting up Flow

    h. Feed in the your Twilio assigned Phone number in the From Phone Number box. Feed the target phone number in the To phone number. Feed in the SMS text. Note you can map dynamic data from the Case record into the text or target phone number

    Setting up Flow

    i. Click ‘Create Flow’ and then ‘Done’ 
     

  4. Testing & Monitoring
    a. In your Dynamics 365 create a new Case.
    b. After a few seconds, you should get a SMS message

    After a few seconds, you should get a SMS message

    c. In Flow management console Click ‘Manage’
    Testing & Monitoring 

    d. You can view your Flow, edit and deactivate it here. Clicking the i will show you the Flow instances details and running results 
     
    Testing & Monitoring

 

Implementation Notes

  1. It may take Flow some time to kick in. If you didn’t get an SMS message after creating the first Case, create another
  2. Twilio trial account will grant you a limited amount of SMS messages and each message will starts with ‘Sent from a Twilio Trial account’
  3. Twilio supports sending messages in these countries