- Migration: shopify_variant_id on products_sizes, shopify_order_id on products_sales - ShopifyService: paginated REST client (2024-10 API) - shopify:map — one-time command to link variants by SKU - shopify:sync — reconciliation command (Shopify is master) - VerifyShopifyWebhook middleware: HMAC-SHA256 verification - ShopifyWebhookController: idempotent orders/paid handler, FIFO inventory deduction - Webhook route: POST /api/webhooks/shopify/orders-paid Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 4.6
parent
f54b471848
commit
467d85dfec
@@ -0,0 +1,73 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class ShopifyService
|
||||
{
|
||||
private string $baseUrl;
|
||||
private string $token;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$domain = config('services.shopify.domain');
|
||||
$version = config('services.shopify.api_version');
|
||||
$this->baseUrl = "https://{$domain}/admin/api/{$version}";
|
||||
$this->token = config('services.shopify.access_token');
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns all product variants from Shopify.
|
||||
* Each entry: ['id', 'sku', 'inventory_quantity', 'product_title']
|
||||
*/
|
||||
public function getAllVariants(): array
|
||||
{
|
||||
$variants = [];
|
||||
$url = "{$this->baseUrl}/products.json?limit=250&fields=id,title,variants";
|
||||
|
||||
while ($url) {
|
||||
$response = Http::withHeader('X-Shopify-Access-Token', $this->token)->get($url);
|
||||
|
||||
if ($response->failed()) {
|
||||
Log::error('Shopify API error', ['status' => $response->status(), 'body' => $response->body()]);
|
||||
break;
|
||||
}
|
||||
|
||||
foreach ($response->json('products', []) as $product) {
|
||||
foreach ($product['variants'] as $variant) {
|
||||
$variants[] = [
|
||||
'id' => (string) $variant['id'],
|
||||
'sku' => $variant['sku'] ?? '',
|
||||
'inventory_quantity' => (int) ($variant['inventory_quantity'] ?? 0),
|
||||
'product_title' => $product['title'],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
// Follow Shopify's Link header pagination
|
||||
$url = $this->nextPageUrl($response->header('Link'));
|
||||
|
||||
if ($url) {
|
||||
usleep(500_000); // 0.5s — stay well within 2 req/s limit
|
||||
}
|
||||
}
|
||||
|
||||
return $variants;
|
||||
}
|
||||
|
||||
private function nextPageUrl(?string $linkHeader): ?string
|
||||
{
|
||||
if (!$linkHeader) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Link: <https://...?page_info=abc>; rel="next"
|
||||
if (preg_match('/<([^>]+)>;\s*rel="next"/', $linkHeader, $m)) {
|
||||
return $m[1];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user