phpclassic / php-shopify

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

get inventroy level #69

Open keyur45 opened 5 years ago

keyur45 commented 5 years ago

How to get Inventory Level in Shopify SDK.

shawnhind commented 5 years ago

I haven't personally used this feature in the SDK but I just wanted to point out that there have been updates in the Shopify API in the last month or two regarding multi-location inventory levels. As far as I know this SDK hasn't been updated to support those changes.

KiloooNL commented 5 years ago

Hi, this is how I do it:

Get the inventory level:

$shopify = new PHPShopify\ShopifySDK;
function getInventoryLevel($productID = '', $variantID = '') {
        global $shopify;

        // Get the variant item id
        if(!empty($productID) && empty($variantID)) {
            $variant = $shopify->Product($productID)->get();
            $variant = $variant[0]['inventory_item_id'];
        } else if(!empty($productID) && !empty($variantID)) {
            $variant = $shopify->Product($productID)->Variant($variantID)->get();
            $variant = $variant['inventory_item_id'];
        } else {
             echo 'No Product ID or Variant ID was specified when trying to get inventory levels for this item.';
        }

        if(isset($variant)) {
            // Get the product's location details based on the item id
            $levels = $shopify->InventoryLevel->get([
                'inventory_item_ids' => $variant
            ]);
            return $levels[0]['available'];
        }
    }

Set the inventory level:

    function setInventoryLevel($productID, $quantity) {
        global $shopify;

        if(isset($productID) && isset($quantity)) {
            // Get the variant item id
            $variant = $shopify->Product($productID)->get();
            $variant = $variant['variants'][0]['inventory_item_id'];

            // Get the product's location details based on the item id
            $levels = $shopify->InventoryLevel->get([
                'inventory_item_ids' => $variant
            ]);

            // Update the products inventory at the given location id
            $shopify->InventoryLevel->set([
                'inventory_item_id' => $variant,
                'location_id' => $levels[0]['location_id'],
                'available' => $quantity
            ]);
        } else {
            echo 'Product ID or Quantity was not specified when trying to update the inventory level.';
        }
    }
PietroLaGrotta commented 2 years ago

Hei @keyur45, add to the name of issue: " and update quantities of products and variations" becouse the @KiloooNL's solution run very well for that! Thanks.