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.









-- 
-- 
=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~
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.
Visit this group at https://groups.google.com/group/adwords-api.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/adwords-api/4e94ff6f-f9b2-461c-b5fe-ffff3ab6a957%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
  • Access reports of l... targaryen . alexander

Reply via email to