Posts tagged with google-oauth

I'm attempting to use the Google Ads API Client Library for PHP with a Service Account json.

Inviting the Service Account to Google Ads account has status of "Awaiting response" - but I cannot login to the Service Account to accept the invite.

Here is the code being used:

<?php // Include the Google Ads API PHP client library require_once 'googleads_google-ads-php/vendor/autoload.php'; use Google\Ads\GoogleAds\Lib\V13\GoogleAdsClientBuilder; use Google\Ads\GoogleAds\Lib\V13\GoogleAdsServerStreamDecorator; use Google\Ads\GoogleAds\Util\V13\ResourceNames; use Google\Ads\GoogleAds\V13\Services\GoogleAdsQuery; use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder; $developerToken = "developerToken"; $jsonKeyFilePath = "json_key.json"; $customerId = "CustomerId"; // Set up authentication using a service account JSON file $googleAdsClient = (new GoogleAdsClientBuilder())     ->withDeveloperToken($developerToken) ->withOAuth2Credential((new OAuth2TokenBuilder())     ->withJsonKeyFilePath($jsonKeyFilePath)     ->withScopes(['https://www.googleapis.com/auth/adwords'])     ->build())     ->build(); // Define the query to retrieve data from the age_range_view $query = "SELECT segments.date, segments.device, metrics.clicks, ad_group_criterion.criterion_id, ad_group_criterion.display_name           FROM age_range_view           LIMIT 1000"; try {     // Execute the query and get the results     $response = $googleAdsClient->getGoogleAdsServiceClient()->search($customerId, $query);     // Loop through the rows of data and extract the desired values     foreach ($response->iterateAllElements() as $googleAdsRow) {         $date = $googleAdsRow->getSegments()->getDate()->getValue();         $device = $googleAdsRow->getSegments()->getDevice()->getValue();         $clicks = $googleAdsRow->getMetrics()->getClicks()->getValue();         $criterionId = $googleAdsRow->getAdGroupCriterion()->getCriterionId()->getValue();         $displayName = $googleAdsRow->getAdGroupCriterion()->getDisplayName()->getValue();                  // Print the extracted values to the console         printf("Date: %s | Device: %s | Clicks: %d | Criterion ID: %d | Display Name: %s\n",             $date,             $device,             $clicks,             $criterionId,             $displayName         );     } } 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         );     } } catch (ApiException $apiException) {     printf("ApiException was thrown with message '%s'.%s",         $apiException->getMessage(),         PHP_EOL     ); } ?> 

Here is the error message:

PHP Fatal error:  Uncaught Google\ApiCore\ApiException: {     "message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https:\/\/developers.google.com\/identity\/sign-in\/web\/devconsole-project.",     "code": 16,     "status": "UNAUTHENTICATED",     "details": [         {             "@type": "type.googleapis.com\/google.ads.googleads.v13.errors.GoogleAdsFailure",             "errors": [                 {                     "errorCode": {                         "authenticationError": "NOT_ADS_USER"                     },                     "message": "User in the cookie is not a valid Ads user."                 }             ],             "requestId": "requestId"         }     ] }   thrown in /data_import/googleads_google-ads-php/vendor/google/gax/src/ApiException.php on line 267 

I attempted to try adding ->withImpersonatedEmail($impersonatedEmail) to the authentication request with an account on the same project that has access to the Google Ads accounts but that did not work.

What am I missing?

While authorizing my Google Ads Account using OAuth Playground to retrieve a lifetime refresh token which could used to further create access tokens, the authorization is throwing This app is blocked security error. I think this is because the GCP OAuth consent screen is not verified. But how do I verify my OAuth consent screen when I don't have an App domain name, since I'm using this as a one time activity to retrieve my refresh token using OAuth Playground?

I am working on a project to let a client authorize their google ads account, and then use those authorized credentials to download data on their behalf. I have a webapp that successfully Authorizes the app to do things on the clients behalf. This generates an access code that I then trade for two credentials, an access token and a refresh token. This refresh token then gets passed to a database, where a separate app attempts to query the googleAds API. It is my understanding that the Google Oauth engine only needs the refresh token.

I am trying to authorize by use of load_from_dict() or load_from_env() methods of the GoogleAdsClient class. Both yield the same error: google.auth.exceptions.RefreshError: ('invalid_client: Unauthorized', {'error': 'invalid_client', 'error_description': 'Unauthorized'})

I have verified the developer_token, client_id, and client_secret are all accurate to what is in the API console. I have also verified the refresh_token is being passed correctly to the credential dict.

I am really at a loss on where to go from here. I have read many stack overflow threads with similar titles, and yet I am still stuck at the same place.

Here are some relevant links.

Google Ads API configuration

Google Identity and Server side web apps

Google's example of an API call

Relevant code

class GoogleAds: def __init__(self):     self.scope = ['https://www.googleapis.com/auth/adwords']     self.client_id = os.getenv('GOOGLE_ADS_CLIENT_ID')     self.client_secret = os.getenv('GOOGLE_ADS_CLIENT_SECRET')     self.developer_token = os.getenv('GOOGLE_ADS_DEVELOPER_TOKEN')     self.refresh_token = os.getenv('GOOGLE_ADS_REFRESH_TOKEN') def authorize(self):     credentials = {         "developer_token": self.developer_token,         "refresh_token": self.refresh_token,         "client_id": self.client_id,         "client_secret": self.client_secret,         "use_proto_plus":"True",         "grant_type": "refresh_token",     }     print(credentials)     googleads_client = GoogleAdsClient.load_from_dict(credentials)     service = googleads_client.get_service("GoogleAdsService")     request = googleads_client.get_type("SearchGoogleAdsRequest")     return service, request 

  1. Does anybody know after how much time or how many requests does refresh token expires in Google ads API? I created refresh token here https://developers.google.com/oauthplayground.
  2. Does anyone know what is the impersonated email in server account in Google ads API? I created server account in Google cloud project. If I run python code with Service Account configuration with generated json_key_file_path and same impersonated_email as my email account with which I created project then I get an error google.auth.exceptions.RefreshError: ('unauthorized_client: Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested.', {'error': 'unauthorized_client', 'error_description': 'Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested.'}). If I put for impersonated_email client_email that I got from generated jon file I get an error: User in the cookie is not a valid Ads user.

With the "Google Ads API" - PHP Client Library.

While calling the "GetCampaigns.php" / "ListAccessibleCustomers.php" example code. I was still getting this error (below) but found a solution (check answer).

Error -

authorization_error: User doesn't have permission to access customer.  Note: If you're accessing a client customer,  the manager's customer id must be set in the 'login-customer-id' header.  See https://developers.google.com/google-ads/api/docs/concepts/call-structure#cid