0

I want to extend a Magento 2 application with communication to a remote webservice.

The requirement is simple: When Productdata gets updated, I want to send a request to a webservice. Depending on the result of the request, I want to update a custom field of the product.

I just don't know how to get this started. Do I need to build a module? Do I need to configure a integration? Is it both?

Thanks!

Sarfaraj Sipai
  • 976
  • 2
  • 13
  • 29
Weissvonnix
  • 103
  • 2

2 Answers2

1

In your case, it's better to use observer. In your case, you should use observer catalog_product_save_after. So now:

  1. Create a new module, let's say Vendor_Module. I assume you know how to create a module. If not, refer to here.
  2. Create file app\code\Vendor\Module\etc\frontend\events.xml with the following content:

    <?xml version="1.0"?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
        <event name="catalog_product_save_after">
            <observer name="call_sample_api" instance="Vendor\Module\Observer\UpdateProduct"/>
        </event>
    </config>
    
  3. Create file app\code\Vendor\Module\Observer\UpdateProduct.php with the following content:

    <?php
    namespace Vendor\Module\Observer;
    
    use \Magento\Framework\Event\ObserverInterface;
    use \Magento\Framework\HTTP\Client\Curl;
    
    class UpdateProduct implements ObserverInterface {
        //Your API details
        protected $APIAddress = '<Your API address>';
    
        /**
         * @var \Magento\Framework\HTTP\Client\Curl
         */
        protected $curl;
    
        /**
         * @param Curl $curl
         */
        public function __construct(
            Curl $curl
        ) {
            $this->curl = $curl;
        }
    
        public function execute(Observer $observer) {
            //I assume you use get method
            $url = $this->APIAddress;
            $product = $observer->getProduct();
            //Load Product Attributes
            $params = [
                'product_attr_1' => $product->getData('product_attr_1'),
                'product_attr_2' => $product->getData('product_attr_2'),
                //And so on if you have
            ];
            //I assume you use POST method
            $this->curl->post($url, $params);
            //Do rest of your works if applicable
    
        }
    }
    

    Note: This is the method to use cURL in Magento.

PY Yick
  • 2,705
  • 1
  • 17
  • 35
0

I prefer to create a module which hooks into catalog_product_save

(check the magento2 event list) event.

So that when product is updated via admin you module gets in action and based on the webservice result update your custom field.

Manoj Deswal
  • 5,785
  • 25
  • 27
  • 50
Twinkle
  • 1
  • 1