How to Make the Most of the Shopify Embedded App SDK

How to Make the Most of the Shopify Embedded App SDK

Shopify Embedded App SDK

The Shopify app store allows merchants to extend the function of their store with hundreds of third party apps. Whether you are a frontend developer or looking to build apps for the app store, you will undoubtedly encounter some Shopify application code while working with the platform. While previously shop owners would have to be redirected away from their shop admin to access third party apps, the Shopify Embedded App SDK that was released a couple of years ago allows shop owners to access their apps directly in their shop's admin interface.

While using the Embedded App SDK is not a requirement, you should probably take advantage of it if you are building a Shopify app. Here at Sovi Creative, we recently decided dig into the Shopify API and release our first app. After doing a bit of research, we decided that using the Embedded App SDK was the only way to go. There are several reasons why it is advantageous, including:

  1. A better user experience for app users, meaning a happier customer and a better chance for a good review.

  2. Your application will be viewed favourably in the app store, giving you preferential ranking.

As you can see, there's really very few reasons not to use the Embedded App SDK. Maybe you haven't even thought about using it for your apps, or maybe you've wanted to but haven't invested the time in getting familiar with it. In this blog post, I'm going to go through the process of creating an embedded app from start to finish, and hopefully by the end those won’t be excuses anymore!

While I will try to be as comprehensive as possible throughout this article, I will assume that you are already familiar with the Shopify API and OAuth process. If not, you can check out this great article published on the Shopify Partner Blog that takes you through the process.

All of the code you will see here is written in Javascript (Node.js for the backend), and is part of a sample app created for this article, which is avaible on github here. I recommend you clone this repository and follow along for a better understanding.

You might also like: How to Build a Shopify App in One Week

Authentication

The OAuth authentication process for an embedded app is the same as the non-embedded counterpart, with some small caveats. To start the process, the client must be redirected from the application to their Shopify store admin, where they can authorize the installation. Since we’re using the embedded app SDK, the app is loaded inside an iframe. For security reasons, Shopify sends a special header, X-Frame-Options=DENY, which prevents the admin from loading in an iframe. To work around this, our app renders a page that contains only the following javascript:

The javascript window.top.location.href ensures we are doing the redirect in the parent window, not in the iframe. Once the user approves, they are redirected back to the path set as the redirect_uri parameter. Here Shopify supplies us with several parameters in the query string. The authorization code is exchanged for the access token, which can be permanently stored for the client to make API requests on their behalf as long as they have the app installed.

PRO TIP: Validation

While the blog post I mentioned earlier does a great job at explaining the process of data validation, as of June 2015 Shopify no longer supports the use of MD5 signatures. All Shopify applications must now validate requests using an SHA256 HMAC. The validation process is relatively simple, but if you have never done it before it can be a little intimidating.

The way HMAC validation works is Shopify generates a piece of data using your app's secret key, which it knows, and some data that it is going to send. This piece of data is called an HMAC. There are many different algorithms which will create a HMAC given some data, but in this case, the SHA256 algorithm is used. Shopify then sends this computed HMAC value along with the request. Our job as application developers is to use the same secret and sent data (or "message") to compute our own HMAC. If our HMAC matches the one sent by Shopify, we know the request is coming from Shopify.

To complete the validation, three pieces of info are required.

Message

The message is some data that was sent in the request we are validating. Understanding the correct message to use is probably the most difficult part to get right. In this case, take all the query parameters as a map:

{

code: 2253d7r40ef185e3gf4614hte35gwr4b,

hmac: d7wer343y3452re3ssdfd4613asdr5t,

shop: shop-name.myshopify.com,

signature: 345kfw90eofkf23okf23rf2owfh92,

timestamp: 114636345,

}

Then delete the HMAC and signature, leaving just the code, shop and timestamp, in that order. The next step is to convert is into a querystring format.

"code={code}&shop={shop}&timestamp={stamp}"

In Node we can do this simply using querystring.stringify(), and most languages/frameworks should have a similar convenience method available.

Client secret

This is the secret key provided in your application settings page.

HMAC

The HMAC is what you are going to use the above two pieces of data to create. Shopify also provides an HMAC as a query parameter in their request.

Once you have this data, generate an hmac hash and compare it to the one sent by Shopify, if they do not match, reject the request. Below is an example of how to do this in Node:

The line crypto.createHmac('sha256', config.oauth.client_secret).update(message).digest('hex'); is where the HMAC is generated, and then subsequently compared to the Shopify HMAC. Notice too how we make a copy of req.query which contains all the query parameters in a Javascript object, then delete the signature and the hmac keys to get the values used for the message.

Initialization

Now that the client has installed the app, we have to make sure that it is embedded in the Shopify admin, and then we can take advantage of all the features provided with the Embedded App SDK. The first step is to initialize the embedded app. To do so, we’ll place the following two script tags just under the head tag.

The first script tag loads app.js, which contains all the Javascript for the embedded app. The second script tag initializes the ShopifyApp object provided by the previous script.

To initialize the app, two pieces of info are required: the application’s API key and the full “myshopify.com” url of the client’s store. Both are provided to the template from the application’s backend. This script must be added to every page you want to use with the Embedded App SDK.

TIP: ShopifyApp.init will force the app to load in the admin iframe if it detects otherwise. For convenience during development, you can add forceRedirct: false to prevent this action.

Now, we have our embedded app up and running, ready to make API calls. From here you can build the app as you normally would, and it will all run inside the client’s shop admin. However, the ShopifyApp object provides a variety of amazing and easy to implement features that we can take advantage of to help give your app a more seamless integration with the Shopify Admin. To get a feel for some of the features, let’s make a simple application. Our app will have a homepage, which simply displays links to two more pages, one to view all products and one to add a new product.

TIP: If you’re developing on localhost and can’t see your embedded app, you may have to change your browser setting to “Allow Unsafe Scripts.” Here’s an example of where to find this option in Chrome:

You might also like: 8 Merchant-Driven Ideas For Your Next Shopify App

Configuring the top bar

Alright, so the home page is really simple, we just added some html with anchor tags linking to our other pages:

But let’s use this page to take a look at some of the methods we can use with the ShopifyApp object. First we call the ShopifyApp.ready() method with a callback where we’ll write all our code that uses this object (Think of it like the $(document).ready() function provided by jQuery). This method will wait until the ShopifyApp object is initialized before it executes our code.

We can initialize the bar using the ShopifyApp.Bar.initialize function, which we pass an object with our configuration.

The first two basic things we can add to the bar is the title, and the path to a logo image that will display in the top left of the bar.

Buttons

The Bar supports three types of buttons, primary, secondary, and tertiary, the difference being in the color and placement of the buttons. If the href parameter is included, the button will act as a link. Adding target:new will make the link open in a new window. If instead a callback is provided, clicking the button will call that function. Additionally, buttons can be dropdowns if the type and set to dropdown and an array of “links” (button objects) is provided.

Modals

The ShopifyApp.openModal takes a url as a parameter and loads it into a modal as an iframe. A modal can be opened from anywhere in the app, but in the code snippet above I trigger the opening of the modal in a button in the top bar. Let’s create a route in the backend that renders a corresponding template:

Then, when the button is clicked, we trigger this modal opening:

Pagination

Now that we have the hang of the top bar, let’s create the product listing page to show how the Embedded App SDK and the API can really work together. First, let’s create a template for our products page, and add in the pagination.

Pagination is added to the top bar just like buttons, with options for specifying the next and previous links. Here, we link to the same /products page, only changing the “?page=” query parameter. This parameter lets our backend know what page a client is on so it can make the appropriate request to the Shopify API. In the Node backend, we’ll create a route /products.

Here we make a GET request to the Shopify API products endpoint. We use the query parameter “?limit=5“ to specify 5 products per page. This means the request will only return 5 products, but we can also specify the page of products to return by adding page={page_number} to our request, so we get different products depending on the page number. The route knows what page number to add to the request because it too has the page query parameter, which is accessed with req.query.page. We also calculate the value of the previous and next page, which is supplied to the top bar pagination buttons in the frontend template.

Flash notices

Finally we will take a look at flash notices. Any store owner will be very familiar with these notices the slide up from the bottom of the window, so it’s a great way to provide the user with feedback for actions such as saving and submitting forms. First we can create a route /add_product. Without going into too much detail, this route takes data about the new product from the request body (from the form we’ll create next) and sends a POST request to the Shopify API. Let’s add another template, add_product.ejs, that will allow the client to upload a product to their store. First we’ll create a simple html form.

To submit this form, we’ll use jQuery.

Here we submit the form in an ajax request. The jQuery.ajax() method takes a success and an error callback, one of which will be called once the request is complete depending on the response. This is a good place to place the flash notices. In the success callback we call ShopifyApp.flashNotice("Product Uploaded Successfully") and in the error callback we’ll add ShopifyApp.flashError("Warning: Product Uploaded Failed").

In conclusion

In this article, we have gone over the embedded app authentication process, initializing the frontend Javascript API, and then touched upon a number of methods and features that the Embedded App SDK provides. Although we covered a lot, there’s still plenty more that the Embedded App SDK offers for you to discover on your own. Now that you have the idea, you can take a look over the Docs and get familiar with features we didn’t look at in this article. Happy coding!

You might also like: Getting Your App in the Shopify App Store

About the Author

Anthony is a full stack web developer from Toronto, Ontario. He currently is works as Application Development Lead for SOVI Creative, an innovative ecommerce agency specializing in Shopify design, development and marketing.

Grow your business with the Shopify Partner Program

Learn more