我尝试使用API获得的价格更新所有产品。现在我在运行脚本时遇到此错误:
Array ( [update] => Array ( [0] => Array ( [id] => 0 [error] => Array ( [code] => woocommerce_rest_product_invalid_id [message] => Invalid ID. [data] => Array ( [status] => 400 ) ) ) ) )
我在哪里乱搞?我知道它说ID无效,但我不确定如何迭代产品而不必单独解决每个ID。
<?php
require __DIR__ . '/vendor/autoload.php';
use Automattic\WooCommerce\Client;
use Automattic\WooCommerce\HttpClient\HttpClientException;
$woocommerce = new Client(
'http://exemple.com',
'ck_xxxxxxxxxxx',
'cs_xxxxxxxxxxx',
[
'wp_api' => true,
'version' => 'wc/v2',
// 'query_string_auth' => true
]
);
function parse_json( $file ) {
$json = json_decode( file_get_contents( $file ), true );
if ( is_array( $json ) && !empty( $json ) ) :
return $json;
else :
die( 'An error occurred while parsing ' . $file . ' file.' );
endif;
}
$url = 'https://username:password@apiservice.com/apis/v1.0/xxxxxxxx';
$json = parse_json($url);
foreach ($json as $product){
$data = [
'update' => [
[
'id' => (int)$product['id'],
'regular_price' => $product['regular_price']
]
]
];
}
print_r($woocommerce->post('products/batch', $data));
?>
这是API I的数据结构,试图从中获取价格:
[
{
"id": "595",
"type": "simple",
"parent_product_id": "",
"name": "Product 1",
"description": "Descrição",
"regular_price": "26.78",
"manage_stock": "1",
"stock": "5",
"weight": "0",
"attribute_name": "",
"attribute_value": "",
"has_variations": "",
"image": "site.com/imagem1.png",
"sku": "10010"
},
{
"id": "596",
"type": "simple",
"parent_product_id": "",
"name": "Product 2",
"description": "Descrição",
"regular_price": "0",
"manage_stock": "0",
"stock": "0",
"weight": "0",
"attribute_name": "",
"attribute_value": "",
"has_variations": "",
"image": "site.com/imagem2.png",
"sku": "11010"
},
(...)
]
答案 0 :(得分:0)
其$url = 'https://username:password@apiservice.com/apis/v1.0/xxxxxxxx';
使用:
$user = 'username';
$pass = 'password'
$url = 'http://apiservice.com/apis/v1.0/xxxxx'
$context = stream_context_create(array(
'http' => array(
'header' => "Authorization: Basic " . base64_encode("$user:$pass")
)
));
$data = file_get_contents($url, false, $context);
$json_new = json_decode($data, true);