在Magento 2 API中分配相关产品

时间:2018-01-04 11:55:04

标签: php magento magento2

我使用magento 2 api分配产品链接,例如相关 crosssell 使用api / V1 / products / {sku} / links

这是我的示例代码

<?php
error_reporting(E_ALL);
define('mag_apiurl',"http://www.mywebsite.com/rest/V1/");
define('tn_webshopKey',"myshowpkey");
$sku1 = "sku1";
$sku2 = "sku2";
$productData = array(
        "items" =>  array(
              "sku" => $sku1,
              "linkType" => 'related',
              "linkedProductSku" => $sku2,
              "linkedProductType" => "simple",
              "position" => 0
        )
    );

    $headers = array("Content-Type:application/json","Authorization: Bearer ".tn_webshopKey);
    $requestUrl= mag_apiurl.'products/'.$sku1.'/links';
    $ch = curl_init($requestUrl);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($productData));
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    echo $returnProductDetails = curl_exec($ch);
?>

但每次我运行脚本吧 回应

{"message":"%fieldName is required filed.","parameters":{"fieldName":"linkType"}}

但链接类型&#39;相关&#39;已在我的数据(productData)中定义

有谁知道解决方案或相关链接有助于:)

2 个答案:

答案 0 :(得分:0)

对不起我的错,我正在阅读magento-2.2企业版的swagger api文档。*但我正在使用magento-2.1。*

实际代码应

$productData = array(
        "items" =>  array(
            array(           
              "sku" => $sku1,
              "link_type" => 'related',
              "linked_product_sku" => $sku2,
              "linked_product_type" => "simple",
              "position" => 0
            )  
        )
    );

    /*
    THE JOSN FORMAT START
    {
      "items": [
        {
          "sku": "string",
          "link_type": "string",
          "linked_product_sku": "string",
          "linked_product_type": "string",
          "position": 0,
          "extension_attributes": {
            "qty": 0
          }
        }
      ]
    }

 ***************END************/

我注意到这些文档之间存在一些差异,每个文档都有不同的模型架构声明,例如有些 snake_case ,另一方面有些 camelCase 所以不要开始混淆在swagger的文档之间,为每个商店选择适当的文档版本

答案 1 :(得分:0)

您可以尝试将“linkType”设置为1而不是“相关”

$linkTypes = ['related' => 1, 'upsell' => 4, 'crosssell' => 5, 'associated' => 3];