使用shopify的API和PHP Laravel获取shopify商店上的所有客户数据

问题描述 投票:0回答:1

我试图使用以下方式从shopify api 获取所有客户数据。但问题是我只得到 250 个客户数据,不超过这个数字,尽管我有 6000 多个客户数据。我的代码有什么问题。

public function getCustomers($id)
    {
        // Fetch shop details
        $shop = DB::table('shopify_integrations')
            ->select('shop_url', 'id', 'access_token')
            ->where('user_id', Auth::user()->id)
            ->where('id', $id)
            ->first();

        if (!$shop) {
            return back()->withErrors(['error' => 'Shop not found']);
        }

        $customers = collect(); // Initialize collection for customers
        $nextPageUrl = "/admin/api/2025-01/customers.json"; // Initial endpoint
        $queryParams = ['limit' => 250]; // Query parameters

        do {
            // Make API call
            $response = self::shopify_call(
                $shop->access_token,
                $shop->shop_url,
                $nextPageUrl,
                $queryParams,
                'GET'
            );

            $responseBody = json_decode($response['response'], true);
            $headers = $response['headers'];

            // Debug: Log headers and next page URL
            Log::info('Headers:', $headers);
            Log::info('Response Body:', $responseBody);

            // Check if customers exist in response
            if (isset($responseBody['customers']) && is_array($responseBody['customers'])) {
                $customers = $customers->merge($responseBody['customers']);
            } else {
                dd('Error: Missing "customers" key in response', $responseBody, $headers);
            }

            usleep(500000); // Pause to avoid rate limits

            // Extract next page URL from headers
            $nextPageUrl = $this->getNextPageUrl($headers);

            // Reset queryParams for the next page
            $queryParams = [];

        } while ($nextPageUrl); // Continue until no next page
          Log::info('Link Header:', ['link' => $headers['link'] ?? 'No Link Header']);
          Log::info('Next Page URL:', ['url' => $nextPageUrl]);
          Log::info('Total Customers Fetched:', ['count' => $customers->count()]);
        // Pass all customers to the view
        return view('shopify.shopify_customers', ['customers' => $customers->toArray()]);
    }

    private function getNextPageUrl($headers)
    {
        if (isset($headers['link'])) {
            // Parse the Link header for rel="next"
            preg_match('/<(.*?)>; rel="next"/', $headers['link'], $matches);
            return $matches[1] ?? null; // Return next page URL or null if not found
        }
        return null; // No Link header, no next page
    }
php laravel shopify shopify-api
1个回答
0
投票

如果您不知道自己在做什么,请删除

$queryParams = ['limit' => 250];
并停止使用 ChatGPT。

© www.soinside.com 2019 - 2024. All rights reserved.