if(isset($_POST['add_shopify']))
{
$title = $_POST['title'];
$body = $_POST['body_html'];
$vendor = $_POST['vendor'];
$type = $_POST['product_type'];
$price = $_POST['price'];
$images = $_POST['images'];
$product = array(
'title'=> $title,
'body_html' => $body,
'vendor'=> $vendor,
'product_type'=> $type,
"variants"=>[[
"price"=> $price
]],
"images" => [
[
"src"=> $images
]
]
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL," https://9e54fc.myshopify.com/admin/api/2022-10/products.json?access_token=*********************" );
curl_setopt($curl, CURLOPT_FAILONERROR, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURLOPT_HTTPHEADER,array(
'Content-Type' => 'application/json',
));
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($product));
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$resp = curl_exec($curl);
if (curl_errno($curl)) {
$error_msg = curl_error($curl);
}
curl_close($curl);
if (isset($error_msg)) {
echo $error_msg;
}
$status_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
print_r(json_decode($resp));
when i run this code it's return true. but when i am checking admin panel there are no product showing of that name. this code is working properly in postman api. please tell me about it what's wrong with it?
CodePudding user response:
You are missing the "product" key in the $product array, please check the below code that there is a "product" key, and inside that, all the product details are there. You have to pass the data in JSON format, but you are using http_build_query, which Shopify doesn't accept with application/json header, so please use the below code to create a product via PHP curl.
<?php
$productData = [
"product" => [
"title" => "Burton Custom Freestyle 151",
"body_html" => "<strong>Good snowboard!</strong>",
"vendor" => "Burton",
"product_type" => "Snowboard",
"variants" => [
[
"option1" => "Blue",
"option2" => "155"
],
[
"option1" => "Black",
"option2" => "159"
]
],
"options" => [
[
"name" => "Color",
"values" => [
"Blue",
"Black"
]
],
[
"name" => "Size",
"values" => [
"155",
"159"
]
]
]
]
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://your-development-store.myshopify.com/admin/api/2022-10/products.json');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'X-Shopify-Access-Token' => '{access_token}',
'Content-Type' => 'application/json',
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($productData));
$response = curl_exec($ch);
curl_close($ch);