Skip to content

Frontend JavaScript

Dylan Fisher edited this page Oct 26, 2022 · 3 revisions

Before loading your application's JavaScript, define the Shopify domain and storefront access token in your application's layout file.

<script>
  window.ForestShopify = window.ForestShopify || {};
  ForestShopify.domain = '<%= ENV['FOREST_SHOPIFY_DOMAIN'].presence || Rails.application.credentials[:shopify_domain] %>';
  ForestShopify.storefrontAccessToken = '<%= ENV['FOREST_SHOPIFY_STOREFRONT_ACCESS_TOKEN'].presence || Rails.application.credentials[:shopify_storefront_access_token] %>';
</script>

Set up the Shopify JavaScript client, using the js-buy-sdk.

// https://shopify.github.io/js-buy-sdk/

$.ajaxSetup({ cache: true });

App.pageLoad.push(function() {
  // TODO: Update your app to specify a specific API version before deploying to production.
  // e.g. https://sdks.shopifycdn.com/js-buy-sdk/2.17.0/index.unoptimized.umd.min.js
  $.getScript('https://sdks.shopifycdn.com/js-buy-sdk/v2/latest/index.umd.min.js', function(data, textStatus, jqxhr) {
    $(document).trigger('app:shopify:ready');
  });
});

$(document).on('app:shopify:ready', function() {
  // Initializing a client to return content in the store's primary language
  App.shopify.client = ShopifyBuy.buildClient({
    domain: ForestShopify.domain,
    storefrontAccessToken: ForestShopify.storefrontAccessToken
  });

  // Find or create a checkout
  var checkoutId = Cookies.get('forest_shopify_checkout');
  var hasCaughtError = false;
  var createCheckout = function() {
    App.shopify.client.checkout.create().then(function(checkout) {
      App.shopify.checkout = checkout;
      Cookies.set('forest_shopify_checkout', App.shopify.checkout.id, { expires: 365 });
      $(document).trigger('app:shopify:checkout');
    }).catch(function(error) {
      console.warn('Error creating Shopify checkout', error);
    });
  };

  if ( checkoutId ) {
    App.shopify.client.checkout.fetch(checkoutId).then(function(checkout) {
      App.shopify.checkout = checkout;
      $(document).trigger('app:shopify:checkout');
    }).catch(function(error) {
      // In case of error, try to create a new checkout session
      createCheckout();
    });
  } else {
    createCheckout();
  }
});

Add an items to the cart

// https://shopify.github.io/js-buy-sdk/
// https://shopify.dev/docs/themes/ajax-api/reference/cart

$(document).on('click', '.add-to-cart', function(e) {
  e.preventDefault();

  var id = $(this).attr('data-id');

  var lineItemsToAdd = [
    {
      variantId: id,
      quantity: 1
    }
  ];

  // Add an item to the checkout
  App.shopify.client.checkout.addLineItems(App.shopify.checkout.id, lineItemsToAdd).then(function(checkout) {
    App.shopify.checkout = checkout;
    // TODO: code to show off your loaded cart
    $('header').append('<p>Added to cart. <a href="' + App.shopify.checkout.webUrl + '">Click here</a> to check out.</p>')
  });
});

Clone this wiki locally