Home

Awesome

ZfrShopify

Latest Stable Version Build Status

ZfrShopify is a modern PHP library based on Guzzle for Shopify.

Dependencies

Installation

Installation of ZfrShopify is only officially supported using Composer:

php composer.phar require 'zfr/zfr-shopify:6.0'

REST API

ZfrShopify provides a one-to-one mapping with API methods defined in Shopify doc. Since the version 4, it also supports a basic integration with the new GraphQL admin API.

Private app

In order to use ZfrShopify as a private app, you must first instantiate the client:

$shopifyClient = new ShopifyClient([
    'private_app' => true,
    'api_key'     => 'YOUR_API_KEY',
    'password'    => 'YOUR_PASSWORD',
    'shop'        => 'domain.myshopify.com',
    'version'     => '2019-04'
]);

Make sure to always include a version. More info about Shopify versioning

Public app

When using a public app, you instantiate the client a bit differently:

$shopifyClient = new ShopifyClient([
    'private_app'   => false,
    'api_key'       => 'YOUR_API_KEY', // In public app, this is the app ID
    'access_token'  => 'MERCHANT_TOKEN',
    'shop'          => 'merchant.myshopify.com',
    'version'       => '2019-04'
]);

Make sure to always include a version. More info about Shopify versioning

Using a container

ZfrShopify also provides built-in container-interop factories that you can use. You must make sure that your container contains a service called "config" that is an array with a key zfr_shopify containing the required config:

// myconfig.php

return [
    'zfr_shopify' => [
        'private_app'   => false,
        'api_key'       => 'YOUR_API_KEY', // In public app, this is the app ID
        'access_token'  => 'MERCHANT_TOKEN',
        'shop'          => 'merchant.myshopify.com',
    ],
];

If you're using Zend\ServiceManager 3, you can use Zend\ComponentInstaller to register our factories into Zend\ServiceManager automatically.

However if you're using other framework or other container, you can still manually register our factories, they are under src/Container folder.

Validating a request

ZfrShopify client provides an easy way to validate an incoming request to make sure it comes from Shopify through the RequestValidator object. It requires a PSR7 requests and a shared secret:

use ZfrShopify\Exception\InvalidRequestException;
use ZfrShopify\Validator\RequestValidator;

$validator = new RequestValidator();

try {
    $validator->validateRequest($psr7Request, 'shared_secret');
} catch (InvalidRequestException $exception) {
    // Request is not valid
}

Validating a webhook

Similarily, you can use the WebhookValidator to validate your webhook:

use ZfrShopify\Exception\InvalidWebhookException;
use ZfrShopify\Validator\WebhookValidator;

$validator = new WebhookValidator();

try {
    $validator->validateWebhook($psr7Request, 'shared_secret');
} catch (InvalidWebhookException $exception) {
    // Request is not valid
}

Validating an application request

Finally, you can also use the ApplicationProxyRequestValidator to validate application proxy requests:

use ZfrShopify\Exception\InvalidApplicationProxyRequestException;
use ZfrShopify\Validator\ApplicationProxyRequestValidator;

$validator = new ApplicationProxyRequestValidator();

try {
  $validator->validateApplicationProxyRequest($psr7Request, 'shared_secret');
} catch {
  // Request is not valid
}

Create an authorization response

ZfrShopify provides an easy way to create a PSR7 compliant ResponseInterface to create an authorization response:

use ZfrShopify\OAuth\AuthorizationRedirectResponse;

$apiKey         = 'app_123';
$shopDomain     = 'shop_to_authorize.myshopify.com';
$scopes         = ['read_orders', 'read_products'];
$redirectionUri = 'https://myapp.test.com/oauth/redirect';
$nonce          = 'strong_nonce';

$response = new AuthorizationRedirectResponse($apiKey, $shopDomain, $scopes, $redirectionUri, $nonce);

While the nonce parameter is required, ZfrShopify does not make any assumption about how to save the nonce and check it when Shopify redirects to your server. You are responsible to safely saving the nonce.

Exchanging a code against an access token

You can use the TokenExchanger class to exchange a code to a long-lived access token:

use GuzzleHttp\Client;
use ZfrShopify\OAuth\TokenExchanger;

$apiKey         = 'app_123';
$sharedSecret   = 'secret_123';
$shopDomain     = 'shop_to_authorize.myshopify.com';
$code           = 'code_123';

$tokenExchanger = new TokenExchanger(new Client());
$accessToken    = $tokenExchanger->exchangeCodeForToken($apiKey, $sharedSecret, $shopDomain, $code);

ZfrShopify also provides a simple factory compliant with container-interop that you can register to the container of your choice, with the ZfrShopify\Container\TokenExchangerFactory.

Exploiting responses

ZfrShopify returns Shopify response directly. However, by default, Shopify wrap the responses by a top-key. For instance, if you want to retrieve shop information, Shopify will return this payload:

{
    "shop": {
        "id": 123,
        "domain": "myshop.myshopify.com"
    }
}

This is a bit inconvenient to use as we would need to do that:

$shopDomain = $shopifyClient->getShop()['shop']['domain'];

Instead, ZfrShopify automatically "unwraps" response, so you can use the more concise code:

$shopDomain = $shopifyClient->getShop()['domain'];

When reading Shopify API doc, make sure you remove the top key when exploiting responses.

Count

Similarily, when you use one of the count endpoint, ZfrShopify will automatically extract the value from Shopify's response, so you do not need to manually access the count property:

php $count = $shopifyClient->getOrderCount(); // $count is already an integer

Using iterators

For most "list" endpoints (getProducts, getCollections...), Shopify allows you to get up to 250 resources at a time. When using the standard get** method, you are responsible to handle the pagination yourself.

For convenience, ZfrShopify allows you to easily iterate through all resources efficiently (internally, we are using generators). Here is how you can get all the products from a given store:

foreach ($shopifyClient->getProductsIterator(['fields' => 'id,title']) as $product) {
   // Do something with product
}

ZfrShopify will take care of doing additional requests when it has reached the end of a given page.

Executing multiple requests concurrently

For optimization purposes, it may be desirable to execute multiple requests concurrently. To do that, ZfrShopify client allow you to take advantage of the underlying Guzzle client and execute multiple requests at the same time.

To do that, you can manually create the Guzzle commands, and execute them all. ZfrShopify will take care of authenticating all requests individually, and extracting the response payload. For instance, here is how you could get both shop info and products info:

$command1 = $client->getCommand('GetShop', ['fields' => 'id']);
$command2 = $client->getCommand('GetProducts', ['fields' => 'id,title']);

$results = $client->executeAll([$command1, $command2]);

// $results[0] represents the response of $command1, $results[1] represents the response of $command2

If a request has failed, it will contain an instance of GuzzleHttp\Command\Exception\CommandException. For instance, here is how you could iterate through all the results:

use GuzzleHttp\Command\Exception\CommandException;

foreach ($results as $singleResult) {
   if ($singleResult instanceof CommandException) {
      // Get the command that has failed, and eventually retry
      $command = $singleResult->getCommand();
      continue;
   }

   // Otherwise, $singleResult is just an array that contains the Shopify data
}

GraphQL API

In 2018, Shopify launched a new API, called the GraphQL Admin API. This new API comes with a lot of advantages compared to the REST API:

The version 4 of ZfrShopify now ships with a basic GraphQL client. It does not yet support the following features, though:

In order to use the client, you must instantiate it. Instead of the ShopifyClient, you must create a ZfrShopify\ShopifyGraphQLClient. If you are using a private app:

$client = new ShopifyGraphQLClient([
    'shop'        => 'test.myshopify.com',
    'version'     => '2019-04',
    'private_app' => true,
    'password'    => 'YOUR PASSWORD'
]);

Make sure to always include a version. More info about Shopify versioning

If you are using a public app:

$client = new ShopifyGraphQLClient([
    'shop'         => 'test.myshopify.com',
    'version'      => '2019-04',
    'private_app'  => false,
    'access_token' => 'ACCESS TOKEN'
]);

Make sure to always include a version. More info about Shopify versioning

Queries

To perform query, simply enter your query as an heredoc. For instance, here is a GraphQL query that get the title and id of the first 5 collections, as well as the 5 first products within those collections (this used to require several queries in the REST API, while everything can be done very efficiently with GraphQL):

$request = <<<'EOT'
query
{
  collections(first: 5) {
    edges {
      node {
        id
        title
        products(first: 5) {
          edges {
            node {
              id
              title
            }
          }
        }
      }
    }
  }
}
EOT;

$result = $client->request($request);

ZfrShopify automatically unwrap the data top key from Shopify response, so you can retrieves the data like this:

foreach ($result['collections']['edges'] as $collection) {
    var_dump('Collection title: ' . $collection['node']['title']);

    foreach ($collection['node']['products']['edges'] as $product) {
        var_dump('Product title: ' . $product['node']['title']);
    }
}

ZfrShopify does not attempt to re-write the GraphQL response.

Variables

ZfrShopify also fully supports GraphQL variable. For instance, here is how you can retrieve a given product by its ID by using GraphQL variables:

$request = <<<'EOT'
query getProduct($id: ID!)
{
  product(id: $id) {
    id
    title
  }
}
EOT;

$variables = [
    'id' => 'gid://shopify/Product/827442593835'
];

$result = $client->request($request, $variables);

var_dump($result);

Mutations

Similarly, ZfrShopify supports mutation. To do this, you simply need to use a mutation query. Here is an example that is creating a product:

$request = <<<'EOT'
mutation createProduct($product: ProductInput!)
{
  productCreate(input: $product) {
    userErrors {
      field
      message
    }
    product {
      id
    }
  }
}
EOT;

$variables = [
    'product' => [
        'title' => 'My product'
    ]
];

$result = $client->request($request, $variables);

var_dump($result);

This request will create a new product whose title is "My product", and will return the id of the product.

For better error handling, you should always include the userErrors object in your response.

Error handling

When using GraphQL requests, there are two kinds of errors that you can catch.

Request errors

Those errors are for malformed GraphQL requests. You can catch them using the \ZfrShopify\Exception\GraphQLErrorException exception:

try {
    $result = $client->request($request);
} catch (\ZfrShopify\Exception\GraphQLErrorException $exception) {
    var_dump($exception->getErrors());
}

User errors

Those errors are for requests that are missing data (like incorrect data, missing data...). You can catch them using the \ZfrShopify\Exception\GraphQLUserErrorException exception:

try {
    $result = $client->request($request);
} catch (\ZfrShopify\Exception\GraphQLUserErrorException $exception) {
    var_dump($exception->getErrors());
}

Implemented endpoints

Here is a list of supported endpoints (more to come in the future):

ACCESS SCOPE RELATED METHODS:

STOREFRONT ACCESS TOKEN RELATED METHODS:

APPLICATION CHARGE RELATED METHODS:

ARTICLE RELATED METHODS:

ASSET RELATED METHODS:

BLOG RELATED METHODS:

CUSTOM COLLECTION RELATED METHODS:

COLLECTION RELATED METHODS

COLLECT RELATED METHODS:

CUSTOMER RELATED METHODS:

CUSTOMER ADDRESS RELATED METHODS:

DISCOUNT CODE RELATED METHODS:

EVENT RELATED METHODS:

FULFILLMENTS RELATED METHODS:

FULFILLMENT ORDER RELATED METHODS:

GIFT CARD RELATED METHODS:

INVENTORY ITEM RELATED METHODS:

INVENTORY LEVEL RELATED METHODS:

LOCATION RELATED METHODS:

METAFIELDS RELATED METHODS:

ORDER RELATED METHODS:

DRAFT ORDER RELATED METHODS:

PAGE RELATED METHODS:

PRICE RULE RELATED METHODS:

PRODUCT RELATED METHODS:

PRODUCT IMAGE RELATED METHODS:

RECURRING APPLICATION CHARGE RELATED METHODS:

REFUND RELATED METHODS:

SHOP RELATED METHODS:

SMART COLLECTION RELATED METHODS:

THEME RELATED METHODS:

PRODUCT VARIANT RELATED METHODS:

REDIRECT RELATED METHODS:

SCRIPT TAG RELATED METHODS:

TRANSACTION RELATED METHODS:

USAGE CHARGE RELATED METHODS:

WEBHOOK RELATED METHODS:

OTHER METHODS: