如何将 Shopify 产品数据提取到我自己的、不在 Shopify 本身内的 index.HTML 文件中?

问题描述 投票:0回答:1

所以我试图将三种不同的 Shopify 产品放入一个 index.html 文件中。我还有一个 style.css 和一个 script.js 文件。

document.addEventListener('DOMContentLoaded', function() {
  // Shopify Buy Button initialization
  const client = ShopifyBuy.buildClient({
    domain: /*removed by editor */,
    storefrontAccessToken: /* removed by editor */,
  });

  const ui = ShopifyBuy.UI.init(client);

  // Product IDs from your Shopify store
  const productIds = ['product-id-1', 'product-id-2', 'product-id-3'];

  // Render products on the page
  productIds.forEach(productId => {
    ui.createComponent('product', {
      id: productId,
      node: document.getElementById('product-container'),
      moneyFormat: '${{amount}}',
      options: {
        product: {
          iframe: false,
          variantId: null, // or specify a variant ID
          width: '100%',
          contents: {
            img: false,
            title: false,
            price: false,
            options: false,
          },
          text: {
            button: 'Add to Cart',
          },
          templates: {
            title: '<h2>{{ title }}</h2>',
            price: '<span>{{ price }}</span>',
          },
        },
        cart: {
          startOpen: false,
          iframe: false,
          contents: {
            title: true,
            lineItems: true,
            footer: true,
          },
          templates: {
            footer: '<div id="cart-footer">Total: {{ total }}</div>',
          },
        },
      },
    });
  });
});
<div id="product-container"></div>

<script src="https://cdn.shopify.com/shopifycloud/buy-button/v2/latest/shopify-buy-button-js"></script>

<script src="script.js"></script>

因此,在打开index.html 文件时,我收到两个错误。错误一是无法加载资源:服务器响应状态为 404 (),这是针对 Shopify 购买按钮的,另一个错误是 Uncaught ReferenceError:ShopifyBuy 未定义 在 HTML 文档中。 (脚本.js:4:20)

javascript html shopify
1个回答
0
投票

所以我可以通过以下代码让一切正常工作:

// Define the API URL and access token
const apiUrl = 'https://shop.myshopify.com/api/2021-04/graphql.json';
const accessToken = 'accessToken';

// Define the GraphQL query
const graphqlQuery = `
  {
    products(first: 3) {
      edges {
        node {
          id
          title
          descriptionHtml
          handle
          variants(first: 1) {
            edges {
              node {
                priceV2 {
                  amount
                  currencyCode
                }
              }
            }
          }
          images(first: 1) {
            edges {
              node {
                originalSrc
              }
            }
          }
        }
      }
    }
  }
`;

// Configure the request options
const requestOptions = {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-Shopify-Storefront-Access-Token': accessToken,
  },
  body: JSON.stringify({ query: graphqlQuery }),
};

// Function to get the currency symbol based on the currency code
function getCurrencySymbol(currencyCode) {
  const currencySymbols = {
    USD: '$',
    GBP: '£',
  };
  return currencySymbols[currencyCode] || currencyCode;
}

// Function to create and append HTML elements
function createAndAppend(tag, content, parent) {
  const element = document.createElement(tag);
  element.innerHTML = content;
  parent.appendChild(element);
}

// Function to navigate to the product page
function navigateToProduct(handle) {
  // Construct the product URL based on the handle
  const productUrl = `https://shop.myshopify.com/products/${handle}`;
  // Navigate to the product URL
  window.location.href = productUrl;
}

// Make the API request
fetch(apiUrl, requestOptions)
  .then(response => response.json())
  .then(({ data }) => {
    // Get the product container element from the DOM
    const productContainer = document.getElementById('product-container');

    // Iterate through the products and create HTML elements for each
    data?.products?.edges?.forEach(({ node }) => {
      const productElement = document.createElement('div');
      createAndAppend('h1', node?.title, productElement);
      createAndAppend('p', node?.descriptionHtml || '', productElement);

      // Check if there is an image, and if so, create an image element
      const imageSrc = node?.images?.edges?.[0]?.node?.originalSrc;
      if (imageSrc) {
        const image = Object.assign(document.createElement('img'), { src: imageSrc });
        productElement.appendChild(image);
      }

      // Display the price information with dynamic currency symbol
      const priceNode = node?.variants?.edges?.[0]?.node?.priceV2;
      if (priceNode) {
        const currencySymbol = getCurrencySymbol(priceNode.currencyCode);
        const price = `${currencySymbol}${priceNode.amount}`;
        createAndAppend('p', `Price: ${price}`, productElement);
      }

      // Create a "Shop Now" button and append it to the product element
      const shopNowButton = Object.assign(document.createElement('button'), {
        innerText: 'Shop Now',
        // Add a click event listener to navigate to the product URL
        onclick: () => navigateToProduct(node.handle),
      });
      productElement.appendChild(shopNowButton);

      // Append the product element to the product container
      productContainer.appendChild(productElement);
    });
  })
  .catch(error => console.error('Error fetching data:', error));

我认为这是因为我也没有使用正确的 Storefront API 密钥

© www.soinside.com 2019 - 2024. All rights reserved.