Access reports of linked account with MCC account

92 views
Skip to first unread message

targaryen...@gmail.com

unread,
Oct 12, 2018, 7:04:27 AM10/12/18
to AdWords API and Google Ads API Forum
Hello dear community,

I opened this question already but can't find it somehow. So I hope this won't be a duplicate.

So I am stuck with a problem which I guess should be easy to solve but I am no expert and can't quite fix it. Just for reference: I work with Laravel 5.7 and Google Ads Api v201806

So what I want to achieve is this:

1. User logs in via oauth2

$oAuth2Credential = new OAuth2([
     
'authorizationUri' => 'https://accounts.google.com/o/oauth2/v2/auth',
     
'tokenCredentialUri' => 'https://www.googleapis.com/oauth2/v4/token',
     
'redirectUri' => '-',
     
'clientId' => '-',
     
'clientSecret' => -',
      '
scope' => 'https://www.googleapis.com/auth/adwords',
   
]);
   
if (!isset($_GET['code'])) {
      $oAuth2Credential
->setState(sha1(openssl_random_pseudo_bytes(1024)));
      $_SESSION
['oauth2state'] = $oAuth2Credential->getState();
      $config
= [
       
'access_type' => 'offline',
       
'prompt' => 'consent',
     
];
      header
('Location: ' . $oAuth2Credential->buildFullAuthorizationUri($config));
     
exit();
   
} elseif (empty($_GET['state'])
   
|| ($_GET['state'] !== $_SESSION['oauth2state'])) {
      unset
($_SESSION['oauth2state']);
     
exit('Invalid state.');
   
} else {
      $oAuth2Credential
->setCode($_GET['code']);
      $authToken
= $oAuth2Credential->fetchAuthToken();
      $refreshToken
= $authToken['refresh_token'];
   
}

2. Check if account is MCC. If it is not then proceed and get the reports (this works flawlessly with the same ajax call from beneath) and if it is then show the user a select field to select the account to get the reports from:

$session = $adWordsSessionBuilder->fromFile(config('app.adsapi_php_path'))
   
->withOAuth2Credential($oAuth2Credential)
   
->build();

    $customerService
= $adWordsServices->get(
      $session
,
     
CustomerService::class
   
);

$customerId
= $customerService->getCustomers()[0]->getCustomerId();
$canManageClients
= $customerService->getCustomers()[0]->getCanManageClients();

$session
= $adWordsSessionBuilder->fromFile(config('app.adsapi_php_path'))
   
->withOAuth2Credential($oAuth2Credential)
   
->withClientCustomerId($customerId)
   
->build();
      $_SESSION
['adsSession'] = $session;
if(!$canManageClients) return view('results.loading');
else {
      $managedCustomerService
= $adWordsServices->get(
        $session
,
       
ManagedCustomerService::class
     
);
      $selector
= new Selector();
      $selector
->setFields(['CustomerId', 'Name']);
      $selector
->setOrdering([new OrderBy('CustomerId', SortOrder::ASCENDING)]);
      $selector
->setPaging(new Paging(0, 500));
      $customers
= $managedCustomerService->get($selector)->getEntries();
     
return view('login.selectcid', compact('customers')) ;
}

3. Pass the selected ID via POST to the controller (and I pass the GET query string from the view before with code and state set). Then get the reports for the selected customerId:

if(!empty($request->clientCustomerId)) {
          $clientCustomerId = $request->clientCustomerId;
          $session = $adWordsSessionBuilder->fromFile(config('app.adsapi_php_path'))
          ->withOAuth2Credential($oAuth2Credential)
          ->withClientCustomerId($clientCustomerId)
          ->build();
          $_SESSION['adsSession'] = $session;
};
$_SESSION['clientCustomerId'] = $clientCustomerId;
return view('results.loading');

In this view I make some ajax calls (which work for logging in with a non mcc account) kinda like this:
    $session = $_SESSION['adsSession'];
    $query
= (new ReportQueryBuilder())
     
->select([
       
'Cost',
       
'Impressions',
       
'Clicks',
       
'Conversions',
       
'CostPerConversion',
       
'Ctr',
       
'AllConversionRate'
     
])
     
->from(ReportDefinitionReportType::CAMPAIGN_PERFORMANCE_REPORT)
     
->build();
    $reportDownloader
= new ReportDownloader($session);
    $reportSettingsOverride
= (new ReportSettingsBuilder())
       
->includeZeroImpressions(false)
       
->build();
        $reportDownloadResult
= $reportDownloader->downloadReportWithAwql(
            sprintf
('%s',$query),
           
DownloadFormat::XML,
            $reportSettingsOverride
         
);
    $json
= json_encode(
      simplexml_load_string
($reportDownloadResult->getAsString())
   
);
    $finalreports
= json_decode($json, true)['table'];
   
return $finalreports;

But I get the following error message (only with my MCC flow):

Client error: `POST https://oauth2.googleapis.com/token` resulted in a `401 Unauthorized` response:
{
 
"error": "unauthorized_client",
 
"error_description": "Unauthorized"
}


I'd appreciate any help! If you need more information please let me know.

Thanks to everybody in advance.









Teja Makani

unread,
Oct 12, 2018, 1:36:09 PM10/12/18
to AdWords API and Google Ads API Forum
Hello Alexander,

Looks like there is another thread going on for the same issue. To avoid confusion, I would recommend you to followup on that thread.

Regards,
Sai Teja, AdWords API Team.
Reply all
Reply to author
Forward
0 new messages