How to use a Webhook in Magento 2

How to use a Webhook in Magento 2

Today we will discuss how to use a webhook in Magento 2. So before starting on this topic let’s start first with the basics of Webhook.

What is a Webhook?

Webhook is basically an event of sending an HTTP request to a URL by which two applications communicate between. Using Webhook we can read the real-time information in the request and processes it.

How to use a Webhook in Magento 2?

For using a webhook in Magento 2 we need to create a REST API in Magento 2 which it will serve as a URL to collect and read Webhook data.

First, we will create a route for REST API in Magento 2 as a POST type:

<?xml version="1.0"?>
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi.xsd">
    <route url="/V1/custom/webhook/inventory" method="POST">
        <service class="Vendor\Module\Api\InventoryWebhookManagementInterface" method="getInventoryWebhookRequest"/>
            <resources>
                <resource ref="anonymous"/>
            </resources>
    </route>
</routes>

Now we will add an API interface class to define the parameters

<?php
namespace Vendor\Module\Api;

/**
* @api used to respond custom api
*/
interface InventoryWebhookManagementInterface
{
    /**
    * @return response to the user
    *
    * POST method used here to post api
    */
    public function getInventoryWebhookRequest();

}

In last we will add a Model management file to execute the coming response from Webhook.

<?php

namespace Vendor\Module\Model;

class InventoryWebhookManagement implements InventoryWebhookManagementInterface
{
    protected $_logger;

    public function __construct(
        \Psr\Log\LoggerInterface $logger
    ){
        $this->logger = $logger;
    }

    public function getInventoryWebhookRequest()
    {
        $api_data = file_get_contents("php://input");
        $this->logger->info($api_data);
    }

}

So on the execution of the event, we will receive a response which is sent via Webhook in our system.log file.

Hope you got the working of adding a Webhook in Magento 2 now.

5 2 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments