我正在使用 Wix 的 API 來查詢產品。我在將他們的示例轉換為 PHP 方面取得了進展,但對他們的過濾方法感到困惑。例如,這個基本查詢:
curl -X POST \
'https://www.wixapis.com/stores/v1/products/query' \
--data-binary '{
"includeVariants": true
}' \
-H 'Content-Type: application/json' \
-H 'Authorization: <AUTH>'enter code here
重寫為:
public function getProducts($code){
$curl_postData = array(
'includeVariants' => 'true'
);
$params = json_encode($curl_postData);
$productsURL = 'https://www.wixapis.com/stores/v1/products/query';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $productsURL);
curl_setopt($ch, CURLOPT_HEADER, false);
$headers = [
'Content-Type:application/json',
'Authorization:' . $code
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, '');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
$curlErr = curl_error($ch);
curl_close($ch);
return $output;
}
但是我在過濾到特定集合時遇到了問題。這是他們的例子:
curl 'https://www.wixapis.com/stores/v1/products/query' \
--data-binary '{
"query": {
"filter": "{\"collections.id\": { \"$hasSome\": [\"32fd0b3a-2d38-2235-7754-78a3f819274a\"]} }"
}
}' \
-H 'Content-Type: application/json' \
-H 'Authorization: <AUTH>'
這是我對它的解釋($collection是我的變數,用于替換 Wix 示例中的固定值):
public function getProducts($code, $collection){
$curl_postData = array(
'filter' => array(
'collections.id' => array(
'$hasSome' => $collection
)
)
);
$params = json_encode($curl_postData);
$productsURL = 'https://www.wixapis.com/stores/v1/products/query';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $productsURL);
curl_setopt($ch, CURLOPT_HEADER, false);
$headers = [
'Content-Type:application/json',
'Authorization:' . $code
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, '');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
$curlErr = curl_error($ch);
curl_close($ch);
return $output;
}
回應與第一個示例相同——我獲得了所有產品,而不僅僅是一個集合。問題幾乎可以肯定是我對他們示例的解釋。我認為它應該是一個多維陣列,但我可能讀錯了。我很感激任何建議。
uj5u.com熱心網友回復:
在第二個代碼塊中,filter屬性的值不是一個物件,而是一個 JSON 編碼的物件。我不確定為什么 API 需要這樣做,但這意味著您必須json_encode()在 PHP 中使用嵌套。
$curl_postData = array(
'filter' => json_encode(array(
'collections.id' => array(
'$hasSome' => $collection
)
))
);
uj5u.com熱心網友回復:
謝謝,巴爾馬爾。您的答案是正確的,只是稍有改動。這是正常作業的最終代碼段。
$curl_postData = array(
'query' => array(
'filter' => json_encode(array(
'collections.id' => array(
'$hasSome' => $collection
)
))
)
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/401033.html
