Issues with creating a product with php

Issues with creating a product with php

Samir-Almeida
Visitor
1 0 0

Hello everyone,

 

I tried using GraphQL Admin API, with PHP, to create a product on my store with my code from my computer, yet the code that is presented on the website (https://shopify.dev/docs/api/admin-graphql/unstable/mutations/productSet) has a syntax error. And because of that my code is not working. 

 

If someone has already done a code that is able to create a product on the shopify store, from a PHP code i would love to know how you did it.

Reply 1 (1)

SomeUsernameHe
Shopify Partner
515 57 109

Go ahead and this corrected and complete PHP code:

<?php

use Shopify\Clients\Graphql;

// Replace these variables with your own values
$storeUrl = "your-development-store.myshopify.com";
$accessToken = "your-access-token";

// Initialize the GraphQL client
$client = new Graphql($storeUrl, $accessToken);

// Define the GraphQL mutation query
$query = <<<QUERY
mutation createProductAsynchronous(\$productSet: ProductSetInput!, \$synchronous: Boolean!) {
  productSet(synchronous: \$synchronous, input: \$productSet) {
    product {
      id
    }
    productSetOperation {
      id
      status
      userErrors {
        code
        field
        message
      }
    }
    userErrors {
      code
      field
      message
    }
  }
}
QUERY;

// Define the variables for the mutation
$variables = [
  "synchronous" => false,
  "productSet" => [
    "title" => "Winter hat",
    "productOptions" => [
      [
        "name" => "Color",
        "position" => 1,
        "values" => [
          ["name" => "Grey"],
          ["name" => "Black"]
        ]
      ]
    ],
    "variants" => [
      [
        "optionValues" => [
          ["optionName" => "Color", "name" => "Grey"]
        ],
        "price" => 79.99
      ],
      [
        "optionValues" => [
          ["optionName" => "Color", "name" => "Black"]
        ],
        "price" => 69.99
      ]
    ]
  ]
];

// Execute the query
$response = $client->query([
  "query" => $query,
  "variables" => $variables
]);

// Check the response for errors
if (isset($response['data']['productSet']['userErrors']) && !empty($response['data']['productSet']['userErrors'])) {
  foreach ($response['data']['productSet']['userErrors'] as $error) {
    echo "Error: " . $error['message'] . " (Field: " . $error['field'] . ", Code: " . $error['code'] . ")\n";
  }
} else {
  $operation = $response['data']['productSet']['productSetOperation'];
  echo "Product Set Operation ID: " . $operation['id'] . "\n";
  echo "Status: " . $operation['status'] . "\n";
}

?>
Have I helped? Consider putting coffee in my mouth!
Buy Me a Coffee