CommercePeer Brand Logo


Programmatically: Magento 2 Product Entity

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:


		

	
    
        
            
                YourCompany\YourModule\Observer\WebhookObserver
                execute
            
        
    
	
	

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);
}
	

LET’S WORK TOGETHER

We love working with Small Businesses, Retailers, Manufacturers. Our team is here to Help.

→ Schedule Free Consultant Now
Copyright © 2024 CommercePeer. All Rights Reserved.