Skip to main content

How to integrate Shopify with your website

<< Back to listing

What is Shopify?

In a nutshell, Shopify is an e-commerce platform allowing users to market and sell their products online. It accommodates all levels of users from those who make just a handful of sales each month to those shipping thousands of items per week. It is designed to be a one-stop-shop for online selling – its a marketing tool, a stock management system, a payment gateway and a fulfilment service all rolled into one. In fact, when you also consider the huge range of add-ons built by external developers offering all manner of custom functionality, there is very little the platform can’t do.

How can it be used?

When you first sign up with Shopify, their assumption is that you want to host your new online store with them. You’ll either choose a theme from their selection, employ one of their approved experts to build one for you or, if you’re feeling really brave, you’ll jump into the template editor and create your own. There is a fourth option though, one that is rarely mentioned but is no less viable, namely hosting the site externally on your own hardware.

Here at Dynamo6 we’re used to building sites from scratch – we use a wide range of tools and techniques which, coupled with our in-depth knowledge of hosting infrastructure, allows us to build beautiful, reliable, scalable websites and applications. It doesn’t make sense for us to host our sites on Shopify’s platform and, in doing so, constrain ourselves to live by their rules. We like to be in control – as they say though “with great power comes great responsibility” – if things go wrong we’ll have to fix them ourselves. But we’re cool with that; we know what we’re doing.

Integrating Shopify to get the best of both worlds

So the next question is, how do we integrate Shopify with a website which resides on external hosting? In the past, the answer was “with difficulty”. There was no official support for this and no documentation on the Shopify site. Various developers proposed a range of solutions on forums and blogs but they all had limitations and were often, for want of a better word, a bit hacky. 

Finally, in early 2016, a knight in shining armour galloped over the horizon in the form of the JavaScript Buy SDK. This lightweight javascript library allows developers to integrate Shopify’s ecommerce platform into any new or existing website. It was developed in conjunction with Shopify and uses their official API to allow retrieval of product information, creation of shopping carts and the ability to send users directly through to the Shopify checkout.

So lets get started. First of all we need to pull the SDK code into our page by adding the following tag. We’re using v0.7 at present as its the latest stable release.

<script src="http://sdks.shopifycdn.com/js-buy-sdk/v0/latest/shopify-buy.umd.polyfilled.min.js"></script>

 

Next we need to pull all the product info from Shopify and display it on our page.

				
// initialise an api client
var shopClient = ShopifyBuy.buildClient({
    // you can generate the creds you need by following Shopify's Getting Started guide
    accessToken: 'xxxxxxxxxxxxxxxxxx',
    domain: 'your-store-name.myshopify.com',
    appId: '6'
});

// create a cart - note that promises are widely used by the SDK
var objCart = null;
shopClient.createCart().then(function(newCart) {
    // store a reference to the cart
    objCart = newCart;
});

// pass your collection_id to pull all product information from Shopify
var arrProducts = null;
shopClient.fetchQueryProducts({
    collection_id: 'xxxxxxxxxx'
}).then(function(products) {
    // store a copy of the data received
    arrProducts = products;

    // loop through and display each product on the page so the user can make their selection
    arrProducts.each(function(i, e) {
        // ...
        // the detail of this is up to you, but for this example i'm going to assume each 
        // product row  has data attributes containing the product and variant IDs
        // and contains a quantity box e.g. <input type="number" name="quantity" value="0">
        // ...
    });
});

 

Next, we need to hook up the checkout button to add each of the chosen products to the Shopify cart we created earlier.

				
// add the onclick event
$('.js-btn-checkout').on('click', function() {
  // loop through all the products in your page and find the ones the user has chosen 
  $('.js-product').each(function(i, e) {
    var $elProduct = $(e),
        $elQuantity = $elProduct.find(input[name=quantity]);

    // how many of this product does the user want to buy?
    if ($elQuantity.val() > 0) {
      var iProductID = $elProduct.data('product-id'),
          iVariantID = $elProduct.data('variant-id');

      // lookup the product in our products array and add it to the cart
      for (var iLoop in arrProducts) {
        if (iProductID == arrProducts[iLoop].id) {
          var arrVariants = arrProducts[iLoop].variants;

          // this is the right product - now loop through variants to find the right one
          for (var jLoop in arrVariants) {
            if (iVariantID == arrVariants[jLoop].id) {

              // we found the one they wanted - now, add to cart
              iBeingAdded += 1;
              objCart.createLineItemsFromVariants({
                variant: arrVariants[jLoop],
                quantity: $elQuantity.val(),
              }).then(function(updatedCart) {
                // indicate this one was added successfully
                iBeingAdded -= 1;
                // are we ready to go?
                readyToCheckout();
              });

              // break out of the variant loop
              break;
            }
          }

          // break out of the product loop
          break;
        }
      }

      // continue looping through the rest of the products ...
    });
  });

 

There’s one last thing we need to do here – forward the user to the checkout. However, because the API adds line items to the cart asynchronously, we’re not necessarily going to know when all the products have been added. That’s where our readyToCheckout function comes in.

				
// create a counter variable which is incremented immediately before the 
// createLineItemsFromVariants call then subsequently decremented inside
// the callback section of the promise that was generated
var iBeingAdded = 0;
var readyToCheckout = function() {
    // if everything we've tried to add has now been added (i.e. the value of iBeingAdded has been 
    // incremented then successfully decremented again the same number of times), send the user to the checkout
    if (iBeingAdded === 0) {
        document.location.href = objCart.checkoutUrl;
    }
};

 

And that’s pretty much it – job done! A year ago, a simple integration like this would have been pretty much impossible but the Javascript Buy SDK has saved the day. OK, it’s not perfect; a few features here and there are currently missing (most notably the ability to send custom properties for each order line) but it’s being actively developed and is gaining popularity quickly. This can only be a good thing – for us, for our clients and for Shopify. Ultimately, the easier they make it for developers to integrate Shopify with their platform, the more likely we are to recommend it as a solution to our customers.

If you’re interested in selling your products online and would like to know more about working with Dynamo6, please contact us.

 

UPDATE: The Buy SDK has come a long way since this article was first written; line order custom properties are now trivial to add and the library as a whole feels a lot more robust. Unfortunately, due to the rapid evolution of the product some of the code provided above will no longer work. Thankfully Shopify have written a handy migration guide which details the various changes you’ll need to make to move from v0.7 to v1