【Web】WebHook Detailed Explanation

Introduction to webhooks

In today's hyper-connected online world, nothing works best in isolation. Completing a task (almost) always requires the participation of multiple entities. An eCommerce application needs to communicate with a payment system, a payment system needs to communicate with a banking system, a banking system needs to communicate with customer accounts... Do you see a pattern?

The ability of independent online systems to communicate with each other and share data is at the heart of the value of today's online services. In this article, webhooks will be introduced. Webhooks are one of many ways to facilitate communication between online services, and by the end of this article, you'll have a complete understanding of what webhooks are, how they work, and when to use them.

What are webhooks?

A webhook is an HTTP request that is triggered by an event in the source system and sent to the target system, usually with a data payload. Webhooks are automated, in other words they are automatically sent when their events are fired in the source system.

This provides a way for one system (the source) to "talk" (HTTP requests) with another system (the target) when an event occurs, and share information about what happened (the request payload).
insert image description here

What are webhooks for?

Based on the above definition, I believe you have understood the purpose of webhook. In short, webhooks are used to communicate the occurrence of an event in one system to another, and they often share data about that event. However, an example is always easier to illustrate, so let's look at a webhook example.

Let's say you subscribe to a streaming service. At the beginning of each month, your credit card will be charged and your bank will need to communicate with you via text message or email. A banking system (source) can use a webhook to call a mail or SMS service (destination) to send you an immediate debit notification every time your card is charged.

The banking system also sends information about the charges, which the mail or SMS service uses to construct an appropriate message for your customer.

webhook request process

For a system to send a webhook, the system must be able to support the process. You can build systems to send webhooks and slack by triggering HTTP requests for different types of events.

These platforms support different types of events depending on the activity taking place within them.

To receive webhook requests, you must register one or more events (also known as topics) for which the platform provides the webhook. The webhook request will be sent to the application's target endpoint, so you need to build one for it and register the URL as the webhook URL for that event.

Once the event's webhook registration is complete and the endpoint has been added, you will receive webhook requests at the target URL provided each time the event occurs.

use webhooks

Now that you have registered webhook requests, you must be ready to receive them. Webhooks are regular HTTP requests and should be handled as such. A webhook provider always has documentation on the implementation details of the webhook URL endpoint to receive the request and access the payload (if any).

Webhook payloads are in serialized form-encoded JSON or XML format.

Webhooks are a one-way communication system, but best practice is to return a 200 or 302 status code to let the originating application know you received it.

It is also recommended to make the webhook request operation on your end idempotent, because some source applications can send the same webhook request multiple times. In this case, you want to ensure that your responses to webhook requests are not duplicated, as this could lead to compromised systems. For more details on implementing webhook idempotence, check out this article.

Webhook POST or GET

Depending on the webhook provider, you might get webhook requests as GET or POST requests. GET webhook requests are simple, their payload is appended to the webhook URL as a query string. The payload of a POST webhook request is in the request body, which may also contain attributes such as authentication tokens.

Webhooks and Polling

Polling is when your application calls the API periodically to check for events or new data. Webhooks, on the other hand, manually push data to your application as events occur in real time.

To capture the difference between these two approaches with a relevant example, voting is like going to the post office to check if you have new mail. Using a webhook is basically every time you get new mail, just give the postman your home address and the mail will be delivered to your home.

Polling is more resource-intensive than webhooks because it can accept multiple network requests before discovering new information, whereas webhooks only make network requests when new information is available.

insert image description here

When to use webhooks

The key word here is real time. When you want to:

  • Gain real-time visibility into events in connected systems
  • Send information to the destination in real time
  • Find cheaper alternatives than voting

Examples of these types of scenarios include:

  • Ecommerce stores notify your invoicing app about sales
  • Ecommerce stores notify merchants when a specific item is out of stock
  • The payment gateway notifies the merchant to pay
  • The version control system notifies team members of commits to the repository
  • Monitoring systems alert administrators to errors or unusual activity in the system
  • Synchronize information across systems - for example, when a user changes their email in your HR or CRM system, their email in the payroll or invoicing system also changes

Asp .Net

Accept and process

interface

Receiving a WebHook depends on who the sender is. Sometimes an additional step in registering a WebHook is to verify that the subscriber is actually listening. Certain WebHooks provide a push-to-pull model, where an HTTP POST request simply contains a reference to the event information, which is then independently retrieved. In general, security models vary.

The purpose of Microsoft ASP.NET WebHooks is to make hooking up APIs easier and more consistent without spending a lot of time learning how to handle any particular variation of WebHooks.

The WebHook receiver is responsible for accepting and validating WebHooks from a particular sender. A WebHook sink can support any number of WebHooks, each with its own configuration. For example, the GitHub WebHook sink can accept WebHooks from any number of GitHub repositories.

WebHook Receiver URI

By installing Microsoft ASP.NET WebHook, you can get a regular WebHook controller that accepts WebHook requests from an open number of services. When a request arrives, it picks the appropriate receiver that has been installed to handle the particular WebHook sender.

The URI for this controller is the WebHook URI registered with the service in the following format:

https:///api/webhooks/incoming//{id}

For security reasons, many WebHook receivers require that the URI be an https URI, and in some cases it must also contain an additional query parameter, which is used to enforce that only the intended party can send the WebHook to said URI.

Component is the name of the recipient, such as github or slack.

{id} is an optional identifier that can be used to identify a specific WebHook sink configuration. This can be used to register N WebHooks with specific receivers. For example, the following three URIs can be used to register three separate WebHooks:

https:///api/webhooks/incoming/github
https:///api/webhooks/incoming/github/12345
https:///api/webhooks/incoming/github/54321

Install the WebHook receiver

To receive WebHooks using Microsoft ASP.NET WebHooks, first install the Nuget package for the WebHook provider or providers from which you want to receive WebHooks. The Nuget package is named Microsoft.AspNet.WebHooks.Receivers.* where the last part indicates that the service is supported. For example

Microsoft.AspNet.WebHooks.Receivers.GitHub supports receiving WebHooks from GitHub and Microsoft.AspNet.WebHooks.Receivers.Custom supports receiving WebHooks generated by ASP.NET WebHooks.

Support is currently found for Dropbox, GitHub, MailChimp, PayPal, Pusher, Salesforce, Slack, Stripe, Trello, and WordPress, but any number of other providers can be supported.

Configure WebHook Receiver

WebHook receivers are configured through the IWebHookReceiverConfig interface, and specific implementations of this interface can be registered using any dependency injection model. The default implementation uses application settings that can be set in the Web.config file, or, if using Azure веб-приложения, can be set through the Azure portal.
insert image description here
The format of the application settings key is as follows:

 MS_WebHookReceiverSecret_<receiver>

The value is a comma-separated list of values ​​that match the {id} values ​​that the WebHook has registered, for example:

MS_WebHookReceiverSecret_GitHub = <secret1>, 12345=<secret2>, 54321=<secret3>

Initialize the WebHook receiver

WebHook receivers are initialized by registering them, usually in the WebApiConfig static class, for example:

namespace WebHookReceivers
{
    
    
    public static class WebApiConfig
    {
    
    
        public static void Register(HttpConfiguration config)
        {
    
    
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new {
    
     id = RouteParameter.Optional }
            );

            // Load receivers
            config.InitializeReceiveGitHubWebHooks();
        }
    }
}

deal with

Once the WebHook receiver has authenticated the WebHook request, it can be processed by user code. This is where the handler is passed in. Handlers derive from the IWebHookHandler interface, but typically use the WebHookHandler class instead of deriving directly from the interface.

WebHook requests can be handled by one or more handlers. The handlers are called in order according to their respective Order properties, where Order is a simple integer (between 1 and 100 is recommended):

insert image description here
A handler can optionally set the Response property on the WebHookHandlerContext, which will cause processing to stop and the response to be sent back to the WebHook as an HTTP response. In the above case, handler C is not called because it is higher order than B and B sets the response.

Setting responses is generally only relevant for WebHooks, where the response can pass information back to the original API. For example, a case where a Slack WebHook will post a response back to the channel the WebHook came from. A handler can set the Receiver property if it only wants to receive WebHooks from that particular receiver. If no receiver is set, all receivers will be called for it.

Another common response use is to use the 410 Returned response to indicate that the WebHook is no longer active and no further requests should be submitted.

By default, all WebHook receivers will call the handler. However, if the Receiver property is set to the name of a handler, the handler will only receive WebHook requests for that receiver.

Handling WebHooks

When the handler is invoked, it gets a WebHookHandlerContext that contains information about the WebHook request. Data (usually the HTTP request body) can be obtained from the Data property.

The data type is typically JSON or HTML form data, but can be cast to a more specific type if desired. For example, custom WebHooks generated by ASP.NET WebHooks can be cast to the CustomNotifications type as follows:

public class MyWebHookHandler : WebHookHandler
{
    
    
    public MyWebHookHandler()
    {
    
    
        this.Receiver = "custom";
    }

    public override Task ExecuteAsync(string generator, WebHookHandlerContext context)
    {
    
    
        CustomNotifications notifications = context.GetDataOrDefault<CustomNotifications>();
        foreach (var notification in notifications.Notifications)
        {
    
    
            ...
        }
        return Task.FromResult(true);
    }
}

queue processing

Most WebHook senders will resend the WebHook if the response does not generate a response within a few seconds. This means that the handler must finish processing within that time period, lest it be called again.

If processing takes longer or is better handled individually, a WebHookQueueHandler can be used to submit WebHook requests to a queue, such as an Azure Storage queue.

An overview of the WebHookQueueHandler implementation is provided here:

public class QueueHandler : WebHookQueueHandler
{
    
    
    public override Task EnqueueAsync(WebHookQueueContext context)
    {
    
    

        // Enqueue WebHookQueueContext to your queuing system of choice

        return Task.FromResult(true);
    }
}

send

translation move

The difference and connection between WebHook and message queue

source

Webhooks Explained: What are Webhooks and How Do They Work?
ASP.NET WebHook ReceiverASP.NET
WebHook Handler

Guess you like

Origin blog.csdn.net/weixin_44231544/article/details/130156857