6 minute read
Overview
Don’t you hate it when the documentation you’re looking for doesn’t exist? So do we. That’s why our MINDs bit the bullet and created instructions to make your life easier:
If you’ve tried to build a custom Webhook in .NET, you‘ve probably noticed the lack of tutorials explaining the process. We had a client who wanted a real-time sync between their CRM and their Emma mailing platform. We didn’t want to query the Emma API on a regular basis checking for updates. It was more efficient for all parties involved to leverage Emma Webhooks to notify our system immediately when a change occurred. The out-of-the-box options in .NET support services for Github, Azure and others, but if the API you’re searching for isn’t offered, it’s hard to find documentation. The following tutorial is intended to fill in the Emma gap.
Required Skills
This tutorial assumes familiarity with Visual Studio and REST-based API calls. It was originally adapted from this post and tweaked to incorporate Postman and Emma. The solution below is only for receiving API calls from JSON requests.
Required Software
- Visual Studio
- Postman
- Azure Subscription
- Emma Subscription
Project Setup
Begin by creating a blank Web API project in Visual Studio.
Add the following line to your WebApiConfig class to allow JSON requests.
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// Initialize Generic JSON WebHook receiver
config.InitializeReceiveGenericJsonWebHooks();
}
}
Install the following NuGet package using the package manager console to obtain the necessary Webhook classes:
Install-Package Microsoft.AspNet.WebHooks.Receivers.
Add the following line of code to aid in routing in the App.config. The keys below can be anything you want, but must be 32 characters.
<configuration>
<appSettings>
<add key="MS_WebHookReceiverSecret_GenericJson" value="i=1388a6b0d05eca2237f10e4a4641260b0a08f3a5,z=80ad19e357b01a04fe767067df7cd31b96a844e1" />
</appSettings>
<system.web>
Create a new class to host your handler code (entry point) and name it whatever you want. The WebHookHandler base class is required to receive Webhook requests.
Paste in this template code:
using Microsoft.AspNet.WebHooks;
using Newtonsoft.Json.Linq;
using System.Threading.Tasks;
namespace MyWebhook
{
public class GenericJsonWebHookHandler : WebHookHandler
{
public GenericJsonWebHookHandler()
{
this.Receiver = "genericjson";
}
public override Task ExecuteAsync(string generator, WebHookHandlerContext context)
{
// Get JSON from WebHook
JObject data = context.GetDataOrDefault<JObject>();
if (context.Id == "i")
{
//You can use the passed in Id to route differently depending on source.
}
else if (context.Id == "z")
{
}
return Task.FromResult(true);
}
}
}
Now let’s test to see if the handler works by building the solution and copying the URL from the output.
(There won’t be a landing page because the server doesn’t return anything).
Paste the following URL into Postman and append the following:
URL format for .NET Webhook URL endpoint from your webconfig
Localhost:{Your Port}/api/webhooks/incoming/genericjson/z?code=80ad19e357b01a04fe767067df7cd31b96a844e1
Enter anything you want into the Body.
Note: You need to include something in the Body or the GenericJson config will error out.
Set a breakpoint, send the request, and make sure it comes through.
Connecting to Emma
To connect to Emma you need a public facing API for Emma to send updates to. Right-click the solution and select “Publish” to send the solution to Azure for hosting. When the Azure wizard appears, before you click “Create Profile”, click the Advanced link to set the configuration to Debug to be able to debug from the server.
Attach your application to the remote server for debugging:
- Click “View”, then “Cloud Explorer.”
- Find your application.
- Click “Attach to Debugger.”
Replace localhost with your new URL and add HTTPS at the beginning.
Why add the “S”? Because .NET Webhooks reject non-secure connections. So, if you don’t add the “S” it will not work!
https://{The Azure URL you’re given}/api/webhooks/incoming/genericjson/z?code=80ad19e357b01a04fe767067df7cd31b96a844e1
You can test the listener again via Postman if you like by pasting in the URL above.
Log into your Emma account and retrieve your public API key and account number.
Go back into Postman and create your first Webhook with your credentials from above.
The example below sends a request each time a contact record is updated within Emma. For a full list of available Webhooks visit the Emma API documentation.
Authenticate via the Authorization tab and enter your Emma credentials.
Send the request via Postman. It should return to you the ID of your Webhook.
Go back to your application in Visual Studio and attach to the debugger.
Test the Webhook by logging into your Emma platform and updating a contact. If you’re connected to the remote server, your breakpoint should be hit within a minute or so.
To use the JSON object you received from Emma, you need Newtonsoft and a way to deserialize the Emma request.
using Newtonsoft.Json;
public override Task ExecuteAsync(string generator,, WebHookHandlerContext context)
{
JObject data = context.GetDataOrDefault<JObject>();
EmmaWebhook request = JsonConvert.DeserializeObject<EmmaWebhook>(data.Root.ToString());
You need a class to map the deserialization if you want to access the Emma JSON properties.
public class EmmaWebhook
{
public string event_name { get; set; }
public Data data { get; set; }
}
public class Data
{
public string member_id { get; set; }
public string account_id { get; set; }
//The Emma result can also come with a TimeStamp
//but I didn't want to deal with a DateTime property.
}
Now try updating a contact in Emma. If you’ve entered everything correctly, you should see your result in the debugger.
Troubleshooting
If you experience issues where Emma is not sending the request, make sure your Webhook is registered. You can see registered Webhooks with the following GET request in Postman:
https://api.e2ma.net/{Your Account Id}/webhooks.
If that doesn’t help, connect your Emma account to Zapier and see if Zapier is able to receive the request.
If you’re still unable to receive the request, go back into the article and make sure you didn’t miss any details such as using the proper key length or HTTPS.
Like Working Smarter?
At Mind over Machines, we pride ourselves on finding the gaps and filling them in new, smart, and efficient ways. Webhooks make a lot of sense, so why not democratize their use?
We know there are times when everybody needs a good set of instructions to follow, but if you’d rather be leading the charge – if you have a knack for creating your own solutions to interesting problems – you might want to come work for us. Our Careers page has all the details.