Shopify API PHP Library

repository·main·Indexed 19 days ago

https://github.com/shopify/shopify-api-php

A framework-agnostic PHP library for building Shopify apps. It provides streamlined access to the Admin REST API, GraphQL Admin API, Storefront API, and Webhooks, and manages OAuth authentication processes. The library requires PHP 7.3+ and can be installed via Composer.

Tokens
19.1K
Snippets
62
Records
81
Agent score
66%

What's inside shopify-api-php

  1. Overview of the Shopify API Library for PHP

    main

    This library enables PHP-based Shopify apps to interact with various Shopify APIs. It is framework-agnostic, meaning it can be integrated into any PHP backend stack without requiring a specific framework.

    Key capabilities include:

    • OAuth: Creating online or offline access tokens for the Admin API.
    • REST Admin API: Making requests to the Shopify REST interface.
    • GraphQL Admin API: Making requests to the Shopify GraphQL interface.
    • Storefront API: Querying the Storefront API.
    • Webhooks: Registering and processing webhooks.
  2. How Webhooks work in the Shopify PHP library

    main

    The library uses a registry-based pattern to manage webhooks. The lifecycle follows three distinct steps:

    1. Loading Handlers: You map specific webhook topics to handler classes using Registry::addHandler. This defines how to react to an event.
    2. Registration: You tell Shopify which events to send to your app using Registry::register. This is typically done after OAuth. You can specify HTTP, EventBridge, or Pub/Sub delivery.
    3. Processing: When Shopify sends a POST request to your registered path, you pass the raw headers and raw body to Registry::process. The library validates the authenticity of the request and then executes the handler you registered in step 1.
  3. Use REST resources to interact with the Admin API

    main
    The library provides dedicated resource classes that represent REST endpoints in the Shopify Admin API. These classes map to all supported API versions (excluding the unstable version). Each resource class provides methods corresponding to the endpoints described in the official Shopify REST Admin API reference. This is the preferred way to interact with specific entities like products, orders, or customers using object-oriented methods.
  4. Getting started with the Shopify API PHP library

    main
    To begin using the Shopify API PHP library, you should follow the structured getting started guide which covers installation, library setup, and core API interactions. The library provides specialized modules for OAuth, REST Admin API, GraphQL API, Storefront API, and Webhooks.
  5. Begin the OAuth process with OAuth::begin

    main

    To start the OAuth flow, create a route (e.g., /login) that calls Shopify\Auth\OAuth::begin. This method returns a URL that redirects the user to the Shopify authentication screen.

    Parameters

    ParameterTypeRequired?Notes
    shopstringYesA Shopify domain name (e.g., example.myshopify.com).
    redirectPathstringYesThe callback route (e.g., auth/callback). Must be allowed in your app settings.
    isOnlineboolYestrue for online sessions, false for offline sessions.
    setCookieFunctioncallableNoAn optional override to handle cookie setting if your framework doesn't use the standard PHP setcookie function.

    If you are using a framework like Yii, you must provide a custom function to ensure cookies are set correctly within the framework's response lifecycle:

    function () use (Shopify\Auth\OAuthCookie $cookie) {
        $cookies = Yii::$app->response->cookies;
        $cookies->add(new \yii\web\Cookie([
            'name' => $cookie->getName(),
            'value' => $cookie->getValue(),
            'expire' => $cookie->getExpire(),
            'secure' => $cookie->isSecure(),
            'httpOnly' => $cookie->isSecure(),
        ]));
    
        return true;
    }
  6. Create a Storefront Access Token via Admin API

    main

    If you are using a sales channel, you can generate a new Storefront Access Token by making a POST request to the storefront_access_tokens endpoint using a REST client and an offline Admin API session. The response will contain the new access_token which you can then use for Storefront API calls.

    // Create a REST client from your offline session
    $client = new 
    Shopify
    Clients
    Rest($session->getShop(), $session->getAccessToken());
    
    // Create a new access token
    $storefrontTokenResponse = $client->post(
        'storefront_access_tokens',
        [
            "storefront_access_token" => [
                "title" => "This is my test access token",
            ]
        ],
    );
    $storefrontAccessToken = $storefrontTokenResponse->getBody()['storefront_access_token']['access_token'];
  7. Implement custom SessionStorage for production

    main

    The Shopify PHP library requires a session storage mechanism to handle OAuth information. While Shopify\Auth\FileSessionStorage is provided for rapid development, it is not suitable for production because it does not automatically clean up old session files, leading to disk build-up.

    To prepare for production, you must implement the Shopify\Auth\SessionStorage interface using your preferred storage method (e.g., Redis, Database, or Memcached) and pass an instance of your implementation to Shopify\Context::initialize.

    Important: Your implementation must include a mechanism to periodically clean up expired or old sessions from your storage, as the library cannot guarantee automatic deletion of all expired sessions.

    // Example of how to pass your custom storage to the context
    use Shopify\Context;
    use Your\Custom\Namespace\MyProductionSessionStorage;
    
    Context::initialize(
        $apiKey, 
        $apiSecret, 
        $scopes, 
        new MyProductionSessionStorage() // Your implementation of SessionStorage
    );
  8. Add a new API version to the Shopify API PHP library

    main

    To add a new API version (e.g., 2025-07) to the library, follow these steps:

    1. Update API Version Constants

    Edit src/ApiVersion.php to include the new version constant using the {MONTH}_{YEAR} naming convention and update the LATEST constant if this is the newest version.

    2. Create Directory Structure

    Create new directories for the source and test files using the Admin{YYYY_MM} format:

    • Source: src/Rest/Admin{YYYY_MM}/
    • Tests: tests/Rest/Admin{YYYY_MM}/

    3. Copy and Update Resource Files

    Copy all files from the most recent API version directory to the new directory. For every PHP file in the new directory, you must update:

    • Namespace: Change to Shopify\Rest\Admin{NEW_VERSION}.
    • API Version String: Update the public static string $API_VERSION property to the new version string.

    4. Update Test Files

    • Rename Files: Use the pattern {ResourceName}{YYYYMM}Test.php (e.g., Article202507Test.php).
    • Update Imports: Update use statements to point to the new versioned namespace.
    • Update Context: Set Context::$API_VERSION to the new version.
    • Update Mock URLs: Update the version string in mock request URLs (e.g., .../admin/api/{NEW_VERSION}/...).

    5. Handle Breaking Changes

    • Removed Resources: Delete the resource file from src/Rest/Admin{NEW_VERSION}/ and its corresponding test file.
    • Modified Resources: Update class properties, the $PATHS array, method signatures, and test cases to reflect changes in the Shopify API.
    # Example: Adding version 2025_07
    
    # 1. Update src/ApiVersion.php
    # public const JULY_2025 = "2025-07";
    # public const LATEST = self::JULY_2025;
    
    # 2. Create directories
    mkdir src/Rest/Admin2025_07/
    tests/Rest/Admin2025_07/
    
    # 3. Copy files from previous version (e.g., 2025_04)
    cp -r src/Rest/Admin2025_04/* src/Rest/Admin2025_07/
    cp -r tests/Rest/Admin2025_04/* tests/Rest/Admin2025_07/
  9. Migrate from ApiVersion::LATEST to explicit versions

    main

    In version 6.0.0 and later, the ApiVersion::LATEST constant has been removed. This change was made to prevent unintended breaking changes caused by the library automatically updating to new Shopify API versions every quarter.

    To migrate, you must replace any direct usage of ApiVersion::LATEST with a specific version string or a specific ApiVersion constant.

    // Before (v5 and earlier)
    $apiVersion = ApiVersion::LATEST;
    
    // After (v6+)
    $apiVersion = '2025-07'; // Explicitly specify the version you want to use
  10. Prerequisites for developing Shopify apps with PHP

    main

    Before using this library, ensure you have the following:

    • Basic knowledge of PHP.
    • A Shopify Partner account and a development store, OR a test store with a private app.
    • A private or custom app already configured in your Shopify environment.
    • ngrok: Installed and running to create a secure tunnel to your localhost.
    • App Configuration: The ngrok URL and the appropriate redirect URI for your OAuth callback route must be added to your Shopify app settings.