有什么方法可以使用 JavaScript(<script>...<script>) 在 theme.liquid 文件中访问 Admin API(GraphQL)?

问题描述

我正在尝试通过“SKU”获取产品,这只能使用 Admin API。我需要将 JavaScript 代码片段注入到 theme.liquid 文件中。我可以仅通过 JavaScript 来实现吗?到目前为止,我的代码看起来像这样:

<script>
const query = `{
  productvariants(first: 1,query: "sku:<SKU>") {
    edges {
      node {
        id
        price
        product {
          title
          description
          featuredImage {
            id
            originalSrc
          }
        }
      }
    }
  }
}`;
const STOREFRONT_ACCESS_TOKEN = 'xxxxxxxxxx';
const GRAPHQL_URL = 'https://<my-store>.myshopify.com/admin/api/2021-01/graphql.json';
const GRAPHQL_BODY = {
  'method': 'POST','headers': {
    'X-Shopify-Storefront-Access-Token': STOREFRONT_ACCESS_TOKEN,'Content-Type': 'application/json',},'body': JSON.stringify({ query })
}
fetch(GRAPHQL_URL,GRAPHQL_BODY)
  .then(res => res.json())
  .then(data => {
    console.log(data);
  })
  .catch((error) => {
    console.log(error);
  });
</script>

我不太熟悉 Shopify 和 Shopify 的 API(店面、管理员)。我尝试了所有可能的方法,但走到了死胡同。如果有人可以将我重定向到正确的资源,我将不胜感激。谢谢!

解决方法

您的代码与此处文档中的代码大致相似:https://shopify.dev/tutorials/authenticate-with-oauth

两个问题,真的:

  1. 在这一行:
'X-Shopify-Storefront-Access-Token': STOREFRONT_ACCESS_TOKEN,

您需要使用您在之后向其请求的令牌

https://{shop}.myshopify.com/admin/oauth/access_token

不过,更大的问题是:

  1. 要仅通过主题代码执行此操作,您最终必须通过前端代码公开您的密钥,这将带来安全风险。从技术上讲,使用 Admin API 的正确方法是设置一个运行嵌入式应用的服务器,并将这些密钥存储在那里的 .env 文件中。