我正在构建一个脚本作为研究项目,以便从API检索价格并每5分钟更新一次数据库。以下代码正在运行。
但现在维持这是一场噩梦,因为我必须按ID列出每个产品以及手动引用api密钥。
我很难做一个foreach循环链接数据库中的产品和api基于他们的SKU并从那里更新价格,但我似乎无法将其拉下来。
<?php
require __DIR__ . '/vendor/autoload.php';
use Automattic\WooCommerce\Client;
use Automattic\WooCommerce\HttpClient\HttpClientException;
$woocommerce = new Client(
'http://example.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/c1212kj1n1n1b112';
$json = parse_json($url);
//Updates simple products prices. Product #586:
$data = [
'update' => [
[
'id' => 586,
'regular_price' => $json['name' == 'Product 1']['regular_price']
]
]
];
print_r($woocommerce->post('products/batch', $data));
// Update product variations. Product #588:
$data = [
'update' => [
[
'id' => 589,
'regular_price' => $json['product_variation[0]']['regular_price']
],
[
'id' => 590,
'regular_price' => $json['product_variation[1]']['regular_price']
],
[
'id' => 591,
'regular_price' => $json['product_variation[2]']['regular_price']
],
]
];
print_r($woocommerce->post('products/588/variations/batch', $data));
?>
API输出示例:
[
{
"product_id": "100",
"type": "simple",
"parent_product_id": "",
"name": "Product 1",
"description": "A short description",
"regular_price": "26.78",
"manage_stock": "1",
"stock": "5",
"weight": "0",
"attribute_name": "",
"attribute_value": "",
"has_variations": "",
"image": "site.com/image1.png",
"sku": "10010"
},
{
"product_id": "200",
"type": "variable",
"parent_product_id": "",
"name": "Product 2",
"description": "A short description",
"regular_price": "0",
"manage_stock": "0",
"stock": "0",
"weight": "0",
"attribute_name": "Color",
"attribute_value": "",
"has_variations": "1",
"image": "site.com/image2.png",
"sku": "11010"
},
{
"product_id": "",
"type": "product_variation",
"parent_product_id": "200",
"name": "",
"description": "A short description",
"regular_price": "3.70",
"manage_stock": "1",
"stock": "100",
"weight": "0",
"attribute_name": "Color",
"attribute_value": "Red",
"has_variations": "",
"image": "",
"sku": "11011"
},
这有可能实现吗?