Many store owners need help to build extra functionality into their shop. Or perhaps you’re a developer who has a great idea for a new application (app) 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.
In this article, we'll look at what it takes to get access to a particular shop and make API calls. It is assumed that you have at least some development knowledge. I will be using PHP to present examples, but you can use almost any development language to accomplish all of the functionality discussed.
Build apps for Shopify merchants
Whether you want to build apps for the Shopify App Store, offer private app development services, or are looking for ways to grow your user base, the Shopify Partner Program will set you up for success. Join for free and access educational resources, developer preview environments, and recurring revenue share opportunities.
Sign upTypes of apps
In Shopify, there are two types of apps: Private and Public. Private apps are locked to only one store and are typically for store owners who want to extend the functionality of their own shops. Public apps, as you may have guessed, are for apps that are to be offered to all store owners and not locked to one shop. For instance, all apps listed in theShopify App Storeare public apps. In this article, we will be focusing on public apps, but the technical side for both is the same.
You might also like:4 Tips for Building a Shopify App That Sells.
Before getting started
在本指南中,我们将经历的每一步needed to get your app running and communicating with the Shopify API. Before we continue, you’ll need to do the following (if you haven't already):
1. Register for aShopify Partner Account. It’s free!
2. When you login, go ahead and create your app’s API keyshere. Most of the options are self-explanatory, however when you get to Application Callback URL field you’ll need to enter thedomain namethat 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 tohttp://localhost/for now.
3. After logging in, clickAppsin the left navigation bar and clickCreate App.
Name your app whatever you like. For theApp URL, input the domain that you are working affixed with/install.php. If you’re developing locally on your machine, you’ll want to enterhttp://localhost/install.php. You may need to add a port number if your server is not running on port 80 (e.g.http://localhost:8888/install.php).
4. Once your app is created, navigate to theApp Infotab. UnderWhistlisted Redirect URL(s), you’ll want to add the same domain as in step 3, this time affixed by/generate_token.php.For example, if you’re developing locally on your machine, you’ll want to addhttp://localhost/generate_token.php.
5. Scroll to the bottom of this view and make note of yourAPI keyandAPI secret key. You’ll need these credentials to follow along with the examples.
Download my sample PHP code. All of my 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 more checks and optimizations.
While we're on the topic of URLs, learn more about what acanonical URLis and why they're so important.
You might also like:7 Tips to Maximize Your Use of the Shopify API.
Generating an access token
To start working with store data using the Shopify API, you must be authenticated by the store. That means the shop owner must install and approve your app for certain permissions (eg, creating new products). This is done using a process called OAuth, which is a very secure and common method for communication between applications. It know that it sounds complicated, but don’t worry, anyone can master it quickly.
In this article, we will 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
When a Shopify merchant requests to install your application through the Shopify App Store, a request will be sent to your application URL with theshopparameter appended. The value of theshopparameter will be the merchant’smyshopifydomain name, e.g.http://localhost/install.php?shop=johns-apparel.myshopify.com.
We can mimic this installation request by simply pasting this URL in our browser address bar while our server is running, substituting the value ofshopfor the domain of your Shopify development store.
Step 2: Installation approval
Once you have the store owner's “myshopify.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.See a full list of scopes and their definitions.
{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
Step 3: Capture access code
If the user has approved your installation, they will come back with an authorization code in the URL as a query string. For example:
The part before the "?" matches the$redirect_uri
variable that you had included.
After the "?" are several parameters that should have been included: “code”, "hmac", and “timestamp”. The “code” parameter is your authorization 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 first…
Step 3.b: Validate data
What if a hacker attempts to send a request to your server in the above format? How do you know if it is indeed from Shopify or if it is someone else trying to be malicious? This is why the “hmac" and “timestamp” are provided.By computing the HMAC SHA256 digest, we can compare this against the incominghmacparameter and determine if the request is legitimate.
PHP code example
Let’s 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
By now we 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 endpoint that you can use to “exchange” your access code with the shop’s permanent API token:
/admin/oauth/access_token
PHP code example
In the above code, we’re posting to Shopify’s servers and then storing the OAuth generated token for demo-shop.myshopify.com into the$token
variable. Remember, this is like a password into this shop, so you’ll want to store this token in a very safe place.
Step 5: Make API calls
If you’ve made it to this step, that means that you’ve gone through all of the hard parts! Now, you can make API calls to the shop as long as you’ve been previously approved for the relevant scope. If you’re not, you’ll need to get a new token with the necessary permissions by going through the above steps.
总而言之,每个API调用需要下面的g details:
- Shop API token
- Shop “myshopify.com” URL
- 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
If everything processed correctly, the$products
variable should contain a JSON string that looks something like:
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 programmatically put this ID into a variable so that we can work with this product.
Okay, now we have the aforementioned ID number stored in the$product_id
variable. Imagine 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…
In the$modify_data array
we have all of the required information that we’re sending to Shopify. This array is converted into a JSON in ourshopify_call()
function. For future reference, the requirements for this API call are listed in theShopify 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:
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, I save a lot of time by using a GUI to make API calls. This way I do not have to write a whole bunch of PHP code before I know for sure that the API contains the data that I need. Below are some good options.
- RESTed(Mac) - $3.99
- I’m Only Resting(Windows) - Free
- RequestBin(Web-Based) - Free
You might also like:Marketing Your Shopify App: The App Listing Page.
Practice makes perfect
After a little bit of practice I think 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. I can’t wait to see what you come up with!
If you have any questions, you can find me at theShopify Forumsor post in the comments below.
Want to learn more about building apps for Shopify?Check out our comprehensive list of articles onShopify App Developmentand theShopify API.Learn more at:Shopify Partners