diff --git a/src/lib/shopifyCollections.ts b/src/lib/shopifyCollections.ts new file mode 100644 index 0000000..5133df6 --- /dev/null +++ b/src/lib/shopifyCollections.ts @@ -0,0 +1,27 @@ +const API_VERSION = '2024-01' + +function getConfig() { + const domain = process.env.SHOPIFY_STORE_DOMAIN + const token = process.env.SHOPIFY_ADMIN_API_TOKEN + if (!domain || !token) throw new Error('SHOPIFY_STORE_DOMAIN et SHOPIFY_ADMIN_API_TOKEN requis') + return { + baseUrl: `https://${domain}/admin/api/${API_VERSION}`, + headers: { 'X-Shopify-Access-Token': token, 'Content-Type': 'application/json' }, + } +} + +export async function addProductToCollection(shopifyProductId: string, collectionId: string): Promise { + if (!collectionId?.trim()) return + const { baseUrl, headers } = getConfig() + const res = await fetch(`${baseUrl}/collects.json`, { + method: 'POST', + headers, + body: JSON.stringify({ collect: { product_id: shopifyProductId, collection_id: collectionId } }), + }) + if (!res.ok) { + const err = await res.text() + if (!err.includes('already') && !err.includes('taken')) { + throw new Error(`Shopify addToCollection error: ${res.status} — ${err}`) + } + } +}