Create product variants using GraphQl API documentation (2024-10). Error occurred while creating variant,Tip: Variable $variants of type [ProductVariantsBulkInput!]!, I referred to the documentation and discussion forum, but did not find the problem. I hope this issue can be resolved in the forum. Thank you very much!
function addProductVariant($shop, $accessToken, $apiKey, $apiSecret, $scopes, $productId, $variables) {
self::initializeContext($apiKey, $apiSecret, $shop, $scopes);
$client = new Graphql($shop, $accessToken);
$variables = [
'productId' => 'gid://shopify/Product/1111',
'strategy' => 'REMOVE_STANDALONE_VARIANT',
'variants' => [
[
'optionValues' => [
'name' => 'Style',
'optionName' => 'Style1'
],
"price"=> 22,
'sku' => 'Jacket01',
'mediaSrc'=>'1.jpg'
],
[
'optionValues' => [
'name' => 'Style2',
'optionName' => 'Style2'
],
"price"=> 22,
'sku' => 'Jacket01-v2',
'mediaSrc'=>'1.jpg'
]
]
];
try {
$response = $client->query(['query' => self::getProductVariantsBulkCreateMutation(), 'variables' => $variables]);
$data = $response->getDecodedBody();
var_dump($data);
$variants = $data['data']['productVariantsBulkCreate']['product']['variants']['edges'] ?? null;
return $variants;
} catch (Exception $e) {
echo $e->getMessage();
}
}
private static function getProductVariantsBulkCreateMutation() {
return <<<'GRAPHQL'
mutation productVariantsBulkCreate($productId: ID!, $variants: [ProductVariantsBulkInput!]!) {
productVariantsBulkCreate(
productId: $productId,
variants: $variants ) {
product {
id
title
variants(first: 10) {
edges {
node {
id
title
price
sku
availableForSale
}
}
}
}
userErrors {
field
message
}
}
}
GRAPHQL;
}
