admin管理员组

文章数量:1123145

I was trying to get all the customers data from shopify api using following way. But the problem i only get 250 customers data not more than that Though i have 6000+ customers data. What's problem with my code.

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
    }

本文标签: Fetch all customers data on shopify store using shopify39s API amp PHP LaravelStack Overflow