-
Notifications
You must be signed in to change notification settings - Fork 4
II. Getting Started
- Async Events: are events that are dispatched from Magento when they are triggered
- Subscribers: is something that listens to one or several async events.
Async events are defined in etc/async_events.xml
. The definition only provides an acknowledgement to Magento that such an async event exist. It has to be dispatched by you at a place you find suitable.
<async_event name="sales.order.created">
<service class="Magento\Sales\Api\OrderRepositoryInterface" method="get"/>
</async_event>
-
async_event
-
name
- A unique name given to the asynchronous event
-
-
service
-
class
- The class or interface that defines the handler. -
method
- The method which is executed and the return value is published to subscribers.
-
Events are dispatched by simply publishing to the EVENT_QUEUE
, however it needs to follow a certain structure.
The Magento\Framework\MessageQueue\PublisherInterface::publish
takes in two arguments
public function publish($topicName, $data);
The first argument $topicName
SHOULD be a string that's defined by the constant \Aligent\AsyncEvents\Helper\QueueMetadataInterface::EVENT_QUEUE
The second argument $data
follows a specific structure. It should contain an array of two strings.
- The first string specifies what
async_event
to dispatch. (anything that's defined inasync_events.xml
) - The second string SHOUD be a JSON serialised string. The serialised string should contain the named arguments of the service method that resolves the async event.
For example, if your service method was Magento\Sales\Api\OrderRepositoryInterface::get
which takes in the following inputs
/**
* @param int $id The order ID.
* @return \Magento\Sales\Api\Data\OrderInterface Order interface.
*/
public function get($id);
your $data
array should look like
$arguments = ['id' => $orderId];
$data = ['sales.order.created', $this->json->serialize($arguments)]
This is likely to change in a future major version where a AsyncEventMessageInterface
would be passed instead of an array of two strings.
Example:
public function execute(Observer $observer): void
{
/** @var Order $object */
$object = $observer->getEvent()->getData('order');
$arguments = ['id' => $object->getId()];
$data = ['sales.order.created', $this->json->serialize($arguments)];
$this->publisher->publish(QueueMetadataInterface::WEBHOOK_QUEUE, $data);
}
Each subscription might want to be handled a little differently. This is useful when each subscriber has their own preferred way of receiving notifications.
Finally, to receive notifications of async events, you have to create subscribers. The module has a REST API to create and manage subscriptions.
{
"asyncEvent": {
"event_name": "sales.order.created",
"recipient_url": "https://example.com/order_created",
"verification_token": "fv38u07Wdh$R@mRd",
"metadata": "http"
}
}