我已实现此代码以订阅 Webhook 到 Shopify 应用的卸载事件。我在 PHP 中创建了一个自定义 shopify 应用程序。所以这里是一步一步的解释:
- 将此代码添加到您要创建 webhook 的位置。就我而言,我将其添加到 generate_token.php 文件中。
/* subscribe to app uninstall webhook */
$webhook_array = array(
'webhook' => array(
'topic' => 'app/uninstalled',
'address' => 'https://yourwebsite.com/webhooks/delete.php?shop=' . $shop_url,
'format' => 'json'
)
);
$webhook = shopify_call($access_token, $shop_url, "/admin/api/2021-10/webhooks.json", $webhook_array, 'POST');
$webhook = json_decode($webhook['response'], JSON_PRETTY_PRINT);
/** subscribe to app uninstall webhook **/
- 要测试是否创建了 webhook,您可以运行以下代码。就我而言,我将此代码添加到应用程序的 index.php 文件中以检查响应:
$webhook = shopify_call($token, $shop, "/admin/api/2019-10/webhooks.json", array(), 'GET');
$webhook = json_decode($webhook['response'], JSON_PRETTY_PRINT);
echo print_r( $webhook );
- 在“webhook”文件夹下创建delete.php文件(因为我们已经指定文件-https://yourwebsite.com/webhooks/delete.php来执行删除)并使用MySQL函数从数据库中删除存储数据。
<?php
require_once("../inc/mysql_connect.php");
require_once("../inc/functions.php");
define('SHOPIFY_APP_SECRET', 'xxxxxxxxxxxxxxxxxxxxxxx'); // Replace with your 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);
}
$res = '';
$hmac_header = $_SERVER['HTTP_X_SHOPIFY_HMAC_SHA256'];
$topic_header = $_SERVER['HTTP_X_SHOPIFY_TOPIC'];
$shop_header = $_SERVER['HTTP_X_SHOPIFY_SHOP_DOMAIN'];
$data = file_get_contents('php://input');
$decoded_data = json_decode($data, true);
$verified = verify_webhook($data, $hmac_header);
if( $verified == true ) {
if( $topic_header == 'app/uninstalled' || $topic_header == 'shop/update') {
if( $topic_header == 'app/uninstalled' ) {
$sql = "DELETE FROM shops WHERE shop_url='".$shop_header."' LIMIT 1";
$result = mysqli_query($conn, $sql);
$response->shop_domain = $decoded_data['shop_domain'];
$res = $decoded_data['shop_domain'] . ' is successfully deleted from the database';
}
else {
$res = $data;
}
}
} else{ $res = "The request is not from Shopify";}
error_log('Response: '. $res); //check error.log to see the result
?>