To receive a webhook response from Shopify and verify it in PHP, you can use the following steps:
- Create a route in your PHP application to handle the webhook request
- Retrieve the raw request payload and HMAC header
- Calculate the HMAC of the payload using the same secret key used by Shopify
- Compare the calculated HMAC with the HMAC header received in the request
- If the HMAC match, process the payload and return a 200 OK response, otherwise return a 401 Unauthorized response
<?php
$shared_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$hmac_header = $_SERVER['HTTP_X_SHOPIFY_HMAC_SHA256'];
$data = file_get_contents('php://input');
$calculated_hmac = base64_encode(hash_hmac('sha256', $data, $shared_secret, true));
if ($hmac_header == $calculated_hmac) {
// HMAC is valid, process the request
// ...
http_response_code(200);
} else {
// HMAC is invalid, return a 401 response
http_response_code(401);
}
?>
Leave a Reply