Extracting SKUs from Shopify Products

Let’s assume we have a use case. We create products at someotherwebsite.com. In the end of each day we want to sync newly created products to Shopify store using API. Each product that we are creating has a unique code to identify it. This code corresponds to Shopify product’s sku. This is how we link products. The workflow should be the following: we need to check if product in exists in Shopify with the sku that is the same as product’s code from someotherwebsite.com. If such product exists in Shopify, we do nothing. If it does not exist, we create a product in Shopify with the same sku as the product code from someotherwebsite.com.

We already have a functional API client and can get products from Shopify and this client code returns JSON decoded object.

$shopifyData = $shopifyProductApi->getProducts();
$shopifyProducts = $shopifyData->products;

Shopify SKUs are located on product variants. Let’s extract the variants.

$variants = array_map(function($product){
	return $product->variants;
}, $shopifyProducts);

The above code will give us variants that are inside each product’s array. We need to flatten variants in order to get an array of all the variants. We can use the following function to flatten the array of variants.

function flatten(array $array) {
    $result = [];
    array_walk_recursive($array, function($a) use (&$result) { $result[] = $a; });
    return $result;
}

And then extract skus

$variants = flatten($variants);
 
$skus = array_map(function($variant){
  	return strtolower(trim($variant->sku));
}, $variants);

Or we can use array_walk_recursive function directly to “scoop out” the SKUs.

$skus = [];
array_walk_recursive($variants, function($variant) use (&$skus) { 
	$skus[] = strtolower(trim($variant->sku));
});

SKUs in Shopify are not required and they may be missing. Let’s filter out empty SKUs from the array

$skus = array_filter($skus, function($sku){
	return !empty($sku);
});

Now we are ready to check if products from someotherwebsite.com exist in Shopify. Let’s assume again, we have an API client to get products from someotherwebsite.com and it returns JSON decoded data

$otherProducts = $someOtherWebsiteProduct->getProducts();
$otherProducts = $otherProducts->data;

We now can loop through the products from other website and create a Shopify product if the code of other product does not exist in our skus array (Shopify).

foreach ($otherProducts as $otherProduct) {
       if (empty($otherProduct->code)) continue; // skip products with missing codes
       $code = strtolower(trim($otherProduct->code)); 
       if (in_array($code, $skus)) continue;  // skip product if it exists in Shopify
 
       $shopifyProductApi->create(['sku' => $code, 'description' => $otherProduct->description]);  // create product in Shopify
}

Resources used:

Thinking in Steps – Laracon US 2016 presentation by Adam Wathan