Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a shopify API request inside webhook callback script

Tags:

shopify

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 http://example.com/script.php 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):

<?php
if($_SERVER['REQUEST_METHOD'] == 'POST'){
  session_start();
  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));
    $sc->call("PUT","/admin/products/".$_SERVER['HTTP_X_SHOPIFY_PRODUCT_ID'].".json",$args);
  }
}

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

like image 521
goivvy.com Avatar asked Jul 08 '26 09:07

goivvy.com


1 Answers

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.

like image 88
David Lazar Avatar answered Jul 11 '26 10:07

David Lazar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!