### Install Shopify API PHP Source: https://github.com/shopify/shopify-api-php/blob/main/docs/getting_started.md Install the Shopify API PHP library using Composer. Ensure you have PHP 7.3 or higher installed. ```bash composer require shopify/shopify-api ``` -------------------------------- ### Initialize Shopify API PHP Context Source: https://github.com/shopify/shopify-api-php/blob/main/docs/getting_started.md Initialize the Shopify API PHP library by calling the `Shopify\Context::initialize` method with your application's configuration settings. This includes API keys, scopes, host name, and session storage. It's recommended to call this early in your application. ```php use Shopify\Context; use Shopify\Utils\ApiVersion; use Shopify\SessionStorage\FileSessionStorage; Context::initialize( apiKey: $_ENV['SHOPIFY_API_KEY'], apiSecretKey: $_ENV['SHOPIFY_API_SECRET'], scopes: $_ENV['SHOPIFY_APP_SCOPES'], hostName: $_ENV['SHOPIFY_APP_HOST_NAME'], sessionStorage: new FileSessionStorage('/tmp/php_sessions'), apiVersion: '2024-10', isEmbeddedApp: true, isPrivateApp: false, ); ``` -------------------------------- ### Install Composer Dependencies Source: https://github.com/shopify/shopify-api-php/blob/main/README.md Installs the necessary dependencies for the Shopify API library using Composer. ```Shell composer install ``` -------------------------------- ### Run Tests with Code Coverage Source: https://github.com/shopify/shopify-api-php/blob/main/README.md Runs tests and generates code coverage reports (text or HTML) after installing the xdebug extension. ```Shell composer test -- [--coverage-text|--coverage-html=] ``` -------------------------------- ### Query Products using Storefront API (PHP) Source: https://github.com/shopify/shopify-api-php/blob/main/docs/usage/storefront.md This example shows how to query product data from the Shopify Storefront API using the `ShopifyClientsStorefront` client. It requires the shop URL and a valid Storefront Access Token. The query is sent as a GraphQL string. ```php // Load the access token as per instructions above $storefrontAccessToken = ''; // Shop from which we're fetching data $shop = 'my-shop.myshopify.com'; // The Storefront client takes in the shop url and the Storefront Access Token for that shop. $storefrontClient = new \Shopify\Clients\Storefront($shop, $storefrontAccessToken); // Call query and pass your query as `data` $products = $storefrontClient->query( data: <<getShop(), $session->getAccessToken(), ); if ($response->isSuccess()) { // Webhook registered! } else { \My\App::log("Webhook registration failed with response: \n" . var_export($response, true)); } } ``` -------------------------------- ### Shopify PHP REST Client - Get Products Source: https://github.com/shopify/shopify-api-php/blob/main/docs/usage/rest.md Demonstrates how to retrieve a list of products from a Shopify store using the `ShopifyClientsRest` class. This method makes a GET request to the 'products' endpoint. The response object contains status code, body, and headers, with a convenience method to get the decoded JSON body. ```php use Shopify\Clients\Rest; $client = new Rest($session->getShop(), $session->getAccessToken()); $response = $client->get(path: 'products'); ``` -------------------------------- ### Get Query Parameters from URL in PHP Source: https://github.com/shopify/shopify-api-php/blob/main/docs/usage/utils.md Extracts query string arguments from a given URL. This method takes a URL string as input and returns an associative array of the parsed query parameters. ```php 'value1', 'key2' => 'value2'] ?> ``` -------------------------------- ### PHP: Custom Set Cookie Function for Yii Framework Source: https://github.com/shopify/shopify-api-php/blob/main/docs/usage/oauth.md Provides an example of a custom function to set cookies within the Yii framework, overriding the default `setcookie` method for the Shopify OAuth process. This is useful for frameworks that do not directly use PHP's `setcookie` function. ```php 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; } ``` -------------------------------- ### Retrieving Next Page with Serialized Page Info (Shopify PHP API) Source: https://github.com/shopify/shopify-api-php/blob/main/docs/usage/rest.md This snippet shows how to unserialize previously saved pagination information and use it to fetch the next page of results from a Shopify REST endpoint. It utilizes the getNextPageQuery() method to get the necessary query parameters for the next page request. ```php $pageInfo = unserialize($serializedPageInfo); $result = $client->get(path: 'products', query: $pageInfo->getNextPageQuery()); ``` -------------------------------- ### Run Tests with Composer Source: https://github.com/shopify/shopify-api-php/blob/main/README.md Executes the test suite for the Shopify API library using Composer. ```Shell composer test ``` -------------------------------- ### Run Linter with Composer Source: https://github.com/shopify/shopify-api-php/blob/main/README.md Runs the linter to check code quality using Composer. ```Shell composer lint ``` -------------------------------- ### Shopify PHP: Basic GraphQL Query Source: https://github.com/shopify/shopify-api-php/blob/main/docs/usage/graphql.md Demonstrates how to instantiate the Shopify PHP GraphQL client and execute a basic query to fetch product data. It requires loading the current session to obtain the access token and shop URL. ```PHP // Load current session to get `accessToken` $session = Shopify\Utils::loadCurrentSession($headers, $cookies, $isOnline); // Create GraphQL client $client = new Shopify\Clients\Graphql($session->getShop(), $session->getAccessToken()); // Use `query` method and pass your query as `data` $queryString = <<query(data: $queryString); ``` -------------------------------- ### Validate and Normalize Composer Configuration Source: https://github.com/shopify/shopify-api-php/blob/main/README.md Validates the composer.json file and normalizes its format. ```Shell composer validate composer normalize ``` -------------------------------- ### Stage Release Files Source: https://github.com/shopify/shopify-api-php/blob/main/RELEASING.md Stages the CHANGELOG.md and src/version.php files for commit. These files contain the release notes and the new version number, respectively. ```bash git add CHANGELOG.md src/version.php ``` -------------------------------- ### Update Local Repository Source: https://github.com/shopify/shopify-api-php/blob/main/RELEASING.md Ensures the local Git repository is up-to-date with the main branch before proceeding with a release. This involves checking out the main branch and pulling the latest changes. ```bash git checkout main && git pull ``` -------------------------------- ### Create Storefront API Access Token (PHP) Source: https://github.com/shopify/shopify-api-php/blob/main/docs/usage/storefront.md This snippet demonstrates how to create a new Storefront API access token using the Shopify PHP SDK's REST client. It requires an existing Admin API session and makes a POST request to the 'storefront_access_tokens' endpoint. ```php // 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']; ``` -------------------------------- ### GraphQL Proxy Request in PHP Source: https://github.com/shopify/shopify-api-php/blob/main/docs/usage/utils.md Forwards GraphQL queries to Shopify and returns the response. This method requires HTTP headers, cookies, and the raw request body. It returns an HttpResponse object. ```php ``` -------------------------------- ### Clear Composer Autoload Cache Source: https://github.com/shopify/shopify-api-php/blob/main/README.md Clears the Composer autoload cache, typically needed after namespace changes. ```Shell composer dump-autoload ``` -------------------------------- ### Implement Shopify Webhook Handler Interface in PHP Source: https://github.com/shopify/shopify-api-php/blob/main/docs/usage/webhooks.md This snippet shows the implementation of the `Shopify\Webhooks\Handler` interface in PHP. It includes the `handle` method, which is called by the Shopify library when a webhook for the registered topic is received, along with its parameters. ```php namespace App\Webhook\Handlers; use Shopify\Webhooks\Handler; class AppUninstalled implements Handler { public function handle(string $topic, string $shop, array $requestBody): void { // Handle your webhook here! } } ``` -------------------------------- ### PHP Shopify SessionStorage Interface Methods Source: https://github.com/shopify/shopify-api-php/blob/main/docs/issues.md Defines the methods required for implementing custom session storage in the Shopify API PHP SDK. These methods handle storing, loading, and deleting session data, crucial for OAuth processes. ```PHP interface SessionStorage { /** * Creates or updates a Session object in your storage. * * @param Session $session The session object to store * @return bool Whether the operation was successful */ public function storeSession(Session $session): bool; /** * Fetches a Session object from your storage. * * @param string $sessionId The id of the session to load * @return Session|null The session object, or null if not found */ public function loadSession(string $sessionId): ?Session; /** * Deletes a session from your storage. * * @param string $sessionId The id of the session to delete * @return bool Whether the operation was successful */ public function deleteSession(string $sessionId): bool; } ``` -------------------------------- ### Shopify PHP: GraphQL Query with Variables Source: https://github.com/shopify/shopify-api-php/blob/main/docs/usage/graphql.md Shows how to perform a GraphQL mutation using the Shopify PHP API, including passing variables to the mutation. This involves constructing a mutation string with variables and providing a separate array for the variable values. ```PHP // load current session and create GraphQL client like above example // Use `query` method, passing the query and variables in an array as `data` $queryUsingVariables = << [ ["title" => "TARDIS"], ["descriptionHtml" => "Time and Relative Dimensions in Space"], ["productType" => "Time Lord technology"] ] ]; $response = $client->query(data: ['query' => $queryUsingVariables, 'variables' => $variables]); // do something with the returned data ``` -------------------------------- ### Check API Version Compatibility in PHP Source: https://github.com/shopify/shopify-api-php/blob/main/docs/usage/utils.md Compares the app's current API version with a reference version. It returns true if the app's version is more recent than or equal to the reference version. ```php ``` -------------------------------- ### Register App Uninstalled Webhook Handler in PHP Source: https://github.com/shopify/shopify-api-php/blob/main/docs/usage/webhooks.md This snippet demonstrates how to register a custom handler for the 'APP_UNINSTALLED' webhook topic using the Shopify API for PHP. It shows the necessary use statements and the call to `Registry::addHandler`. ```php use Shopify\Webhooks\Registry; use Shopify\Webhooks\Topics; use App\Webhook\Handlers\AppUninstalled; Registry::addHandler(Topics::APP_UNINSTALLED, new AppUninstalled()); ``` -------------------------------- ### PHP: Generate Embedded App URL with getEmbeddedAppUrl Source: https://github.com/shopify/shopify-api-php/blob/main/docs/usage/utils.md This function generates the Shopify URL for embedded applications. It requires a base64-encoded host string as input and returns the constructed URL string. This method is more reliable than using the shop parameter for directing merchants. ```php ``` -------------------------------- ### Process Shopify Webhooks in PHP Source: https://github.com/shopify/shopify-api-php/blob/main/docs/usage/webhooks.md This snippet shows how to process incoming Shopify webhook requests using the Shopify API for PHP. It includes validating the request, checking the response for success, logging messages, and handling potential exceptions during processing. ```php class ShopifyController { public function webhooksAction($request) { try { $response = Shopify\Webhooks\Registry::process($request->headers->toArray(), $request->getRawBody()); if ($response->isSuccess()) { \My\App::log("Responded to webhook!"); // Respond with HTTP 200 OK } else { // The webhook request was valid, but the handler threw an exception \My\App::log("Webhook handler failed with message: " . $response->getErrorMessage()); } } catch (\Exception $error) { // The webhook request was not a valid one, likely a code error or it wasn't fired by Shopify \My\App::log($error); } } } ``` -------------------------------- ### Sanitize Shop Domain in PHP Source: https://github.com/shopify/shopify-api-php/blob/main/docs/usage/utils.md Ensures a Shopify shop domain is formatted correctly as 'my-domain.myshopify.com'. It accepts the shop domain and an optional custom myshopify domain for testing. Returns a sanitized string or null if invalid. ```php ``` -------------------------------- ### Load Current Session in PHP Source: https://github.com/shopify/shopify-api-php/blob/main/docs/usage/utils.md Fetches the current user's session based on provided HTTP headers and cookies. It can load either online or offline sessions and returns a Session object or null. ```php ``` -------------------------------- ### Implement Shopify Webhook Handler in PHP Source: https://github.com/shopify/shopify-api-php/blob/main/docs/usage/webhooks.md This snippet demonstrates how to implement a custom webhook handler for Shopify in PHP. It defines a class that adheres to the `Shopify\Webhooks\Handler` interface, with a `handle` method to process the webhook's topic, shop details, and request body. ```php namespace App\Webhook\Handlers; use Shopify\Webhooks\Handler; class AppUninstalled implements Handler { public function handle(string $topic, string $shop, array $requestBody): void { // Handle your webhook here! } } ``` -------------------------------- ### Load Offline Session in PHP Source: https://github.com/shopify/shopify-api-php/blob/main/docs/usage/utils.md Retrieves an offline session for a given shop URL. This method optionally includes expired sessions and returns a Session object or null if no session is found. It does not validate the shop domain. ```php ``` -------------------------------- ### Serialize and Unserialize Page Info in Shopify PHP API Source: https://github.com/shopify/shopify-api-php/blob/main/docs/usage/rest.md Demonstrates how to serialize and unserialize page information obtained from a Shopify API response. This allows saving and retrieving pagination state between requests. ```php $serializedPageInfo = serialize($result->getPageInfo()); ``` ```php $pageInfo = unserialize($serializedPageInfo); $result = $client->get(path: 'products', query: $pageInfo->getNextPageQuery()); ``` -------------------------------- ### Decode Session Token (JWT) in PHP Source: https://github.com/shopify/shopify-api-php/blob/main/docs/usage/utils.md Decodes a JSON Web Token (JWT) and extracts its payload using the API secret key. This method takes the JWT string as input and returns the decoded payload. ```php ``` -------------------------------- ### Validate HMAC Signature in PHP Source: https://github.com/shopify/shopify-api-php/blob/main/docs/usage/utils.md Verifies the authenticity of a request by checking its HMAC signature. It requires the URL query parameters and the app's secret key. Returns a boolean indicating validity. ```php 'example.com', 'hmac' => 'some_hmac_hash'], 'your_secret_key'); // $isValid will be true or false ?> ```