PHP: 创建shopify webhook, shopify webhook实例, create shopify webhook, php shopify webhook example

大概有两种方式创建 shopify webhook

 

第一种是后台创建:

Settings -> Notifications -> Webhooks -> create webhook

 

 

 

PHP: 创建shopify webhook, shopify webhook实例, create shopify webhook, php shopify webhook example
PHP: 创建shopify webhook, shopify webhook实例, create shopify webhook, php shopify webhook example

创建之后有个 signed code 黄色背景部分

PHP: 创建shopify webhook, shopify webhook实例, create shopify webhook, php shopify webhook example
PHP: 创建shopify webhook, shopify webhook实例, create shopify webhook, php shopify webhook example

 

第二种是通过 API 或者 APP 创建:

如果你是开发者或者测试者,那么一定有 https://partners.shopify.com/ 账户,创建一个APP后,在 APP ->  App credentials ->  API secret key 。API secret key 就相当于第一种方法的 signed code。

创建后,我们需要代码验证: (参考:https://help.shopify.com/en/api/getting-started/webhooks)

https://yourdomain.com/order-creation.php

<?php

define('SHOPIFY_APP_SECRET', 'my_shared_secret'); // 这个就是 第一种方法的  signed code 或者 第二种方法的 API secret key

function verify_webhook($data, $hmac_header)
{
  $calculated_hmac = base64_encode(hash_hmac('sha256', $data, SHOPIFY_APP_SECRET, true));
  return hash_equals($hmac_header, $calculated_hmac);
}

$hmac_header = $_SERVER['HTTP_X_SHOPIFY_HMAC_SHA256'];
$data = file_get_contents('php://input'); // 获取shopify的json返回值,不要用 $_POST
$verified = verify_webhook($data, $hmac_header);

// 数据处理
if($verified AND $data)
{
    $domain  = $_SERVER['HTTP_X_SHOPIFY_SHOP_DOMAIN']; //'justcode.myshopify.com'
    $topic   = $_SERVER['HTTP_X_SHOPIFY_TOPIC'];      //'products/update'
    $section = current(explode('/', $topic));
    $data    = json_decode($data);

    if($section == 'products')
    {
        $product_id = $data['id'];

    }
    else if($section == 'orders')
    {

    }

    header("HTTP/1.1 200 OK");
}
else header("HTTP/1.1 500 Internal Server Error");

exit();

如果想保存数据,可以用 error_log 或者

   $file = fopen("/var/www/html/test/test1.txt","w");
    fwrite($file,var_export($_SERVER, true));

    $file = fopen("/var/www/html/test/test2.txt","w");
    fwrite($file, file_get_contents('php://input'));
    fclose($file);

 

 

本文:PHP: 创建shopify webhook, shopify webhook实例, create shopify webhook, php shopify webhook example