Programmatically: How to create custom Magento webhooks
Step 1: Create an Observer Class
Create a new PHP file in the app/code/YourCompany/YourModule/Observer directory (replace YourCompany and YourModule with your module's namespace and name).
In this file, create a class that implements the Magento\Framework\Event\ObserverInterface. For example:
// app/code/YourCompany/YourModule/Observer/WebhookObserver.php
namespace YourCompany\YourModule\Observer;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
class WebhookObserver implements ObserverInterface
{
public function execute(Observer $observer)
{
// Your code here to handle the webhook event
}
}
Step 2: Define the Webhook Event
In the same file, define the webhook event using the event.xml file. This file should be placed in the app/code/YourCompany/YourModule/etc directory.
Create a new file called event.xml:
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/event.xsd">
<events>
<event name="sales_order_place_after">
<observer>
<class>YourCompany\YourModule\Observer\WebhookObserver</class>
<method>execute</method>
</observer>
</event>
</events>
</config>
Step 3: Implement Webhook Logic
In the execute method of your observer class, you can implement the logic to send the webhook notification to the external service. For example:
// app/code/YourCompany/YourModule/Observer/WebhookObserver.php
public function execute(Observer $observer)
{
// Get the order object
$order = $observer->getOrder();
// Send a POST request to the external service
$url = 'https://your-external-service.com/webhook';
$data = array('order_id' => $order->getId(), 'order_status' => $order->getStatus());
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
$response = curl_exec($ch);
curl_close($ch);
// Log the response
Mage::log('Webhook response: ' . $response);
}