0

Case : When product is created, I need to send SKU to 3rd party, and then they immediately call magento REST API to get product by SKU.

So far I'm using catalog_product_save_after event. And for testing purpose I call v1/products/{sku} inside observer.

public function execute(\Magento\Framework\Event\Observer $observer)
    {
     $product = $observer->getProduct();
     if($product->isObjectNew()){
       $ch = curl_init("http://xxx.xxx/index.php/rest/V1/products/".$product->getSku());
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Authorization: Bearer " . xxx));
        $result = curl_exec($ch);
     }
}

Observer is working fine and I can get $product.

However, unfortunatelly the result for calling rest api is error "message":"Requested product doesn't exist". But when i tried to call v1/products/{sku} with same SKU as before after few seconds, I got the product.

Is there any way to get what i want with that flow? Or I need to use another event?

1

catalog_product_save_after is fired in scope of product save DB transaction. So the product is not actually persisted to the database yet, when it is requested via web API.

Preferred extension mechanism in Magento 2 is plugins. When 'after' plugin is invoked, product transaction should already be committed, so your case should pass.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.