Receiving Loyalty Accounts Rather than Loyalty Rewards

Hello there, I am trying to receive a list of loyalty rewards, but for some reason, it only gives me accounts rather than the rewards themselves. How would I go around fixing it? Thank you.

public function getAllRewards()
    {
        $client = new SquareClient([
            'accessToken' => env('SQUARE_TOKEN'),
            'environment' => Environment::PRODUCTION,
        ]);

        try {
            $loyaltyApi = $client->getLoyaltyApi();
            $response = $loyaltyApi->listLoyaltyRewards();

            if ($response->isSuccess()) {
                $rewards = $response->getResult()->getRewards();
                return $rewards;  
            } else {
                $errors = $response->getErrors();
                return response()->json(['error' => $errors]);
            }
        } catch (ApiException $e) {
            return response()->json(['error' => $e->getMessage()]);
        }
    }

:wave: I’m Square Dev AI, here to help answer your question!
Based on the information you’ve provided, the following documentation will help answer your question:

Additional Documentation

Loyalty Program Overview
Retrieve Loyalty Program
Create and Retrieve Loyalty Accounts

If this documentation helped you find a solution, please check the box indicating that this reply solves the problem.
Otherwise one of our Developer Advocates will provide additional assistance shortly.

The code you’ve shared is correct for retrieving a list of loyalty rewards using the Square Loyalty API. If you’re receiving a list of accounts instead of rewards, it’s possible that you might be calling the wrong function.

Ensure that you’re calling the listLoyaltyRewards() function to retrieve a list of loyalty rewards. If you’re trying to retrieve a list of loyalty accounts, you should be using the searchLoyaltyAccounts() function instead.

If you’re still facing issues, it might be helpful to check the response you’re getting from the API for any error messages or unexpected data.

This answer was reviewed by @Bryan-Square.

No, this does not answer the question still, I tried to make a new method, but still provides me the same result.

public function getAllRewards()
    {
        Log::info('getAllRewards method called');
    
        $accessToken = env('SQUARE_TOKEN');
        if (!$accessToken) {
            Log::error('SQUARE_TOKEN is not set in the environment');
            return response()->json(['error' => 'Internal server error.'], 500);
        }
    
        $client = new SquareClient([
            'accessToken'   => $accessToken,
            'environment'   => Environment::PRODUCTION,
        ]);
    
        $user = Auth::user();
        if (!$user) {
            Log::error('User is not authenticated');
            return response()->json(['error' => 'User is not authenticated.'], 401);
        }
    
        $loyaltyAccountId = $user->loyalty_account_id;
        Log::info('User authenticated', ['user_id' => $user->id, 'loyaltyAccountId' => $loyaltyAccountId]);
    
        if (empty($loyaltyAccountId)) {
            Log::error('Loyalty Account ID is missing for user', ['user_id' => $user->id]);
            return response()->json(['error' => 'Loyalty Account ID is missing.'], 400);
        }
    
        try {
            // Step 1: Fetch the Loyalty Program
            Log::info('Fetching Loyalty Program');
            $programResponse = Http::withHeaders([
                'Authorization' => 'Bearer ' . $accessToken,
                'Accept'        => 'application/json',
            ])->get("https://connect.squareup.com/v2/loyalty/programs/44d119e3-d3a2-47af-a6f1-7dadc27d7562");
    
            Log::info('Loyalty Program API Response:', ['response' => $programResponse->json()]);
    
            if (!$programResponse->successful()) {
                Log::error('Failed to fetch loyalty program', ['error' => $programResponse->json()]);
                return response()->json(['error' => 'Failed to fetch loyalty program.'], 400);
            }
    
            $program = $programResponse->json()['program'] ?? null;
            if (!$program) {
                Log::error('Loyalty program not found in API response.');
                return response()->json(['error' => 'Loyalty program not found.'], 404);
            }
    
            $rewardTiers = $program['reward_tiers'] ?? [];
            Log::info('Reward Tiers from Program:', ['tiers' => $rewardTiers]);
    
            if (empty($rewardTiers)) {
                Log::error('No reward tiers found in loyalty program.');
                return response()->json(['error' => 'No reward tiers found in the program.'], 404);
            }
    
            // Step 2: Fetch the Customer's Loyalty Account
            Log::info('Fetching Customer Loyalty Account');
            $accountResponse = Http::withHeaders([
                'Authorization' => 'Bearer ' . $accessToken,
                'Accept'        => 'application/json',
            ])->get("https://connect.squareup.com/v2/loyalty/accounts/{$loyaltyAccountId}");
    
            $accountData = $accountResponse->json();
            Log::info('Loyalty Account API Raw Response:', ['response' => $accountData]);
    
            if (!$accountResponse->successful()) {
                Log::error('Failed to fetch customer loyalty account', ['error' => $accountData]);
                return response()->json(['error' => 'Failed to fetch customer loyalty account.'], 400);
            }
    
            $account = $accountData['account'] ?? null;
            if (!$account) {
                Log::error('No loyalty account found in API response.');
                return response()->json(['error' => 'No loyalty account found for the customer.'], 404);
            }
    
            $customerPoints = $account['balance'] ?? 0;
            Log::info("Customer Points Balance:", ['points' => $customerPoints]);
    
            if ($customerPoints === 0) {
                Log::warning("Customer has zero loyalty points.");
                return response()->json(['error' => 'No rewards available based on the current points.'], 404);
            }
    
            // Step 3: Determine Available Rewards
            Log::info('Determining Available Rewards');
            $availableRewards = [];
    
            foreach ($rewardTiers as $rewardTier) {
                $pointsRequired = $rewardTier['points'] ?? 0;
                $rewardName = $rewardTier['name'] ?? 'Unknown Reward';
                $rewardId = $rewardTier['id'] ?? null;
    
                Log::info("Evaluating Reward", ['rewardName' => $rewardName, 'pointsRequired' => $pointsRequired, 'rewardId' => $rewardId]);
    
                if ($customerPoints >= $pointsRequired) {
                    $availableRewards[] = [
                        'id'            => $rewardId,
                        'rewardName'    => $rewardName,
                        'pointsRequired'=> $pointsRequired,
                        'discountType'  => $rewardTier['definition']['discount_type'] ?? '',
                        'discountValue' => $rewardTier['definition']['percentage_discount'] ?? 0,
                        'maxDiscount'   => $rewardTier['definition']['max_discount_money']['amount'] ?? 0,
                    ];
                }
            }
    
            if (!empty($availableRewards)) {
                Log::info('Available Rewards for Customer:', ['rewards' => $availableRewards]);
                return response()->json(['data' => $availableRewards], 200);
            } else {
                Log::warning('No rewards available based on customer points.', ['points' => $customerPoints]);
                return response()->json(['error' => 'No rewards available based on the current points.'], 404);
            }
        } catch (\Exception $e) {
            Log::error('Exception in getAllRewards:', ['exception' => $e->getMessage()]);
            return response()->json(['error' => 'An error occurred while fetching loyalty data.'], 500);
        }
    }