public function BingAccount(Request $request) { try { $apiKey = $request->header('x-api-key'); if (empty($apiKey)) { return response()->json(['error' => 'Please provide a valid API key.'], 400); } $user = User::where('api_key', $apiKey)->first(); if (empty($user)) { return response()->json(['error' => 'Invalid API key.'], 404); } // ----------------------------------------------------------------- // 1. Allowed account count (default 2) // ----------------------------------------------------------------- $accountCount = $user->adaccounts ?? 2; // ----------------------------------------------------------------- // 2. Bing access token // ----------------------------------------------------------------- $bing_user = BingToken::where('user_id', $user->id) ->whereNotNull('access_token_bing') ->first(); if (!$bing_user) { return response()->json(['error' => 'No Bing token found for this user.'], 404); } $access_token = $bing_user->access_token_bing; // ----------------------------------------------------------------- // 3. All accounts from Bing API // ----------------------------------------------------------------- $allAccounts = BingHelper::fetchBingAccounts($access_token, null); // ----------------------------------------------------------------- // 4. Customer ID (kept from your original code) // ----------------------------------------------------------------- $customerResponse = $this->getCustomerId($user->id); $customerData = $customerResponse->getData(true); $customerId = $customerData['customer_id'] ?? null; // ----------------------------------------------------------------- // 5. **UNIQUE & NON-NULL** connected account IDs from the log // ----------------------------------------------------------------- $connectedAccountIds = BingApiLogMonitor::whereNotNull('account_id') ->whereNotNull('api_key') ->where('api_key', $apiKey) ->orderBy('created_at', 'desc') ->pluck('account_id') // Collection of IDs ->filter() // removes null (extra safety) ->map(fn($id) => (string) $id) // force string for safe comparison ->unique() // **remove duplicates** ->values() // re-index ->toArray(); // dump($connectedAccountIds); // ----------------------------------------------------------------- // 6. Build response // ----------------------------------------------------------------- $result = []; if ($accountCount <= count($connectedAccountIds)) { // ---- LIMIT REACHED → show only logged accounts foreach ($allAccounts as $account) { $accountId = (string) $account['id']; if (in_array($accountId, $connectedAccountIds)) { $result[] = [ 'id' => $accountId, 'name' => $account['name'], 'customer_id' => $customerId, ]; } } } else { // ---- LIMIT NOT REACHED → show everything foreach ($allAccounts as $account) { $result[] = [ 'id' => (string) $account['id'], 'name' => $account['name'], 'customer_id' => $customerId, ]; } } return response()->json($result, 200); } catch (\Exception $e) { return response()->json(['error' => $e->getMessage()], 500); } } public static function fetchBingAccounts($accessToken, $customerId = null) { try { // Define SOAP WSDL and settings $wsdl = 'https://clientcenter.api.bingads.microsoft.com/Api/CustomerManagement/v13/CustomerManagementService.svc?singleWsdl'; $soapOptions = [ 'trace' => true, 'exceptions' => true, 'cache_wsdl' => WSDL_CACHE_NONE, ]; // Initialize SoapClient $client = new SoapClient($wsdl, $soapOptions); // Set SOAP headers for authentication $headers = [ new \SoapHeader( 'https://bingads.microsoft.com/Customer/v13', 'DeveloperToken', '107VJds1SPJ646669' // Replace with your developer token ), new \SoapHeader( 'https://bingads.microsoft.com/Customer/v13', 'AuthenticationToken', $accessToken ), ]; $client->__setSoapHeaders($headers); // Prepare GetAccountsInfo request $request = [ 'CustomerId' => $customerId, // Optional: null to use authenticated user's default customer 'OnlyParentAccounts' => false, // Set to true if you only want parent accounts ]; // Call GetAccountsInfo $response = $client->GetAccountsInfo($request); // Extract account names and customer IDs $accounts = []; if (!empty($response->AccountsInfo->AccountInfo)) { $accountsList = is_array($response->AccountsInfo->AccountInfo) ? $response->AccountsInfo->AccountInfo : [$response->AccountsInfo->AccountInfo]; foreach ($accountsList as $account) { // dump($account); $accounts[] = [ 'id' => $account->Id, 'name' => $account->Name, 'customer_id' => $account->Number, // Add CustomerId to the array ]; } } // Log::info('Bing Accounts Fetched: ', $accounts); return $accounts; } catch (\SoapFault $e) { Log::error("SOAP Fault: " . $e->getMessage()); Log::error("Last Request: " . $client->__getLastRequest()); Log::error("Last Response: " . $client->__getLastResponse()); return []; } catch (\Exception $e) { Log::error("General Error: " . $e->getMessage()); return []; } } public function getCustomerId($user_id) { // Retrieve credentials from .env $bing_user = BingToken::where('user_id', $user_id)->whereNotNull('access_token_bing')->first(); if (!$bing_user) { return response()->json([ 'success' => false, 'error' => 'No Bing access token found for the user.', ], 404); } $accessToken = $bing_user->access_token_bing; $developerToken = '107VJds1SPJ646669'; $wsdlUrl = 'https://clientcenter.api.bingads.microsoft.com/Api/CustomerManagement/v13/CustomerManagementService.svc?singleWsdl'; try { // Initialize SOAP client $options = [ 'trace' => true, 'exceptions' => true, 'features' => SOAP_SINGLE_ELEMENT_ARRAYS, ]; $client = new SoapClient($wsdlUrl, $options); // Prepare SOAP headers $headers = [ new \SoapHeader( 'https://bingads.microsoft.com/Customer/v13', 'DeveloperToken', $developerToken, false ), new \SoapHeader( 'https://bingads.microsoft.com/Customer/v13', 'AuthenticationToken', $accessToken, false ), ]; // Set SOAP headers $client->__setSoapHeaders($headers); // Prepare GetUser request $request = [ 'UserId' => null, // Set to null to get the current authenticated user ]; // Make the GetUser API call $response = $client->GetUser($request); // dump($response); // Extract customer ID from the response if (isset($response->CustomerRoles->CustomerRole[0]->CustomerId)) { $customerId = $response->CustomerRoles->CustomerRole[0]->CustomerId; return response()->json([ 'success' => true, 'customer_id' => $customerId, ]); } else { return response()->json([ 'success' => false, 'error' => 'No customer ID found in the response.', ], 404); } } catch (Exception $e) { // Handle errors return response()->json([ 'success' => false, 'error' => $e->getMessage(), 'request' => $client->__getLastRequest() ?? null, 'response' => $client->__getLastResponse() ?? null, ], 500); } }