如何在magento 2.0中使用curl请求获取产品列表

时间:2017-04-19 05:25:49

标签: php api magento curl

我希望使用curl请求获取所有产品。我通过仪表板中的API集成生成了访问令牌。

以下是获取产品列表的代码。

$token = 'xxxxxxxxxxxxxxxxxxxxxx';
$url = 'http://myIP/Magento/index.php/rest/V1/products';
$params = array('searchCriteria[filter_groups][0][filters][0][field]'=>'page_size','searchCriteria[filter_groups][0][filters][0][value]'=>10);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: Bearer '.$token));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$res = curl_exec($curl);
$response =  json_decode($res);
print_r($response);

回复是

stdClass Object ( [message] => %fieldName is a required field. [parameters] => stdClass Object ( [fieldName] => product ) )

请帮忙。我如何获得产品。

2 个答案:

答案 0 :(得分:1)

你可以这样做:

<?php

$token = "xxxxxxxxxxxxxxxxxxxxxxxx";
$api = "rest/V1/products";

$json = '
{
    "search_criteria": {
        "filter_groups": [
            {
                "filters": [
                    {
                        "field": "name",
                        "value": "%",
                        "condition_type": "like"
                    }
                ]
            }
        ],
        "sort_orders": [
            {
                "field": "name",
                "direction": "ASC"
            }
        ]
    }
}
';

$get_params = http_build_query(json_decode($json));

$ch = curl_init("http://my.website.com/index.php/".$api."?".$get_params);

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  "Authorization: Bearer ".$token
));

$result = curl_exec($ch);
$result = json_decode($result, 1);
print_r($result);

?>

答案 1 :(得分:0)

啊,我找到了它,上面是maxagaz建议的命令行版本:

curl -g -H "Authorization: Bearer xxxxxxxxxxxxxxxxxxxx" "http://example.com/index.php/rest/V1/products?searchCriteria[filter_groups][0][filters][0][field]=name&searchCriteria[filter_groups][0][filters][0][value]=%25&searchCriteria[filter_groups][0][filters][0][condition_type]=like"