Generate a Shopify API Token
Store owners often ask for help to build extra functionality into their shop. Or, if you’re a developer who has a great idea for a new application that would help store owners sell better. Either way, you’ll probably need to use Shopify’s API. The API allows you to do things like downloading a shop’s product inventory and modifying the shop’s theme.
We’ll examine what it takes to get access to a particular shop and make API calls in this article. You should have some development knowledge. We’ll use PHP to present examples, but you can use almost any development language to accomplish all of the functionality discussed.
TYPES OF APPS
Shopify uses two different type apps, Private and Public. Private apps are locked to only one store and are for store owners who want to extend the functionality of their own shops. Public apps, are for apps that are to be offered to all store owners and not locked to one shop. For example, all apps listed in the Shopify App Store are public apps. We will be focusing on public apps, but the technical side for both is the same.
BEFORE GETTING STARTED
We’ll go through each step that is needed to get your app running and communicating with the Shopify API. However; before going any further, you’ll need to do the following:
1. Register for a Shopify Partner Account. It’s free!
2. When you login, create your app’s API keys here. Most of the options are self-explanatory, however; when you get to Application Callback URL field, you’ll need to enter the domain that you’re working on. Shopify will only send tokens to this domain. For instance, if you’re working on your local computer you may want to set this to https://localhost/ for now.
3. After creating your app, grab your API keys. You’ll need both strings in order to follow along with the examples in this guide:
Download the sample PHP code from here. All of the sample code below is taken from these scripts. The sample code is written in a procedural style to make it easy to learn the core concepts. In a production environment, you’ll certainly want to add ore checks and optimizations.
Generating an Access Token
To start working with store data using the Shopify API, you must be authenticated by the store. This means the owner must install and approve your app for certain permissions(i.e., creating new products). This is done using a process called OAUTH, which is a very secure and common method for communication between applications. This sounds complicated, but anyone can master it quickly.
We’ll use OAUTH to build a special URL where the user can approve your app and finally generate a special token that you can use to access the relevant shop via the API going forward. Below is a flowchart outlining all of the steps necessary to accomplish this.
Step 1.: Gathering Shop Info
Shopify needs to know which shop you want to install your app on, so lets start by asking the user.
Step 2.: Installation Approval
Once you have the store owners “my shopify.com” URL, you’ll need to redirect the user to a URL where they can approve your app. The format of this URL is as follows.
https://{shop}myshopify.com/admin/oauth/authorize?client_id={api_key}&scope={scopes}&redirect_uri={redirect_uri}
{shop}
The subdomain “myshopify.com” URL that the user gave you.
{api_key}
Your API key that was provided to you, as per above.
{scopes}
This is a list of permissions that you’re asking the store owner to accept. For this example we will want the ability to read orders and modify products so I am requesting read_orders and write_products. A full list of scopes and their definitions are listed here.
{redirect_uri}
Where the user should be sent to next. This is the URL for the script that will generate the token, as described in step 3 below:
PHP Code Example
//Set variables for our request
$shop = “demo-shop”;
$api_key = “1r30mrvCFMfq2DLGuIXyY2veEJVgTtdd”;
$scopes = “read_orders,write_products”;
$redirect_uri = “https://localhost/generate_token.php”;
// Redirect
header(“Location: ” . $install_url);
die();
Step 3.: Capture Access Code
If the user has approved your installation, they will come back with an access code in the URL as a query string.
https://localhost/generate_token.php?code={authorization_code}&signature=da9d83
The part before the “?” matches the $redirect_url variable that you had included.
After the “?” are three parameters that should have been included: “code”, “signature”, and “timestamp”. The “code” parameter is your access code that you will use for the part of the OAUTH process. The other two parameters are used for validating that the request is indeed from Shopify. Let’s work on that.
Step 3.b: Validate Data
What if a hacker attempts to send a request to your server. How do you know if it is indeed from Shopify or if it is someone else trying to be alicious? This is why the “signature” and “timestamp” are provided. With a little MD5 encryption, you can run this check.
PHP Code Example
// Set variable for our request
$shared_secret = “TBB5wltKarRtkn5mUVZck9RxHePNN6Jo”;
$code = $Get[“code”];
$timestamp = $_GET[“timestamp”];
$signature_data = $_GET[“signature”];
//Compile signature data
$signature_data = $shared_secret . “code=” . $code . “shop=”. $shop . “.myshopify.comtimestamp=” . $timestamp;
//Use signature data to check that the response is from Shopify or not
if (md5($signature_data) === $signature) {
// VALIDATED
} else {
//NOT VALIDATED – Someone is being shady!
}
Keep going by using this “code” value to get an access token for the shop. We will do so by running our first API call.
Step 4: Exchange Access Code for the Shop Token
We now have everything that we need to generate the app token: your app API key, your app secret key credentials, and the access code.
Shopify has a special API call endpoing that you can use to “exchange” your access code with the shop’s permanent API token:
/admin/oauth/access_token
// Set variables for our request
$shop = “domo-shop”;
$request_headers = array(
“Content-type” => “application/json”, // Tell Shopify that we’re expect
“client_id” => “1r30mrvCFMfq2DLGuIXyY2veEJVgTtDD”, // Your app API key
“client_secret” => “TBB5wltKarRtKn5mUVZck9RxHePNN6Jo”, // Your app create
“code” => $_Get[“code”] // Grab the access key from the URL
);
// Call our Shopify function
$shopify_response = shopify_call(NULL, $shop, “/admin/oauth/access_token”, $response
// Convert response into a nice and simple array
$shopify_response = json_decode($shopify_response[‘response’], TRUE);
//Store the response
$token = $shopify_response[‘access_token’];
Step 5: Make API Calls
If you’re this far, that means that you’ve gotten through the hard parts! Now, you can make API calls to the shop as long as you’ve been previously approved for the relevant scop. If you’re not, you’ll need to get a new token with the necessary permission by going through the above steps.
To summarize, each API call will need the following details:
1. Shop API token
2. Shop “myshopify.com” URL
3. The API endpoint for which to call along with any special parameters.
In this guide one of the permissions (scopes) we’ve requested access to is reading product information, let’s try that now. The endpoint for that you’ll need is /admin/products.json
PHP Code Example
// Set variable for our request
$shop = “demo-shop”;
$token = “SWp~I7gKAckA~F9!fAvv9yrI3grYsSkw”;
$query – array(
“Content-type” => “application/json” // Tell Shopify that we’re expect
);
// Run API call to get all products
$products – shopify_all($token, $shop, “/admin/products.json”, array(), “GET”
// Get response
$products – $products [“response”];
If everything processed correctly, the $products variable should contain a JSON string that looks something like:
{
– products: {
– {
body_html: “Testing Title“,
created_at: “2014-09-30T01:00:58-04:00”,
handle: “test”,
id: 370733088
product_type: “test”,
published_at: “2014-09-30T01:00:52-04:00”,
published_scope: “global”,
template_suffix: null,
title: “Test”,
updated_at: “2014-09-30T01:00:58:04:00”,
vendor: “vendor-test”,
tags: “”,
+ variants: [ – ],
– options: [
– {
id: 438045328
name: “Title”,
position: 1,
product_id: 370733088
}
[,
images: [ ]
{
]
}
In the returned JSON, I have only one product, which is ID number 370733088. Let’s assume that we want to modify this product, so continuing with this code, we will programtically put this ID into a variable so that we can work with this product.
// Convert product JSON information into an array
$products = json_decode($products[‘response’], TRUE);
// Get the ID of the first product
$product_id = $products[‘products’] [0] [‘id];
Now we have the aforementioned ID number stored in the $product_it variable. Imageine that I want to modify this product’s title. The existing title, “test”, isn’t very user friendly after all. You’ll need to use that $product_id variable so that Shopify knows which product you’re modifying.
// Modify product data
$modify_data = array(
“id” => array(
“title => “My New Title”
)
);
// Run API call to modify the product
$modified_product = shopify_call($token, $shop, “/admin/products/” . $product_
// Storage response
$modified_product_response = $modified_product[‘response’];
In the $modify_data array we have all of the required information that we are sending to Shopify. This array is converted into a JSON in our shopify_call() function. For future reference, the requirements for this API call are listed in the Shopify API docs. You may also notice that our method of data transaction is PUT. This tells Shopify that we’re modifying data as opposed to downloading or deleting it.
If this API call was successful, you’ll get back a JSON string of your updates in the $modified product response variable:
{
– product: {
body_html: “,b>Testing Title”,
created_at: “2014-09-30T01:00:58-04:00”,
handle: “test”,
id: 370733088,
product_type: “test”,
published_scope: “global:,
template_suffix: null,
title: “My New Title”,
updated_at: “2014-09-30T11:44:43-04:00”
vendor: “vendor-test”,
tags: “”,
+ variants: […],
– options: [
– {
id: 438045328,
name: “Title”,
position: 1,
product_id” 370733088
}
],
images: [ ]
}
}
As you can see the product title has been updated to match what we sent in the $modify_data variable. Shopify has made their API to be very predictable and consistent. This means that going forward, you can work with most of the API endpoints in a similar fashion.
Making API Calls on the Fly
When I develop for Shopify, you can save alot of time by using a GUI to make API calls. This way you don’t have to write a whole bunch of PHP code before you know for sure that the API contains the data that you need. Some good options are RESTed(Mac) – 3.99, I’m Only Resting (Windows) – Free, RequestBin (Web-Based) – Free.
Conclusion
After a bit of practice, you’ll agree that the Shopify API is both flexible and easy to access. So much can be done with it and it is only expanding in support for various endpoints.
Let’s see what you can come up with!
Recent Projects
Tech-savvy and innovative, Marina is a full-stack developer with a passion for crafting seamless digital experiences. From intuitive front-end designs to rock-solid back-end solutions, she brings ideas to life with code. A problem-solver at heart, she thrives on challenges and is always exploring the latest tech trends to stay ahead of the curve. When she's not coding, you'll find her brainstorming the next big thing or mentoring others to unlock their tech potential.