How do you use the Storefront API from a checkout UI extension?

kyle_truong
Shopify Partner
59 6 16

The documentation surround use of the Storefront API is confusing to me and I'm not sure how/if I can use it within a checkout UI extension. 

 

On one hand, I've seen a couple examples of apps calling the Storefront API while also using checkout UI extensions, and some hints that this may be possible in threads like this:

 

https://community.shopify.com/c/shopify-apis-and-sdks/how-do-i-fetch-product-details-from-a-checkout...

 

On the other hand, I'm reading that the app must be turned into a sales channel (for public apps) in threads like this:

 

https://community.shopify.com/c/shopify-apis-and-sdks/storefront-api-app-must-have-a-channel-record/...

 enabled network_access for my extension and gave tried to call the Storefront API:

 

useEffect(() => {
    if (!isInitialized) {
      const testCall = async () => {
        const response = await fetch(
          `https://<myshopifyDomain>.myshopify.com/api/2022-07/graphql.json`,
          {
            method: 'POST',
            body: `
            query {
              products (first: 3) {
                edges {
                  node {
                    id
                    title
                  }
                }
              }
            }
            `,
          },
        );
        const data = await response.json();
        console.log('data', data);
      };
testCall(); } }, []);

but it returns a 403 error. 

 

I guess the points I'm trying to clear up are:

 

1. How can one call the Storefront API from a checkout UI extension?

2. Is converting the app into a Sales Channel necessary? It feels like quite a blocker if it is as I've read many apps having legitimate use-cases for the Storefront API but having their app rejected to become a Sales Channel because it doesn't fit the criteria for a Sales Channel. 

 

 

Reply 1 (1)

FutureAndAHope
Shopify Partner
32 1 16

I was just looking through the documentation and there appears to be a way to do this see https://shopify.dev/docs/api/checkout-ui-extensions/2023-10/apis/storefront-api

 

import {useEffect, useState} from 'react';
import {
  useApi,
  reactExtension,
  List,
  ListItem,
} from '@shopify/ui-extensions-react/checkout';
export default reactExtension(
  'purchase.checkout.block.render',
  () => <Extension />,
);
function Extension() {
  const [data, setData] = useState();
  const {query} = useApi();

  useEffect(() => {
    query(
      `query ($first: Int!) {
        products(first: $first) {
          nodes {
            id
            title
          }
        }
      }`,
      {
        variables: {first: 5},
      },
    )
      .then(({data, errors}) => setData(data))
      .catch(console.error);
  }, [query]);

  return (
    <List>
      {data?.products?.nodes.map((node) => (
        <ListItem key={node.id}>
          {node.title}
        </ListItem>
      ))}
    </List>
  );
}