phpclassic / php-shopify

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

Set inventory to a product #289

Closed Izan-Ciclick closed 1 year ago

Izan-Ciclick commented 1 year ago

Please can u give me and example that how i can set the stock to a product. I was trying with InventoryLevel or Loction->InventoryLevel but not work for me.

PHPism commented 1 year ago

I will give you my example. It may not be the best practice, but I used it to sync inventory between company ERP system and Shopify store. Be ware that you don't set the new Quantity directly, you send it as an adjustment from old Qty to new Qty. You can get inventory_quantity and inventory_item_id if you already save variantId in your database. But I don't and you may need to sleep(1); between each Shopify call. That's my Example. First I get all products:

$params = array(
    'limit' => '250',
    'fields' => 'id,title,admin_graphql_api_id,variants',
);
$products = $shopify->Product->get($params);

$shopify_variants = array();
foreach($products as $product)
{
    foreach($product['variants'] as $variant)
    {
        $shopify_variants[] = $variant;
    }
}

Then I loop the variants and compare them with my variants if there's a qty mismatch, I sent adjustment call.

foreach($shopify_variants as $shopify_variant)
{
    // $qtyNew: The current qty in your system.
    $qtyAdjustment = $qtyNew - $shopify_variant['inventory_quantity'];

    $adjustment = array(
        "location_id" => $shopify_location_id, // Shopify inventory location.
        "inventory_item_id" => $shopify_variant['inventory_item_id'],
        "available_adjustment" => $qtyAdjustment
    );

    $shopify->InventoryLevel->adjust($adjustment);
}

Hope this helps.

Izan-Ciclick commented 1 year ago

Thanks for ur quick answer.

It works perfect!!