Loading...
Complete integration with webhooks, Liquid snippets, bulk processing scripts, and theme app extensions.
// Shopify Webhook Handler - Save as: pages/api/shopify/product-created.js (Next.js)
// Or deploy as serverless function
import crypto from 'crypto';
const SHOPIFY_SECRET = 'YOUR_SHOPIFY_WEBHOOK_SECRET';
const BUTTERFLY_API_KEY = 'YOUR_BUTTERFLY_API_KEY';
const SHOPIFY_ACCESS_TOKEN = 'YOUR_SHOPIFY_ACCESS_TOKEN';
const SHOPIFY_STORE = 'yourstore.myshopify.com';
export default async function handler(req, res) {
if (req.method !== 'POST') {
return res.status(405).json({ error: 'Method not allowed' });
}
// Verify webhook signature
const hmac = req.headers['x-shopify-hmac-sha256'];
const body = JSON.stringify(req.body);
const hash = crypto
.createHmac('sha256', SHOPIFY_SECRET)
.update(body, 'utf8')
.digest('base64');
if (hmac !== hash) {
return res.status(401).json({ error: 'Invalid signature' });
}
const product = req.body;
// Process each product image
for (const image of product.images || []) {
try {
// Remove background with ButterflyAPI
const processedImage = await processWithButterfly(image.src, 'background-remove');
// Update Shopify product image
await updateShopifyImage(product.id, image.id, processedImage);
console.log(`Processed image ${image.id} for product ${product.id}`);
} catch (error) {
console.error(`Error processing image ${image.id}:`, error);
}
}
res.status(200).json({ success: true });
}
async function processWithButterfly(imageUrl, action) {
const response = await fetch('https://butterflyapi.com/api/v1/run', {
method: 'POST',
headers: {
'Authorization': `Bearer ${BUTTERFLY_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
api: action,
imageUrl: imageUrl,
}),
});
const data = await response.json();
if (data.error) {
throw new Error(data.error);
}
return data.outputUrl;
}
async function updateShopifyImage(productId, imageId, newImageUrl) {
const response = await fetch(
`https://${SHOPIFY_STORE}/admin/api/2024-01/products/${productId}/images/${imageId}.json`,
{
method: 'PUT',
headers: {
'X-Shopify-Access-Token': SHOPIFY_ACCESS_TOKEN,
'Content-Type': 'application/json',
},
body: JSON.stringify({
image: {
id: imageId,
src: newImageUrl,
},
}),
}
);
if (!response.ok) {
throw new Error(`Shopify API error: ${response.status}`);
}
return response.json();
}Get your ButterflyAPI key from your dashboard
Get Shopify API credentials from your Shopify Admin → Settings → Apps → Develop apps
BUTTERFLY_API_KEY=your_butterflyapi_key SHOPIFY_ACCESS_TOKEN=your_shopify_token SHOPIFY_STORE=yourstore.myshopify.com SHOPIFY_WEBHOOK_SECRET=your_webhook_secret
In Shopify Admin → Settings → Notifications → Webhooks:
Deploy your webhook handler and create a test product to verify the integration works
Need help with Shopify integration?