Shopify App Development in Vanilla PHP: Creating Products w/ GraphQL

Over the past few years, REST has become the only way for designing web APIs. However, there are things that make REST very inflexible. For example, you cannot control how much data you can retrieve or you can’t specify the only data that you wish to retrieve, etc.

This happens in Shopify app development as well. If you want to get a product using REST API, all of the data about your products will be sent to you. This makes REST very heavy and slow to use.

So, that’s why GraphQL was created, to cope with the need for more flexibility and efficiency.

But, we’re not going to focus on the difference between REST and GraphQL. Instead, we’re going to learn how to create products using GraphQL mutations and vanilla PHP.

Video Tutorial

If you prefer watching video tutorials, then the video below is for you.

Otherwise, feel free to keep reading the content below.

Getting Started

If this is your first time learning how to make Shopify apps using vanilla PHP, then we highly recommend reading through our guide here. We also have a ton of videos covering Shopify app development, so before you proceed, make sure that you have a local web server and a Shopify app installed in your development store.

Before we start using GraphQL mutations in PHP, we need to create a function that will allow us to make API calls.

GraphQL API Call Function

Create a new PHP file called functions.php and copy the following code:

<?php


function graphql($token, $shop, $query = array()) {
	$url = "https://" . $shop . "/admin/api/2021-07/graphql.json";

	$curl = curl_init($url);
	curl_setopt($curl, CURLOPT_HEADER, TRUE);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
	curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE);
	curl_setopt($curl, CURLOPT_MAXREDIRS, 3);
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);


	$request_headers[] = "";
	$request_headers[] = "Content-Type: application/json";
	if (!is_null($token)) $request_headers[] = "X-Shopify-Access-Token: " . $token;
	curl_setopt($curl, CURLOPT_HTTPHEADER, $request_headers);
	curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($query));
	curl_setopt($curl, CURLOPT_POST, true);

	$response = curl_exec($curl);
	$error_number = curl_errno($curl);
	$error_message = curl_error($curl);
	curl_close($curl);

	if ($error_number) {
		return $error_message;
	} else {

		$response = preg_split("/\r\n\r\n|\n\n|\r\r/", $response, 2);

		$headers = array();
		$header_data = explode("\n",$response[0]);
		$headers['status'] = $header_data[0]; 
		array_shift($header_data);
		foreach($header_data as $part) {
			$h = explode(":", $part, 2);
			$headers[trim($h[0])] = trim($h[1]);
		}

		return array('headers' => $headers, 'body' => $response[1]);

	}
    
}
Code language: PHP (php)

This function above will allow you to send GraphQL queries to the Shopify GraphQL endpoint. You just need to provide your access token, Shopify store domain, and the query/mutation.

Alright, so now that we have the function to make GraphQL API calls, we can start and set up our index file.

The Index File

Create a new PHP file in your project and make sure it’s your index file so name it index.php. Once the file is created, you can copy the following code:

<?php
require_once( "functions.php" );
$shop_url = $_GET['shop'];
$access_token = 'shpca_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';

?>
Code language: PHP (php)

In the code above, we referenced the functions.php so that we can use the graphql() function.

Now, make sure that you have your access token in the $access_token variable. If you don’t know how to generate an access token, then watch our tutorial here.

Let’s assume you already have your access token, we can now proceed and use the GraphQL function to create products.

Creating Products using GraphQL Mutations

In the same file, create a new variable and use the function graphql() like what we did below.

<?php
require_once( "inc/functions.php" );
$shop_url = $_GET['shop'];
$access_token = 'shpca_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';

$mutation = graphql($access_token, $shop_url, array());
?>
Code language: PHP (php)

In the 3rd argument, we applied an empty array, that array is where you’re going to apply the query/mutation.

So let’s create a new variable and call it $query or whatever you want. Then, in this variable, we will create an array and its key SHOULD be set to query. Again, the key SHOULD be set to query and not something else. Then, we’re going to use that variable in the 3rd argument of the graphql() function.

<?php
require_once( "inc/functions.php" );
$shop_url = $_GET['shop'];
$access_token = 'shpca_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';

$query = array("query" => '');
$mutation = graphql($access_token, $shop_url, $query);
?>
Code language: PHP (php)

Next, let’s use mutations.

Update the array to the following:

<?php
require_once( "inc/functions.php" );
$shop_url = $_GET['shop'];
$access_token = 'shpca_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';

$query = array("query" => '
	mutation {
		productCreate(
			input: {
				title: "Vanilla PHP & GraphQL"
				descriptionHtml: "<p>I am created using GraphQL!</p>"
			}
		) {
			product {
				id
				title
			}
		}
	}
');

$mutation = graphql($access_token, $shop_url, $query);
?>
Code language: PHP (php)

In this mutation, we used the productCreate field and this field requires us to provide an argument input so there we provided a title and a descriptionHtml. After the product is created, the mutation will then return a field called product and in that field, we create retrieve data about the product like its id, title, tags, images, etc. To learn more about the product field, click here.

That’s it! If you run your app, it should give you the following response.

{
	"data": {
		"productCreate": {
			"product": {
				"id": "gid:\/\/shopify\/Product\/1234567890"
				"title": "Vanilla PHP & GraphQL"
			}
		}
	}
}
Code language: JSON / JSON with Comments (json)

1 Comment.

Leave a Reply