Skip to content

Tutorial: Creating Webhooks

Gowri edited this page Dec 9, 2021 · 20 revisions

One of the most common use cases of async events is to publish webhooks to external systems. In this tutorial we'll explore creating a simple webhook that is published to all subscribers when a sales order is placed.

Firstly, we'll need to define an asynchronous event so we can dispatch it. A definition of an asynchronous event describes the name of the event and the shape of the data that will be provided when the event is dispatched.

An advantage of this is that lot of the core Magento data interfaces that are used for web APIs can be reused. Which means, if those APIs ever get updated, you don't have to change a thing.

Defining Async Event and Payload

<async_event name="sales.order.created">
    <service class="Magento\Sales\Api\OrderRepositoryInterface" method="get"/>
</async_event>

The above code defines a sales.order.created. This asynchronous event will have some data that corresponds to the same interface as the orders API.

How do we know?

If you open Magento/Sales/etc/webapi.xml and find the API for get orders, we can see it's being powered by the same method of the same repository.

    <route url="/V1/orders/:id" method="GET">
        <service class="Magento\Sales\Api\OrderRepositoryInterface" method="get"/>
        <!-- ... -->
    </route>

Which means, you can pretty much turn any existing web API into a webhook. There are some caveats depending on the repositories, please see the warnings.

Creating subscribers

Once you have an asynchronous event defined, the next step is to create a subscription. Here we will use an HTTPs subscription. The REST API can be used to create a new subscription

{
  "asyncEvent": {}
}

Dispatching Async Event

Clone this wiki locally