Yeah that’s odd, my log says otherwise. Even though, my log says it returns nothing. I have tested the API on the playground, but it shows the data unlike the console.log. Thank you for the quick response.
local.INFO: Category Response: []
Here is the full code if needed.
<?php
namespace App\Http\Controllers;
use Square\SquareClient;
use Square\Environment;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Square\Models\ListLoyaltyRewardsRequest;
class SquareController extends Controller
{
public function getCatalogItems()
{
$accessToken = env('SQUARE_TOKEN');
$url = 'https://connect.squareup.com/v2/catalog/list';
//$url = 'https://connect.squareupsandbox.com/v2/catalog/list';
$response = Http::withHeaders([
'Authorization' => 'Bearer ' . $accessToken,
'Accept' => 'application/json',
])->get($url);
if ($response->successful()) {
$catalogItems = $response->json();
return response()->json(['catalog_items' => $catalogItems]);
} else {
$error = $response->json();
return response()->json(['error' => $error], $response->status());
}
}
public function getAllItems()
{
$accessToken = env('SQUARE_TOKEN');
$url = 'https://connect.squareup.com/v2/catalog/list';
//$url = 'https://connect.squareupsandbox.com/v2/catalog/list';
$response = Http::withHeaders([
'Authorization' => 'Bearer ' . $accessToken,
'Accept' => 'application/json',
])->get($url);
if ($response->successful()) {
$catalogItems = $response->json()['objects'];
$items = [];
$fillings = [];
$categories = [];
foreach ($catalogItems as $catalogItem) {
if ($catalogItem['type'] === 'CATEGORY') {
$categoryId = $catalogItem['id'];
$categoryName = $catalogItem['category_data']['name'];
$categories[$categoryId] = $categoryName;
}
}
foreach ($catalogItems as $catalogItem) {
if ($catalogItem['type'] === 'ITEM') {
$itemId = $catalogItem['id'];
$itemName = $catalogItem['item_data']['name'];
$itemDescription = $catalogItem['item_data']['description'] ?? 'No description available';
$itemImageIds = $catalogItem['item_data']['image_ids'] ?? [];
$itemVariations = $catalogItem['item_data']['variations'];
$itemFillingIds = $catalogItem['item_data']['modifier_list_info'] ?? [];
$itemCategoryName = [];
if (isset($catalogItem['item_data']['categories']) && is_array($catalogItem['item_data']['categories'])) {
foreach ($catalogItem['item_data']['categories'] as $category) {
$categoryId = $category['id'];
$categoryName = $categories[$categoryId] ?? 'Uncategorized';
$itemCategoryName[] = $categoryName;
}
} else {
$itemCategoryNames[] = 'Uncategorized';
}
if (!is_array($itemImageIds)) {
$itemImageIds = [];
}
if (!is_array($itemFillingIds)) {
$itemFillingIds = [];
}
$images = [];
foreach ($itemImageIds as $imageId) {
//$imageUrl = "https://connect.squareupsandbox.com/v2/catalog/object/$imageId";
$imageUrl = "https://connect.squareup.com/v2/catalog/object/$imageId";
$imageResponse = Http::withHeaders([
'Authorization' => 'Bearer ' . $accessToken,
])->get($imageUrl);
if ($imageResponse->successful()) {
$imageData = $imageResponse->json()['object']['image_data'];
$imageUrl = $imageData['url'];
$images[] = $imageUrl;
} else {
$error = $imageResponse->json();
info('Error fetching image URL for image ID ' . $imageId . ': ' . json_encode($error));
}
}
$itemPrice = null;
$variationDetails = [];
foreach ($itemVariations as $variation) {
$variationDetails[] = [
'variationId' => $variation['id'],
'variationName' => $variation['item_variation_data']['name'],
'variationPrice' => $variation['item_variation_data']['price_money']['amount'] ?? 0
];
if (isset($variation['item_variation_data']['price_money']['amount'])) {
$itemPrice = $variation['item_variation_data']['price_money']['amount'];
}
}
// Get tax rate from Square API
$taxRate = $this->getTaxRateFromSquareApi($itemId);
Log::info('Tax Rate for item ' . $itemId . ': ' . $taxRate);
// Calculate tax amount
$taxAmount = ceil(($itemPrice * $taxRate) / 100);
Log::info('Tax Amount for item ' . $itemId . ': ' . $taxAmount);
$itemFillings = [];
foreach ($itemFillingIds as $itemFillingId) {
//$modifierUrl = "https://connect.squareupsandbox.com/v2/catalog/object/{$itemFillingId['modifier_list_id']}";
$modifierUrl = "https://connect.squareup.com/v2/catalog/object/{$itemFillingId['modifier_list_id']}";
$modifierResponse = Http::withHeaders([
'Authorization' => 'Bearer ' . $accessToken,
])->get($modifierUrl);
if ($modifierResponse->successful()) {
$modifierListData = $modifierResponse->json()['object']['modifier_list_data'];
$modifierListName = $modifierListData['name'];
foreach ($modifierListData['modifiers'] as $modifier) {
$modifierName = $modifier['modifier_data']['name'];
$modifierId = $modifier['id'];
$modifierPrice = $modifier['modifier_data']['price_money']['amount'];
$itemFillings[] = [
'modifierListName' => $modifierListName,
'modifierId' => $modifierId,
'modifierName' => $modifierName,
'modifierPrice' => $modifierPrice
];
}
} else {
$error = $modifierResponse->json();
info('Error fetching modifier list for modifier list ID ' . $itemFillingId['modifier_list_id'] . ': ' . json_encode($error));
}
}
Log::info('Item Fillings', ['itemFillings' => $itemFillings]);
$items[] = [
'id' => $itemId,
'name' => $itemName,
'description' => $itemDescription,
'price' => $itemPrice,
'tax_amount' => $taxAmount,
'tax_rate' => intval($taxRate),
'images' => $images,
'variations' => $variationDetails,
'fillings' => $itemFillings,
'categories' => $itemCategoryName
];
}
}
Log::info('Items:', $items);
return response()->json($items);
} else {
$error = $response->json();
Log::info('Error:', $error);
return response()->json(['error' => $error], $response->status());
}
}
private function getTaxRateFromSquareApi($itemId)
{
// Debug statement to verify method invocation
Log::info('getTaxRateFromSquareApi called for item ID: ' . $itemId);
$accessToken = env('SQUARE_TOKEN');
$url = "https://connect.squareup.com/v2/catalog/object/$itemId";
//$url = "https://connect.squareupsandbox.com/v2/catalog/object/$itemId";
$response = Http::withHeaders([
'Authorization' => 'Bearer ' . $accessToken,
'Accept' => 'application/json',
])->get($url);
if ($response->successful()) {
$itemData = $response->json()['object'];
$taxRateId = $itemData['item_data']['tax_ids'][0] ?? null;
if ($taxRateId) {
Log::info('Tax Rate Id: ' . $taxRateId);
// Get tax rate details from Square API
$taxRateDetails = $this->getTaxRateDetailsFromSquareApi($taxRateId);
if ($taxRateDetails) {
Log::info('Tax Rate Details: ' . json_encode($taxRateDetails));
$taxPercentage = $taxRateDetails['percentage'] ?? 0;
return intval($taxPercentage);
} else {
Log::info('Tax Rate details not found for tax ID: ' . $taxRateId);
}
} else {
Log::info('No tax rate ID found for item ID: ' . $itemId);
}
} else {
$error = $response->json();
Log::info('Error fetching tax rate for item ID ' . $itemId . ': ' . json_encode($error));
}
// Default to 0 if there's an error or tax rate is not found
return 0;
}
private function getTaxRateDetailsFromSquareApi($taxRateId)
{
$accessToken = env('SQUARE_TOKEN');
$url = "https://connect.squareup.com/v2/catalog/object/$taxRateId";
//$url = "https://connect.squareupsandbox.com/v2/catalog/object/$taxRateId";
$response = Http::withHeaders([
'Authorization' => 'Bearer ' . $accessToken,
'Accept' => 'application/json',
])->get($url);
if ($response->successful()) {
return $response->json()['object']['tax_data'];
} else {
$error = $response->json();
Log::error('Error fetching tax rate details for tax rate ID ' . $taxRateId . ': ' . json_encode($error));
return null;
}
}
public function getItemData(Request $request, $itemId)
{
$accessToken = env('SQUARE_TOKEN');
$url = 'https://connect.squareup.com/v2/catalog/list';
//$url = 'https://connect.squareupsandbox.com/v2/catalog/list';
$response = Http::withHeaders([
'Authorization' => 'Bearer ' . $accessToken,
'Accept' => 'application/json',
])->get($url);
if ($response->successful()) {
$catalogItems = $response->json()['objects'];
// Search for the item with the given ID
foreach ($catalogItems as $catalogItem) {
if ($catalogItem['type'] === 'ITEM' && $catalogItem['id'] === $itemId) {
$itemName = $catalogItem['item_data']['name'];
// Initialize itemDescription
$itemDescription = '';
// Extract description from variations
$itemDescription = $catalogItem['item_data']['description'] ?? 'No description available';
// Extract price from the first variation
$itemPrice = $catalogItem['item_data']['variations'][0]['item_variation_data']['price_money']['amount'] ?? null; // Assuming single variation
$itemImageIds = $catalogItem['item_data']['image_ids'] ?? [];
return response()->json([
'name' => $itemName,
'description' => $itemDescription,
'price' => $itemPrice,
'image_ids' => $itemImageIds,
]);
}
}
return response()->json(['error' => 'Item not found.'], 404);
} else {
$error = $response->json();
return response()->json(['error' => $error], $response->status());
}
}
public function getCategoryData()
{
$accessToken = env('SQUARE_TOKEN');
$url = 'https://connect.squareup.com/v2/catalog/list';
//$url = 'https://connect.squareupsandbox.com/v2/catalog/list';
$response = Http::withHeaders([
'Authorization' => 'Bearer ' . $accessToken,
'Accept' => 'application/json',
])->get($url);
if ($response->successful()) {
$catalogItems = $response->json()['objects'];
$categories = [];
// Iterate over all objects in the API response
foreach ($catalogItems as $catalogItem) {
// Check if the object is of type "CATEGORY"
if ($catalogItem['type'] === 'CATEGORY') {
$categoryId = $catalogItem['id'];
$categoryName = $catalogItem['category_data']['name'] ?? '';
$categoryImageIds = $catalogItem['category_data']['image_ids'] ?? [];
if (!is_array($categoryImageIds)) {
$categoryImageIds = [];
}
$images = [];
foreach ($categoryImageIds as $imageId) {
//$imageUrl = "https://connect.squareupsandbox.com/v2/catalog/object/$imageId";
$imageUrl = "https://connect.squareup.com/v2/catalog/object/$imageId";
$imageResponse = Http::withHeaders([
'Authorization' => 'Bearer ' . $accessToken,
])->get($imageUrl);
if ($imageResponse->successful()) {
$imageData = $imageResponse->json()['object']['image_data'];
$imageUrl = $imageData['url'];
$images[] = $imageUrl;
} else {
$error = $imageResponse->json();
info('Error fetching image URL for image ID ' . $imageId . ': ' . json_encode($error));
}
}
// Create a category object with ID and name
$category = [
'id' => $categoryId,
'name' => $categoryName,
'image' => $images
];
// Add the category object to the categories array
$categories[] = $category;
}
}
Log::info('Category Response: ' . json_encode($categories));
// Return the categories array as JSON response
return response()->json($categories);
} else {
$error = $response->json();
return response()->json(['error' => $error], $response->status());
}
}
public function getAllRewards()
{
$accessToken = env('SQUARE_TOKEN');
$client = new SquareClient([
'accessToken' => $accessToken,
'environment' => Environment::PRODUCTION,
]);
$user = Auth::user();
$loyaltyAccountId = $user->loyalty_account_id;
try {
// Step 1: Fetch the loyalty program
$programResponse = Http::withHeaders([
'Authorization' => 'Bearer ' . $accessToken,
'Accept' => 'application/json',
])->get("https://connect.squareup.com/v2/loyalty/programs");
Log::info('Loyalty Program Response:', ['response' => $programResponse->json()]);
if ($programResponse->successful()) {
$program = $programResponse->json()['programs'][0] ?? null; // Adjust based on response structure
if (!$program) {
return response()->json(['error' => 'No main loyalty program found.'], 404);
}
// Step 2: Fetch the customer's loyalty account
$accountResponse = Http::withHeaders([
'Authorization' => 'Bearer ' . $accessToken,
'Accept' => 'application/json',
])->get("https://connect.squareup.com/v2/loyalty/accounts/{$loyaltyAccountId}");
Log::info('Loyalty Account Response:', ['response' => $accountResponse->json()]);
if ($accountResponse->successful()) {
$account = $accountResponse->json()['account'] ?? null;
if (!$account) {
return response()->json(['error' => 'No loyalty account found for the customer.'], 404);
}
$customerPoints = $account['balance'] ?? 0;
// Step 3: Compare customer's points with reward tiers
$availableRewards = [];
if (isset($program['reward_tiers']) && count($program['reward_tiers']) > 0) {
foreach ($program['reward_tiers'] as $rewardTier) {
$pointsRequired = $rewardTier['points'];
if ($customerPoints >= $pointsRequired) {
$availableRewards[] = [
'rewardName' => $rewardTier['name'],
'pointsRequired' => $pointsRequired,
'discountType' => $rewardTier['definition']['discount_type'] ?? '',
'discountValue' => $rewardTier['definition']['percentage_discount'] ?? 0,
'maxDiscount' => $rewardTier['definition']['max_discount_money']['amount'] ?? 0,
];
}
}
if (count($availableRewards) > 0) {
Log::info('Available Rewards:', $availableRewards);
return response()->json(['data' => $availableRewards], 200);
} else {
Log::info('No rewards available for the customer\'s current points.');
return response()->json(['error' => 'No rewards available based on the current points.'], 404);
}
} else {
Log::warning('No reward tiers found in the loyalty program.');
return response()->json(['error' => 'No reward tiers found in the program.'], 404);
}
} else {
Log::error('Failed to fetch customer loyalty account:', ['error' => $accountResponse->json()]);
return response()->json(['error' => 'Failed to fetch customer loyalty account.'], 400);
}
} else {
Log::error('Failed to fetch loyalty program:', ['error' => $programResponse->json()]);
return response()->json(['error' => 'Failed to fetch loyalty program.'], 400);
}
} catch (\Exception $e) {
Log::error('Exception fetching loyalty program or rewards:', ['exception' => $e->getMessage()]);
return response()->json(['error' => 'An error occurred while fetching loyalty data.'], 500);
}
}
}