Webhook Event Receiver with Azure Functions

Microsoft Azure Functions is a solution to run small pieces of code in the cloud. If your code is very small and have only one purpose, an Azure Function could be the cost effective solution.

This is an example of a generic Webhook event receiver. A webhook is a way for other systems to make a callback to your system whenever an event is raised in the other system. This Webhook event receiver will simply receive the Webhook event’s payload (payload = the JSON that the other system is POST’ing to you), envelope the payload and write it to a Queue.

STEP 1: SET UP AN AZURE FUNCTION

Select an Function App and create a new function:

Create New Azure Function

Create New Azure Function

 

STEP 2: CREATE A NEW FUNCTION

Select New Function and from the “API & Webhooks”, select “Generic Webhook – C#:

Create Generic Webhook

Create Generic Webhook

Microsoft will now create a Webhook event receiver boilerplate code file, which we will modify slightly later.

STEP 3: ADD A ROUTE TEMPLATE

Because we would like to have more than one URL to our Azure Function (each webhook caller should have it’s own URL so we can differentiate between them) we need to add a route template.

Select the “Integrate” section and modify the “Route template”. Add {caller} to the field:

Add a Route Template

Add a Route Template

STEP 4: INTEGRATE WITH AZURE QUEUE STORAGE

We need to be able to write to an Azure Queue. In Azure Functions, the integration is almost out of the box.

Select the “Integrate” section and under “Outputs”, click “New Output”, and select the “Azure Queue Storage”:

Azure Queue Storage

Azure Queue Storage

Configure the Azure Queue Settings:

Azure Queue Settings

Azure Queue Settings

  • Message parameter name: The Azure Function knows about the queue through a parameter to the function. This is the name of the parameter.
  • Storage account connection: The connection string to the storage where the azure queue is located.
  • Queue name: Name of queue. If the queue does not exist (it does not exist by default) a queue will be created for you.

STEP 5: MODIFY THE BOILERPLATE CODE

We need to make small but simple modifications to the boilerplate code (I have marked the changes form the boilerplate code with comments):

#r "Newtonsoft.Json"

using System;
using System.Net;
using Newtonsoft.Json;

// The string caller was added to the function parameters to get the caller from the URL.
// The ICollector<string> outQueue was added to the function parameters to get access to the output queue.
public static async Task<object> Run(HttpRequestMessage req, string caller, ICollector<string> outQueue, TraceWriter log)
{
    log.Info($"Webhook was triggered!");

    // The JSON payload is found in the request
    string jsonContent = await req.Content.ReadAsStringAsync();
    dynamic data = JsonConvert.DeserializeObject(jsonContent);

    // Create a dynamic JSON output, enveloping the payload with 
	// The caller, a timestamp, and the payload itself
    dynamic outData = new Newtonsoft.Json.Linq.JObject();
    outData.caller = caller;
    outData.timeStamp = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
    outData.payload = data;
    
	// Add the JSON as a string to the output queue
    outQueue.Add(JsonConvert.SerializeObject(outData));     
    
	// Return status 200 OK to the calling system.
    return req.CreateResponse(HttpStatusCode.OK, new
    {
        caller = $"{caller}",
        status = "OK"
    });
}

STEP 6: TEST IT

Azure Functions have a built in tester. Run a test to ensure that you have pasted the correct code and written the correct names in the “Integrate” fields:

Test

Test

Use the Microsoft Azure Storage Explorer to check that the event was written to the queue:

Azure Storage Explorer

Azure Storage Explorer

STEP 7: CREATE KEYS FOR THE WEBHOOK EVENT SENDERS

Azure Functions are not available unless you know the URL and the key. Select “Manage” and add a new Function Key.

Function Keys

Function Keys

The difference between Function Keys and Host Keys are that Function Keys are specific to that function, but the Host Keys are global keys that can be used for any function.

To call your Azure Function, the caller need to know the URL + the key. The key can be send in more than one way:

  • Using the URL, parameter ?code=(key value) and &clientid=(key name)
  • In the request header, using the x-functions-key HTTP header.

STEP 8: GIVE URL AND KEY TO CALLING SYSTEM

This is a Restlet Client example that calls my function. I use the QueryString to add the code and clientid parameters:

MORE TO READ:

 

Advertisements

About briancaos

Developer at Pentia A/S since 2003. Have developed Web Applications using Sitecore Since Sitecore 4.1.
This entry was posted in .net, c#, General .NET, Microsoft Azure and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s