Hello dear community,

I am stuck with a problem which should be easy to solve but I am no expert 
and can't get it quite right. Just for clarification: I use Laravel 5.7 and 
Google Ads Api v201806

So what I am trying to achieve:

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 whether account is MCC or not
$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();

3. If account is not mcc, just proceed and get the reports (this works), if 
account is MCC get a select field with all managable accounts to choose the 
account to get the reports from
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();
      $_SESSION['adsSession'] = $session;
      return view('login.selectcid', compact('customers')) ;
    }
4. Let the MCC select which account to get the reports from and send it via 
post to the controller
Here I also pass the GET query string to the next view, so the code and 
state is still set
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');



5. Get the report for the customerId from the request in the next view
I get all my required data via an ajax call to a function somewhat 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'];
    $_SESSION['campaignsPerformaceData'] = $finalreports;
    return $finalreports;

But in return I get the following error message:
"Client error: `POST https://oauth2.googleapis.com/token` resulted in a 
`401 Unauthorized` response: { "error": "unauthorized_client", "
error_description": "Unauthorized" } "

I have to mention, that all this works with a non MCC account. I think 
because I don't mess arround with the customerIds. 

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

Thanks to all 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/05ba7832-3e9e-447a-81e2-afabb0730715%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
  • Getting access to R... targaryen . alexander

Reply via email to