I’m developing a Node.js application using Express to handle Shopify webhooks for product updates and creations. My goal is to verify the HMAC signature provided by Shopify to ensure the request’s integrity. However, I’m encountering a persistent issue where the generated HMAC in my application does not match the HMAC provided by Shopify.
What I Want to Achieve:
Whenever a product is created or updated in Shopify, I want to:
- Check the vendor name of the product.
- If a collection for that vendor does not exist, create a new automated collection for the vendor.
- Add the product to the collection where the vendor name matches the collection.
Problem:
The HMAC signature generated in my Node.js application does not match the HMAC signature provided by Shopify in the headers.
Current Code:
const express = require('express');
const crypto = require('crypto');
const axios = require('axios');
const getRawBody = require('raw-body');
const contentType = require('content-type');
const app = express();
const PORT = process.env.PORT || 3000;
// Replace with your actual Shopify Webhook secret key
const SHOPIFY_WEBHOOK_SECRET = 'your_shopify_webhook_secret';
const SHOPIFY_API_KEY = 'your_shopify_api_key';
const SHOPIFY_PASSWORD = 'your_shopify_password';
const SHOPIFY_STORE_URL = 'your_shopify_store_url';
const API_VERSION = 'your_api_version';
// Middleware to capture raw body
const generateRawBody = (req, res, next) => {
getRawBody(
req,
{
length: req.headers['content-length'],
limit: '99mb',
encoding: contentType.parse(req).parameters.charset,
},
(err, string) => {
if (err) return next(err);
req.rawBody = string;
next();
}
);
};
const verifyShopifyWebhook = (req, res, next) => {
const hmacHeader = req.headers['x-shopify-hmac-sha256'];
const body = req.rawBody;
// Ensure the body is treated as a buffer for the HMAC calculation
const generatedHash = crypto
.createHmac('sha256', SHOPIFY_WEBHOOK_SECRET)
.update(body)
.digest('base64');
console.log('Raw Body:', body.toString('utf8'));
console.log('Headers:', req.headers);
console.log('Shopify HMAC:', hmacHeader);
console.log('Generated HMAC:', generatedHash);
if (generatedHash === hmacHeader) {
req.body = JSON.parse(body);
next();
} else {
res.status(403).send("Couldn't verify incoming Webhook request!");
}
};
const createAutomatedCollection = async (vendor) => {
try {
console.log('Fetching existing collections...');
const collectionsResponse = await axios.get(`https://${SHOPIFY_API_KEY}:${SHOPIFY_PASSWORD}@${SHOPIFY_STORE_URL}/admin/api/${API_VERSION}/custom_collections.json`);
const collections = collectionsResponse.data.custom_collections;
const vendorCollection = collections.find(collection => collection.title === vendor);
if (!vendorCollection) {
console.log(`Creating new automated collection for vendor: ${vendor}`);
await axios.post(`https://${SHOPIFY_API_KEY}:${SHOPIFY_PASSWORD}@${SHOPIFY_STORE_URL}/admin/api/${API_VERSION}/custom_collections.json`, {
custom_collection: {
title: vendor,
body_html: `Automated collection for vendor ${vendor}`,
published: true,
rules: [
{
column: 'vendor',
relation: 'equals',
condition: vendor
}
]
}
});
console.log('Automated collection created successfully.');
} else {
console.log('Collection for vendor already exists:', vendor);
}
} catch (error) {
console.error('Error creating collection:', error.response ? error.response.data : error.message);
}
};
app.post('/webhook/product-create', generateRawBody, verifyShopifyWebhook, async (req, res) => {
const product = req.body;
console.log('Received Product:', product);
await createAutomatedCollection(product.vendor);
res.status(200).send('Webhook received');
});
app.post('/webhook/product-update', generateRawBody, verifyShopifyWebhook, async (req, res) => {
const product = req.body;
console.log('Received Product Update:', product);
await createAutomatedCollection(product.vendor);
res.status(200).send('Webhook received');
});
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Debugging Information:
- The raw body captured from the webhook:
{"admin_graphql_api_id":"gid://shopify/Product/9491952927015","body_html":"u003cpu003eBlue silk tuxedo with marbled aquatic pattern and dark lining. Sleeves are complete with rounded hem and black buttons. u003c/pu003e","created_at":"2024-08-05T07:48:51-07:00","handle":"blue-silk-tuxedo-copy","id":9491952927015,"product_type":"Tuxedo","published_at":"2024-08-05T07:48:50-07:00","template_suffix":null,"title":"Blue Silk Tuxedo Copy Product","updated_at":"2024-08-05T07:58:49-07:00","vendor":"Mahi Two","status":"active","published_scope":"web","tags":"men, silk, tuxedo","variants":[{"admin_graphql_api_id":"gid://shopify/ProductVariant/48952763253031","barcode":null,"compare_at_price":null,"created_at":"2024-08-05T07:48:51-07:00","id":48952763253031,"inventory_policy":"deny","position":1,"price":"70.00","product_id":9491952927015,"sku":null,"taxable":true,"title":"Small","updated_at":"2024-08-05T07:48:51-07:00","option1":"Small","option2":null,"option3":null,"image_id":null,"inventory_item_id":50961093689639,"inventory_quantity":0,"old_inventory_quantity":0},{"admin_graphql_api_id":"gid://shopify/ProductVariant/48952763285799","barcode":null,"compare_at_price":null,"created_at":"2024-08-05T07:48:51-07:00","id":48952763285799,"inventory_policy":"deny","position":2,"price":"70.00","product_id":9491952927015,"sku":null,"taxable":true,"title":"Medium","updated_at":"2024-08-05T07:48:51-07:00","option1":"Medium","option2":null,"option3":null,"image_id":null,"inventory_item_id":50961093722407,"inventory_quantity":0,"old_inventory_quantity":0},{"admin_graphql_api_id":"gid://shopify/ProductVariant/48952763318567","barcode":null,"compare_at_price":null,"created_at":"2024-08-05T07:48:51-07:00","id":48952763318567,"inventory_policy":"deny","position":3,"price":"70.00","product_id":9491952927015,"sku":null,"taxable":true,"title":"Large","updated_at":"2024-08-05T07:48:51-07:00","option1":"Large","option2":null,"option3":null,"image_id":null,"inventory_item_id":50961093755175,"inventory_quantity":0,"old_inventory_quantity":0}],"options":[{"name":"Title","id":11903875514663,"product_id":9491952927015,"position":1,"values":["Small","Medium","Large"]}],"images":[],"image":null,"media":[],"variant_gids":[{"admin_graphql_api_id":"gid://shopify/ProductVariant/48952763253031","updated_at":"2024-08-05T14:48:51.000Z"},{"admin_graphql_api_id":"gid://shopify/ProductVariant/48952763285799","updated_at":"2024-08-05T14:48:51.000Z"},{"admin_graphql_api_id":"gid://shopify/ProductVariant/48952763318567","updated_at":"2024-08-05T14:48:51.000Z"}]}
- The headers received:
{
"host": "ccd1-39-34-196-154.ngrok-free.app",
"user-agent": "Shopify-Captain-Hook",
"content-length": "2588",
"accept": "*/*",
"accept-encoding": "gzip;q=1.0,deflate;q=0.6,identity;q=0.3",
"content-type": "application/json",
"x-forwarded-for": "34.123.146.212",
"x-forwarded-host": "ccd1-39-34-196-154.ngrok-free.app",
"x-forwarded-proto": "https",
"x-shopify-api-version": "2024-07",
"x-shopify-event-id": "5b79dfd5-3a5b-4cb1-beca-58585be78467",
"x-shopify-hmac-sha256": "V3TBvd630SKRS75H4/4CeF7kkVgV4A22+7fh2FjYTpY=",
"x-shopify-product-id": "9491952927015",
"x-shopify-shop-domain": "c2-saad-sajid.myshopify.com",
"x-shopify-topic": "products/update",
"x-shopify-triggered-at": "2024-08-05T14:58:49Z",
"x-shopify-webhook-id": "2f3d8c0f-4006-4db3-a87f-ec6eb393725a"
}
- Shopify HMAC: V3TBvd630SKRS75H4/4CeF7kkVgV4A22+7fh2FjYTpY=
- Generated HMAC: 2t26gy7++w26mMqwCvqBJl/uGDRl/1jUrB2qA2ZCJMQ=
What I’ve Tried:
- Ensuring the raw body is captured correctly using getRawBody.
- Treating the body as a buffer for HMAC calculation.
- Logging the raw body, headers, and both HMACs for debugging.
Despite these efforts, the generated HMAC does not match the one provided by Shopify. Any help or guidance on resolving this mismatch would be greatly appreciated.
Environment:
- Node.js version: v20.15.0
- Express version: 4.19.2