skip to Main Content

I am working on connecting to the Shopify API however the way it is structured for access is apikey:[email protected]

Apps script however will not allow you to use a URL with the login credentials for the UrlFetchApp.fetch function 12345:[email protected] and I seem unable to pass the information through successfully via the basic headers.

function shopify_connect() {

  var url = "https://storename.myshopify.com/admin/products.json/GET";
  var apikey = '12345';
  var password = '67890';

  var headers = {
    "User-Agent" :"[email protected]",
    "Authentication" : 'Basic ' + Utilities.base64Encode(apikey + ':' + password)
  }

  var options = {
    "headers": headers,
  }

 var response = UrlFetchApp.fetch(url, options);
}

When I log the output from response, it appears that I am getting to the login HTML however never passing beyond that.

Any help in clarifying this access method would be greatly appreciated.

Logger Response:

[19-01-01 12:09:54:516 EST] <!DOCTYPE html>
<html lang="en">
<head>

  <meta charset="utf-8" />
  <title>Shopify &raquo; Please log in</title>
  <meta name="referrer" content="never" />
  <meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<link rel="icon" sizes="192x192" href="//cdn.shopify.com/s/assets/touch-icons/touch-icon-192x192-840b11274adbc510a1db23976759bd31ceee84ddbb36478d494a3a2cf19b5ae6.png" />
  <link rel="shortcut icon" type="image/x-icon" href="//cdn.shopify.com/s/assets/favicon-4425e7970f1327bc362265f54e8c9c6a4e96385b3987760637977078e28ffe92.png" />
<link rel="apple-touch-startup-image" href="//cdn.shopify.com/s/assets/touch-icons/mobile-startup-564eed49b6c483b80796f529e05b4bf1d54e9cd9beeb0bb89b10d3c6a2282ea6.png" />
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="//cdn.shopify.com/s/assets/touch-icons/icon-114x114-precomposed-79d1c57f01b233f016319dc4048d90524e9ce252c058a306ef9db2216ab26911.png" />
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="//cdn.shopify.com/s/assets/touch-icons/icon-72x72-precomposed-584c35aa679456ab4e2f1cd971191498d7fecf7321b4ded8bae5c5a2c51176e3.png" />
<link rel="apple-touch-icon-precomposed" sizes="57x57" href="//cdn.shopify.com/s/assets/touch-icons/icon-57x57-precomposed-49c0927bd56de30bc28439aed87097b7c8e41f2bb4f00661f01a00729c2a1b77.png" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover, user-scalable=0" />

  <link rel="stylesheet" media="screen" href="//cdn.shopify.com/s/assets/dialog-fresh-66526625df0ed5b32afd82a4e7ae3a843a721051c14cdf0f5add5ea1e7988b07.css" crossorigin="anonymous" data-turbolinks-track="true" integrity="sha256-ZlJmJd8O1bMq/YKk5646hDpyEFHBTN8PWt1eoeeYiwc=" />

</head>

<body class="page-auth-login fresh-ui">
  <div id="container">
    <noscript class="no-js">
      In order to use the Shopify admin you need to enable Javascript. <a target="_blank" href="https://www.enable-javascript.com/">Learn how to enable Javascript</a>.
    </noscript>
    <main role="main" id="dialog-alternate">
      <div class="login-form">
  <h1 class="dialog-heading">Runeworks Development</h1>
  <h2 class="dialog-subheading">Log in to manage your store</h2>

  <form class="lookup-form" action="/admin/auth/login" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="&#x2713;" /><input type="hidden" name="authenticity_token" value="o+iwLU/BJDawX3A5Pnpa9S0MCn7CIdhzXoPqXvJoiizZp6sK4FRsLRo6IIAUUAJI5mUgIoFyOpSNqswZJfKRdg==" />
    <div id="email-login">
      <div class="clearfix">
        <div class="login-container">

          <div class="lform dialog-form">
            <div class="require-cookies">
              <div class="ui-banner ui-banner--status-critical ui-banner--within-page">
<div class="ui-banner__ribbon"><svg class="next-icon next-icon--size-20 next-icon--no-nudge" aria-hidden="true" focusable="false"> <use xlink:href="#error-major" /> </svg></div><div class="ui-banner__content-container"><div class="ui-banner__heading"><h2 class="ui-heading">Please enable cookies in your browser preferences to continue.</h2></div></div></div>            </div>
          </div>

          <div id="sign-in-form" class="lform dialog-form">
            <input type="hidden" name="redirect" value="" id="redirect" />
            <input type="hidden" name="step" value="lookup" />
            <div id="login">
              <div class="input-group">
                <div class="next-input-wrapper"><label class="next-label" for="Login">Email</label><input type="email" name="login" id="Login" spellcheck="false" autofocus="autofocus" required="required" class="next-input" /></div>

                <div class="next-input-wrapper"><label class="next-label helper--visually-hidden" for="Password">Password</label><input type="password" name="password" id="Password" class="next-input hidden-password" tabindex="-1" placeholder="Password" spellcheck="false" /></div>
              </div>
            </div> <!-- /#login -->

            <button class="ui-button ui-button--primary ui-button--full-width dialog-submit" type="submit" name="commit" id="EmailConfirm">Continue</button>

          </div> <!-- /#sign-in-form -->

            <div id="remember-me" class="remember-me">
              <input type="hidden" name="remember" id="remember_checkbox_default" value="0" />
              <div class="next-input-wrapper"><label class="next-label next-label--switch" for="remember_checkbox">Keep me logged in</label><input type="checkbox" name="remember" id="remember_checkbox" value="1" class="next-checkbox" checked="checked" /><span class="next-checkbox--styled"><svg class="next-icon next-icon--size-10 checkmark" aria-hidden="true" focusable="false"> <use xlink:href="#next-checkmark-thick" /> </svg></span></div>
            </div>
        </div>
      </div>
    </div>

    <div id="other-login">
    </div>
</form>
  <script type="text/javascript">
    if (typeof window.analytics !== 'undefined') {
      window.analytics.trackForm($('[action="/admin/auth/login"]')[0], 'login', {
        category: 'login',
        subdomain: "runeworks-development.myshopify.com"
      });
    }

    if (!navigator.cookieEnabled) {
      $('.require-cookies').show();
    }

    var showContinueButton = document.querySelector('.email-login a');

    if (showContinueButton instanceof HTMLElement) {
      showContinueButton.addEventListener('click', showLoginWithEmailBox.bind(this, true));
    }

    function showLoginWithEmailBox(show) {
      var continueButton = document.querySelector('.dialog-submit');
      var display = show ? '' : 'none';

      document.getElementById('login').style.display = display;

      if (continueButton instanceof HTMLElement) {
        continueButton.style.display = display;
      }

      if (showContinueButton instanceof HTMLElement) {
        showContinueButton.style.display = show ? 'none' : '';
      }
    }

    (function (){
      var ssoEnabled = false;
      if (ssoEnabled) {
        showLoginWithEmailBox(false)
      }
    })();
  </script>
</div>

    </main>

      <footer role="contentinfo" id="footer">
        <a target="_blank" class="ico ico-shopify-bag" href="//www.shopify.com">
          <span class="helper--visually-hidden">Shopify.com</span>
</a>      </footer>
  </div>

  <script src="//cdn.shopify.com/s/assets/admin/admin_jquery-1f0f820501c3b7fcb70379d8fa17d2fcfdb3722abc2a5eeedac0f05bfef7705c.js" crossorigin="anonymous" integrity="sha256-Hw+CBQHDt/y3A3nY+hfS/P2zciq8Kl7u2sDwW/73cFw="></script>
  <script src="//cdn.shopify.com/s/assets/admin/auth-af2f48596342908db2529c61a0cfcb59fa7feff59591946bdd8caad81b7abc64.js" crossorigin="anonymous" integrity="sha256-ry9IWWNCkI2yUpxhoM/LWfp/7/WVkZRr3Yyq2Bt6vGQ="></script>
  <script>var _gaq = _gaq || [];_gaq.push(["_setAccount","UA-82702-18"]);_gaq.push(["_addDevId","o5cUG"]);_gaq.push(["_setAllowLinker",true]);_gaq.push(["_setDomainName",".myshopify.com"]);_gaq.push(["_setAllowHash",false]);_gaq.push(["_trackPageview","/admin/auth/login"]);</script>

<script id="TrekkieLoader" type="text/javascript">
  (function(){
    var config = {"Trekkie":{"appName":"admin","development":false,"embedMode":"parent","defaultAttributes":{"shopId":16037216320,"requestIsFromShopify":false}},"Clickstream":{"appName":"admin"},"Performance":{"navigationTimingApiMeasurementsEnabled":true,"navigationTimingApiMeasurementsSampleRate":0.25},"Session Attribution":{},"LastShop":{}};
    var trekkie_version = '2017.09.05.1';
    var analytics = window.analytics = window.analytics || [];
    if (analytics.integrations) {
      return;
    }
    analytics.methods = [
      'identify',
      'page',
      'ready',
      'track',
      'trackForm',
      'trackLink'
    ];
    analytics.factory = function(method) {
      return function() {
        var args = Array.prototype.slice.call(arguments);
        args.unshift(method);
        analytics.push(args);
        return analytics;
      };
    };
    for (var i = 0; i < analytics.methods.length; i++) {
      var key = analytics.methods[i];
      analytics[key] = analytics.factory(key);
    }
    analyt

2

Answers


  1. Chosen as BEST ANSWER

    So after working with it further, taking another look at the example Cooper referenced, I was able to get the connection to process correctly.

    Here is the code in the event that someone else has the same issue in the future:

    function shopify_connection_test() {
      var api_key = '<enter api key here';
      var api_pass = '<enter api password here>';
      var store_url = 'https://storename.myshopify.com/admin/products.json';
    
      var product = {
      "product": {
        "title": "Burton Custom Freestyle 151",
        "body_html": "<strong>Good snowboard!</strong>",
        "vendor": "Burton",
        "product_type": "Snowboard",
        "tags": "Barnes & Noble, John's Fav, &quot;Big Air&quot;"
      }
    }
      var payload = JSON.stringify(product);
    
      var headers = {
        "Content-Type" : "application/json",
        "Authorization": "Basic " + Utilities.base64Encode(api_key + ":" + api_pass)
      };
    
      var params = {
        "method" : "POST",
        "headers" : headers,
        "contentType" : "application/json",
        "payload" : payload
      }
    
      var response = UrlFetchApp.fetch(store_url, params)
      Logger.log(response.getContentText())
    }
    

    This specifically uploads a product, I didn't want to exclude any information. The references in the Shopify API documentation should be enough for anyone looking to change its overall functionality.


  2. I had a similar problem where Shopify would return a (401) unauthorized {“errors”:”[API] Invalid API key or access token (unrecognized login or wrong password)”} when using UrlFetchApp on GAS, even though the request was working perfectly with Postman.

    Runeworks Gaming solution worked, the trick is to pass the authorization into a “headers” object, nested in the “params” of the url fetch app.

    I have used UrlFetchApp on many other occasions by putting the “Authorization” header directly into the params, but apparently, this won’t work with Shopify.

    Working:

    var SHOP_ID = "Your shop ID";
    var API_KEY = "Your API key";
    var API_PASSWORD = "Your API password";
    
    var encoded = Utilities.base64Encode(API_KEY + ':' + API_PASSWORD);
    
    var headers = {
        "Content-Type" : "application/json",
        "Authorization": "Basic " + encoded
      };
    
      var options = {
        "contentType" : "application/json",
        'method' : 'GET',
        'headers' : headers, // This is the important part
        'followRedirects' : false,
      };
    
    var response = UrlFetchApp.fetch("https://" + SHOP_ID  + ".myshopify.com/admin/api/2019-04/orders.json?status=any",options);
    
    var RESPONSE_CODE = response.getResponseCode();
    var CONTENT_JSON = JSON.parse(response.getContentText());
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search