*MCC ID: *984-320-1347 *REQUEST CODE:* <?php session_start();
require_once 'vendor/autoload.php'; use GetOpt\GetOpt; use Google\Ads\GoogleAds\Examples\Utils\ArgumentNames; use Google\Ads\GoogleAds\Examples\Utils\ArgumentParser; use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder; use Google\Ads\GoogleAds\Lib\V5\GoogleAdsClient; use Google\Ads\GoogleAds\Lib\V5\GoogleAdsClientBuilder; use Google\Ads\GoogleAds\Lib\V5\GoogleAdsException; use Google\Ads\GoogleAds\Lib\V5\GoogleAdsServerStreamDecorator; use Google\Ads\GoogleAds\V5\Errors\GoogleAdsError; use Google\Ads\GoogleAds\V5\Resources\CustomerClient; use Google\Ads\GoogleAds\V5\Services\CustomerServiceClient; use Google\Ads\GoogleAds\V5\Services\GoogleAdsRow; use Google\ApiCore\ApiException; use Google\Auth\OAuth2; use Google\AdsApi\AdWords\AdWordsSessionBuilder; $oauth2 = new OAuth2([ 'authorizationUri' => 'https://accounts.google.com/o/oauth2/v2/auth', 'tokenCredentialUri' => 'https://www.googleapis.com/oauth2/v4/token', 'redirectUri' => 'http://example.com/index.php', 'clientId' => '******************.apps.googleusercontent.com', 'clientSecret' => '***************************', 'scope' => 'https://www.googleapis.com/auth/adwords', 'access_type' => 'offline', 'prompt' => 'consent', ]); if (!isset($_GET['code'])) { $oauth2->setState(sha1(openssl_random_pseudo_bytes(1024))); $_SESSION['oauth2state'] = $oauth2->getState(); $config = [ 'access_type' => 'offline' ]; header('Location: ' . $oauth2->buildFullAuthorizationUri($config)); exit; } elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) { unset($_SESSION['oauth2state']); exit('Invalid state.'); } else { $oauth2->setCode($_GET['code']); $authToken = $oauth2->fetchAuthToken(); $refresh_token = $authToken['access_token']; } $session = (new AdWordsSessionBuilder())->fromFile('getcustomerid.ini')->withOAuth2Credential($oauth2)->build(); $rand_file = "test.txt"; file_put_contents($rand_file, serialize($oauth2)); $_SESSION['oauth2'] = $rand_file; // die; /** * Gets the account hierarchy of the specified manager customer ID and login customer ID. If you * don't specify them, the example will instead print the hierarchies of all accessible customer * accounts for your authenticated Google account. Note that if the list of accessible customers * for your authenticated Google account includes accounts within the same hierarchy, this example * will retrieve and print the overlapping portions of the hierarchy for each accessible customer. */ class GetAccountHierarchy { // Optional: You may pass the manager customer ID on the command line or specify it here. If // neither are set, a null value will be passed to the runExample() method, and the example // will print the hierarchies of all accessible customer IDs. private const MANAGER_CUSTOMER_ID = null; // Optional: You may pass the login customer ID on the command line or specify it here if and // only if the manager customer ID is set. If the login customer ID is set neither on the // command line nor below, a null value will be passed to the runExample() method, and the // example will use each accessible customer ID as the login customer ID. private const LOGIN_CUSTOMER_ID = null; // Stores the mapping from the root customer IDs (the ones that will be used as a start point // for printing each hierarchy) to their `CustomerClient` objects. private static $rootCustomerClients = []; public static function main() { // Either pass the required parameters for this example on the command line, or insert them // into the constants above. $options = (new ArgumentParser())->parseCommandArguments([ ArgumentNames::MANAGER_CUSTOMER_ID => GetOpt::OPTIONAL_ARGUMENT, ArgumentNames::LOGIN_CUSTOMER_ID => GetOpt::OPTIONAL_ARGUMENT ]); $managerCustomerId = $options[ArgumentNames::MANAGER_CUSTOMER_ID] ?: self::MANAGER_CUSTOMER_ID; $loginCustomerId = $options[ArgumentNames::LOGIN_CUSTOMER_ID] ?: self::LOGIN_CUSTOMER_ID; if ($managerCustomerId xor $loginCustomerId) { throw new \InvalidArgumentException( 'Both the manager customer ID and login customer ID must be provided together, ' . 'or they must both be null.' ); } // Generate a refreshable OAuth2 credential for authentication. $oauth2 = unserialize(file_get_contents($_SESSION['oauth2'])); // Construct a Google Ads client configured from a properties file and the // OAuth2 credentials above. $googleAdsClient = (new GoogleAdsClientBuilder())->fromFile('google_ads_php.ini') ->withOAuth2Credential($oauth2) ->build(); try { self::runExample($googleAdsClient, $managerCustomerId, $loginCustomerId); } catch (GoogleAdsException $googleAdsException) { printf( "Request with ID '%s' has failed.%sGoogle Ads failure details:%s", $googleAdsException->getRequestId(), PHP_EOL, PHP_EOL ); foreach ($googleAdsException->getGoogleAdsFailure()->getErrors() as $error) { /** @var GoogleAdsError $error */ printf( "\t%s: %s%s", $error->getErrorCode()->getErrorCode(), $error->getMessage(), PHP_EOL ); } exit(1); } catch (ApiException $apiException) { printf( "ApiException was thrown with message '%s'.%s", $apiException->getMessage(), PHP_EOL ); exit(1); } } /** * Runs the example. * * @param GoogleAdsClient $googleAdsClient the Google Ads API client * @param int|null $managerCustomerId the manager customer ID * @param int|null $loginCustomerId the login customer ID */ public static function runExample( GoogleAdsClient $googleAdsClient, ?int $managerCustomerId, ?int $loginCustomerId ) { $rootCustomerIds = []; if (is_null($managerCustomerId)) { // We will get the account hierarchies for all accessible customers. $rootCustomerIds = self::getAccessibleCustomers($googleAdsClient); } else { // We will get only the hierarchy for the provided manager customer ID when it's // provided. $rootCustomerIds[] = $managerCustomerId; } $allHierarchies = []; $accountsWithNoInfo = []; // Constructs a map of account hierarchies. foreach ($rootCustomerIds as $rootCustomerId) { $customerClientToHierarchy = self::createCustomerClientToHierarchy($loginCustomerId, $rootCustomerId); if (is_null($customerClientToHierarchy)) { $accountsWithNoInfo[] = $rootCustomerId; } else { $allHierarchies += $customerClientToHierarchy; } } // Prints the IDs of any accounts that did not produce hierarchy information. if (!empty($accountsWithNoInfo)) { print 'Unable to retrieve information for the following accounts which are likely ' . 'either test accounts or accounts with setup issues. Please check the logs for ' . 'details:' . PHP_EOL; foreach ($accountsWithNoInfo as $accountId) { print $accountId . PHP_EOL; } print PHP_EOL; } // Prints the hierarchy information for all accounts for which there is hierarchy info // available. foreach ($allHierarchies as $rootCustomerId => $customerIdsToChildAccounts) { printf( "The hierarchy of customer ID %d is printed below:%s", $rootCustomerId, PHP_EOL ); self::printAccountHierarchy( self::$rootCustomerClients[$rootCustomerId], $customerIdsToChildAccounts, 0 ); print PHP_EOL; } } /** * Creates a map between a customer client and each of its managers' mappings. * * @param int|null $loginCustomerId the login customer ID used to create the GoogleAdsClient * @param int $rootCustomerId the ID of the customer at the root of the tree * @return array|null a map between a customer client and each of its managers' mappings if the * account hierarchy can be retrieved. If the account hierarchy cannot be retrieved, returns * null */ private static function createCustomerClientToHierarchy( ?int $loginCustomerId, int $rootCustomerId ): ?array { // Creates a GoogleAdsClient with the specified login customer ID. See // https://developers.google.com/google-ads/api/docs/concepts/call-structure#cid for more // information. // Generate a refreshable OAuth2 credential for authentication. $oauth2 = unserialize(file_get_contents($_SESSION['oauth2'])); // Construct a Google Ads client configured from a properties file and the // OAuth2 credentials above. $googleAdsClient = (new GoogleAdsClientBuilder())->fromFile('google_ads_php.ini') ->withOAuth2Credential($oauth2) ->withLoginCustomerId($loginCustomerId ?? $rootCustomerId) ->build(); // Creates the Google Ads Service client. $googleAdsServiceClient = $googleAdsClient->getGoogleAdsServiceClient(); // Creates a query that retrieves all child accounts of the manager specified in search // calls below. $query = 'SELECT customer_client.client_customer, customer_client.level,' . ' customer_client.manager, customer_client.descriptive_name,' . ' customer_client.currency_code, customer_client.time_zone,' . ' customer_client.id FROM customer_client WHERE customer_client.level <= 1'; $rootCustomerClient = null; // Adds the root customer ID to the list of IDs to be processed. $managerCustomerIdsToSearch = [$rootCustomerId]; // Performs a breadth-first search algorithm to build an associative array mapping // managers to their child accounts ($customerIdsToChildAccounts). $customerIdsToChildAccounts = []; while (!empty($managerCustomerIdsToSearch)) { $customerIdToSearch = array_shift($managerCustomerIdsToSearch); // Issues a search request by specifying page size. /** @var GoogleAdsServerStreamDecorator $stream */ try { $stream = $googleAdsServiceClient->searchStream( $customerIdToSearch, $query ); } catch(Exception $e) { echo "<pre>"; print_R($e); } // Iterates over all elements to get all customer clients under the specified customer's // hierarchy. foreach ($stream->iterateAllElements() as $googleAdsRow) { /** @var GoogleAdsRow $googleAdsRow */ $customerClient = $googleAdsRow->getCustomerClient(); // Gets the CustomerClient object for the root customer in the tree. if ($customerClient->getIdUnwrapped() === $rootCustomerId) { $rootCustomerClient = $customerClient; self::$rootCustomerClients[$rootCustomerId] = $rootCustomerClient; } // The steps below map parent and children accounts. Continue here so that managers // accounts exclude themselves from the list of their children accounts. if ($customerClient->getIdUnwrapped() === $customerIdToSearch) { continue; } // For all level-1 (direct child) accounts that are a manager account, the above // query will be run against them to create an associative array of managers to // their child accounts for printing the hierarchy afterwards. $customerIdsToChildAccounts[$customerIdToSearch][] = $customerClient; // Checks if the child account is a manager itself so that it can later be processed // and added to the map if it hasn't been already. if ($customerClient->getManagerUnwrapped()) { // A customer can be managed by multiple managers, so to prevent visiting // the same customer multiple times, we need to check if it's already in the // map. $alreadyVisited = array_key_exists( $customerClient->getIdUnwrapped(), $customerIdsToChildAccounts ); if (!$alreadyVisited && $customerClient->getLevelUnwrapped() === 1) { array_push($managerCustomerIdsToSearch, $customerClient->getIdUnwrapped()); } } } } return is_null($rootCustomerClient) ? null : [$rootCustomerClient->getIdUnwrapped() => $customerIdsToChildAccounts]; } /** * Retrieves a list of accessible customers with the provided set up credentials. * * @param GoogleAdsClient $googleAdsClient the Google Ads API client * @return int[] the list of customer IDs */ private static function getAccessibleCustomers(GoogleAdsClient $googleAdsClient): array { $accessibleCustomerIds = []; // Issues a request for listing all customers accessible by this authenticated Google // account. $customerServiceClient = $googleAdsClient->getCustomerServiceClient(); $accessibleCustomers = $customerServiceClient->listAccessibleCustomers(); print 'No manager customer ID is specified. The example will print the hierarchies of' . ' all accessible customer IDs:' . PHP_EOL; foreach ($accessibleCustomers->getResourceNames() as $customerResourceName) { $customer = CustomerServiceClient::parseName($customerResourceName)['customer']; print $customer . PHP_EOL; $accessibleCustomerIds[] = intval($customer); } print PHP_EOL; return $accessibleCustomerIds; } /** * Prints the specified account's hierarchy using recursion. * * @param CustomerClient $customerClient the customer client whose info will be printed and * its child accounts will be processed if it's a manager * @param array $customerIdsToChildAccounts a map from customer IDs to child * accounts * @param int $depth the current depth we are printing from in the * account hierarchy */ private static function printAccountHierarchy( CustomerClient $customerClient, array $customerIdsToChildAccounts, int $depth ) { if ($depth === 0) { print 'Customer ID (Descriptive Name, Currency Code, Time Zone)' . PHP_EOL; } $customerId = $customerClient->getIdUnwrapped(); print str_repeat('-', $depth * 2); printf( " %d ('%s', '%s', '%s')%s", $customerId, $customerClient->getDescriptiveNameUnwrapped(), $customerClient->getCurrencyCodeUnwrapped(), $customerClient->getTimeZoneUnwrapped(), PHP_EOL ); // Recursively call this function for all child accounts of $customerClient. if (array_key_exists($customerId, $customerIdsToChildAccounts)) { foreach ($customerIdsToChildAccounts[$customerId] as $childAccount) { self::printAccountHierarchy($childAccount, $customerIdsToChildAccounts, $depth + 1); } } } } GetAccountHierarchy::main(); *RESPONSE LOG:* ApiException was thrown with message '{ "message": "The caller does not have permission", "code": 7, "status": "PERMISSION_DENIED", "details": [ { "@type": 0, "data": "type.googleapis.com\/google.ads.googleads.v5.errors.GoogleAdsFailure" }, { "@type": 0, "data": [ { "errorCode": { "authorizationError": "MISSING_TOS" }, "message": "The developer must sign the terms of service. They can be found here: ads.google.com\/aw\/apicenter" } ] } ] }'. Thanks On Thursday, October 15, 2020 at 9:25:16 PM UTC+5:30 adsapiforumadvisor wrote: > Hi, > > Thank you for reaching out. As you said when you use the Google Ads API > with the same developer token it's not working, could you please share the > complete request and response logs along with the MCC account id associated > with the developer token via the *Reply privately to author* option for > us to further investigate? > > > > Thanks and regards, > Xiaoming, Google Ads API Team > > > [image: Google Logo] > Xiaoming > Google Ads API Team > > > ref:_00D1U1174p._5004Q268oue:ref > -- -- =~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~ Also find us on our blog: https://googleadsdeveloper.blogspot.com/ =~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~ You received this message because you are subscribed to the Google Groups "AdWords API and Google Ads API Forum" group. To post to this group, send email to adwords-api@googlegroups.com To unsubscribe from this group, send email to adwords-api+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/adwords-api?hl=en --- You received this message because you are subscribed to the Google Groups "AdWords API and Google Ads API Forum" group. To unsubscribe from this group and stop receiving emails from it, send an email to adwords-api+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/adwords-api/9bf0f35b-ba2f-416e-bb74-5f30a954f60cn%40googlegroups.com.