How To Make A Shopify API Request Inside Webhook Callback Script

- 1 answer

I am writing my first Shopify app that will unpublish a product once its inventory level goes below threshold.

For that I register a webhook with callback URL that will be called by Shopify once product update event occurs.

In script.php how do I obtain Shopify API token to make PUT request to products/update to unpublish it?

Here is my script.php so far (I know I am missing hmac validation but that is not the point):

  require 'shopify.php';
  $api_key = 'api_key';
  $secret = 'secret';
  $sc = new ShopifyClient($_SERVER['HTTP_X_SHOPIFY_SHOP_DOMAIN'], $_SERVER['HTTP_X_SHOPIFY_HMAC_SHA256'], $api_key, $secret);
  $inventory = $_POST['inventory_quantity'];
  $old_inventory = $_POST['old_inventory_quantity'];
  if($inventory <= 0){
    $args = array("product" => array("id" => $_SERVER['HTTP_X_SHOPIFY_PRODUCT_ID'], "published" => false));

I am trying to use $_SERVER['HTTP_X_SHOPIFY_HMAC_SHA256'] but obviously that is wrong.



Shopify sends you the name of the shop in the header of every webhook. So your webhook can now authenticate the incoming call, and with the shop name, you simply query your persistence layer for the matching shop credentials. If you find the shop, you can open up an API session very easily, since you have the two things you need:

  1. shopify domain name of the store
  2. shopify access token

Note that a better way to hide products is to consider listening to the orders webhooks, which provide orders and products, and then query the inventory level of the product sold. Working off of product/update webhooks could be super obnoxious in terms of the number of calls you might have to process in comparison to orders.