index-shop/site/config/shopify.php

83 lines
2.1 KiB
PHP
Raw Permalink Normal View History

<?php
/**
* Récupère les produits Shopify avec cache (TTL 1h)
*/
function getShopifyProducts(): array
{
$cache = kirby()->cache('shopify');
$products = $cache->get('products');
if ($products === null) {
$products = fetchShopifyProducts();
$cache->set('products', $products, 60); // Cache 60 minutes
}
return $products;
}
/**
* Appel direct à l'API Shopify Storefront
*/
function fetchShopifyProducts(): array
{
$domain = 'nv7cqv-bu.myshopify.com';
$token = 'dec3d35a2554384d149c72927d1cfd1b';
$apiVersion = '2026-01';
$endpoint = "https://{$domain}/api/{$apiVersion}/graphql.json";
$query = '
query getAllProducts {
products(first: 250, sortKey: TITLE) {
edges {
node {
id
handle
title
}
}
}
}
';
$ch = curl_init($endpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Nécessaire pour dev local sur Windows
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'X-Shopify-Storefront-Access-Token: ' . $token
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
'query' => $query
]));
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode !== 200) {
error_log("Shopify API error: HTTP {$httpCode}");
return [];
}
$data = json_decode($response, true);
if (isset($data['errors'])) {
error_log("Shopify API GraphQL errors: " . json_encode($data['errors']));
return [];
}
$products = [];
foreach ($data['data']['products']['edges'] as $edge) {
$node = $edge['node'];
$products[] = [
'id' => $node['id'],
'handle' => $node['handle'],
'title' => $node['title']
];
}
return $products;
}