phpclassic / php-shopify

PHP SDK for Shopify API
Apache License 2.0
568 stars 211 forks source link

Feature: Storefront GraphQL Requests #308

Open whobutsb opened 11 months ago

whobutsb commented 11 months ago

I propose adding a new feature to the library enabling users to interact with the Shopify Storefront GraphQL API. This API necessitates an alternative endpoint for authenticated requests: https://my-store.myshopify.com/api/2023-04/graphql.json.

Key Modifications:

  1. Updated lib/ShopifyResource.php:
    • Modified __construct() to accept and set a new configuration variable StoreFrontAccessToken, obtainable via Shopify Admin under "Private App" setup.
  2. Extended lib/GraphQL.php:
    • Introduced storefront() method, mirroring post() method’s signature. If $url argument remains unset, it assembles the correct Shopify GraphQL storefront URL for requests.

Example Usage:

$shopify = \PHPShopify\ShopifySDK::config([
    'AccessToken' => 'SHOPIFY_ADMIN_TOKEN',
    'ShopUrl' => 'my-store.myshopify.com',
    'StoreFrontAccessToken' => 'STOREFRONT_ACCESS_TOKEN'  // Required for Storefront API requests
]);

$query = <<<GQL
    // retrieve the french canadian translations for a product
    query getProductById(\$id: ID!) @inContext(country: CA, language: FR) {
        product(id: \$id) {
            id
            title
            handle
            productType
            tags
            descriptionHtml
            options {
                id
                name
                values
            }
        }
    }
GQL;

// product global id - 'gid://shopify/Product/123456789'
$variables = [
    'id' => $productGID
];

$data = $shopify->GraphQL->storefront($query, null null, $variables);

Motivation: I Encountered a scenario requiring product locale translations retrieval for a client's store. The existing Shopify Admin GraphQL API fell short, necessitating the Storefront API. I appreciate the ease of use this library brings and think this feature would be beneficial to the developers that work with this great library.

I appreciate any feedback and am open to making any necessary changes. Thank you for considering this enhancement!