【问题标题】:how to update product information outside from Magento如何在 Magento 之外更新产品信息
【发布时间】:2025-12-07 17:50:02
【问题描述】:

我想以编程方式更新产品信息,例如数量、价格等。 (来自 Magento 源目录之外。)

我该怎么做?

【问题讨论】:

    标签: php magento2


    【解决方案1】:

    Magento 很容易引导。如果您想要一个可以访问所有函数的独立脚本,只需在 PHP 文件顶部添加以下内容:

    define('MAGENTO', realpath(dirname(__FILE__)));
    require_once MAGENTO . '/../app/Mage.php'; //or whatever location your Mage.php file is
    Mage::app(Mage_Core_Model_Store::ADMIN_CODE); //initialization with another store is possible
    

    之后,您可以加载所有模型。要更新您的产品,我建议您使用两种方法。普通的:

    Mage::getModel('catalog/product')->setStoreId($myStoreId)->load($myProductId)
        ->setPrice(50)
        ->save();
    

    或 API 模型用法:

    $api = Mage::getModel('catalog/product_api_v2');
    $api->update($productId, $productData, $store, $identifierType);
    

    【讨论】:

      【解决方案2】:

      我强烈建议利用 M2x 中提供的 REST API 来创建/更新产品及其属性。
      注意:您可以选择在 Magento 2 中使用 OAuth 或不记名令牌来验证/授权您的 API 调用。

      您可以在此处找到有关 Magento 2.1 中所有可用 API 的更多信息 - http://devdocs.magento.com/swagger/index_21.html

      您可以在标题为 catalogProductRepositoryV1 的分组下​​找到所需 API 的详细信息

      • 使用搜索/过滤条件获取产品信息 -> GET /V1/products
      • 获取特定产品的信息 -> GET /V1/products/{sku}
      • 创建新产品 -> POST /V1/products
      • 创建/更新特定产品 -> PUT /V1/products/{sku}

      我还没有测试过代码,但我认为这样的事情应该可以解决问题:

          $BEARER_TOKEN_TO_USE_FOR_TRANSACTION = 'XYZ';
      
          $REQUEST_HEADER = array( 
                              "Authorization => Bearer ". $BEARER_TOKEN_TO_USE_FOR_TRANSACTION , 
                              "cache-control: no-cache",
                              "content-type: application/json"
                              ); 
          $REQUEST_URL='INSTANCE_URL/rest/V1/products';
      
          $PRODUCT_DATA_TO_USE ='{
            "product": {
              ENTER_PRODUCT_ATTRIBUTES_AS_JSON
          } }';
      
          $CURL_OBJ = curl_init($REQUEST_URL); 
      
          $CURL_OPTIONS_ARRAY_TO_USE = array (
              CURLOPT_HTTPHEADER => $REQUEST_HEADER,
              CURLOPT_CUSTOMREQUEST => "POST",
              CURLOPT_POSTFIELDS => $PRODUCT_DATA_TO_USE,
              CURLOPT_URL => $REQUEST_URL,
              CURLOPT_RETURNTRANSFER => true,
              CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
              CURLOPT_ENCODING => "",
              CURLOPT_MAXREDIRS => 10,
              CURLOPT_TIMEOUT => 30,
          );
      
          curl_setopt_array($CURL_OBJ, $CURL_OPTIONS_ARRAY_TO_USE);
          $result = curl_exec($CURL_OBJ);
          $result =  json_decode($result);
          echo 'Output -> " . $result;
      

      【讨论】: