You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Magento 2 Rest API产品保存事件咨询:触发外部系统产品同步

Real-Time Sync Between Magento 2 Product Additions and Your Custom Software

Great question! Let's walk through how you can achieve this real-time sync, since Magento 2's core REST API doesn't expose direct webhook events like product_save_after out of the box—but there are solid workarounds to make this happen.

Magento's backend event system is exactly what you need here. You can build a lightweight custom module to listen for the product_save_after event, then trigger your custom software's API to sync the new product data. Here's how to approach it:

  • Step 1: Register the event observer
    Create a custom module (if you don't have one already) and add an event declaration in etc/events.xml:

    <?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="product_save_after">
            <observer name="sync_product_to_custom_software" instance="Vendor\Module\Observer\SyncProductToCustomSoftware" />
        </event>
    </config>
    
  • Step 2: Build the observer class
    In your observer class, fetch the saved product data, check if it's a new product (using $product->isObjectNew()), then send a POST request to your custom software's API. Example PHP code:

    <?php
    namespace Vendor\Module\Observer;
    
    use Magento\Framework\Event\Observer;
    use Magento\Framework\Event\ObserverInterface;
    use Magento\Catalog\Model\Product;
    use GuzzleHttp\Client;
    
    class SyncProductToCustomSoftware implements ObserverInterface
    {
        protected $client;
    
        public function __construct(Client $client)
        {
            $this->client = $client;
        }
    
        public function execute(Observer $observer)
        {
            /** @var Product $product */
            $product = $observer->getProduct();
            
            // Only sync new products (skip updates if you don't need them)
            if (!$product->isObjectNew()) {
                return;
            }
    
            // Map Magento product data to your custom software's required format
            $productData = [
                'sku' => $product->getSku(),
                'name' => $product->getName(),
                'price' => $product->getPrice(),
                // Add other fields as needed
            ];
    
            try {
                // Send request to your custom software's API endpoint
                $this->client->post('https://your-custom-software.com/api/add-product', [
                    'json' => $productData,
                    'headers' => [
                        'Authorization' => 'Bearer YOUR_CUSTOM_SOFTWARE_API_KEY'
                    ]
                ]);
            } catch (\Exception $e) {
                // Log errors for debugging (use Magento's logger)
                $logger = \Magento\Framework\App\ObjectManager::getInstance()->get(\Psr\Log\LoggerInterface::class);
                $logger->error('Failed to sync product to custom software: ' . $e->getMessage());
            }
        }
    }
    
  • Step 3: Handle the API response in your custom software
    When your software receives the product data, you can either:

    • Automatically create the product entry in your system (best for true sync)
    • Trigger the "add product" page pre-filled with the Magento product data (if you need manual review before saving)

Option 2: Use Magento 2 Webhook Extensions

If you don't want to build a custom module from scratch, you can use existing webhook extensions from the Magento Marketplace. These extensions let you map Magento events (like product_save_after) to external API endpoints, so you can configure them to send product data to your custom software whenever a new product is added.

Option 3: Polling (Non-Real-Time Fallback)

If real-time sync isn't strictly mandatory, you can set up a scheduled task (cron job) in your custom software that periodically calls Magento's REST API to fetch new products. Use the created_at filter to get products added since the last sync:

# Example REST API call (replace with your credentials and date range)
curl -X GET "https://your-magento-site.com/rest/V1/products?searchCriteria[filter_groups][0][filters][0][field]=created_at&searchCriteria[filter_groups][0][filters][0][value]=2024-01-01 00:00:00&searchCriteria[filter_groups][0][filters][0][condition_type]=gteq" \
-H "Authorization: Bearer YOUR_MAGENTO_API_TOKEN"

This is simpler to set up but won't give you instant sync.

Key Notes to Consider

  • Error Handling: Always add retry logic or error logging for failed API calls to avoid losing product data.
  • Data Mapping: Make sure all critical product fields (SKU, price, inventory, etc.) are correctly mapped between Magento and your custom software.
  • Authentication: Use secure API keys or OAuth for both the Magento API and your custom software's API to prevent unauthorized access.

内容的提问来源于stack exchange,提问作者Vish Vaghela

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:17:21