Posts tagged with google-api-php-client

As per my question, I want to filter the campaign's metrics based on the date range filter read the below code:

 /**  * Runs the example.  *  * @param GoogleAdsClient $googleAdsClient the Google Ads API client  * @param int $customerId the customer ID  */ public static function getGoogleAdCampaigns(GoogleAdsClient $googleAdsClient, int $customerId){     $googleAdsServiceClient = $googleAdsClient->getGoogleAdsServiceClient();     // Creates a query that retrieves all campaigns.     $query = "SELECT campaign.id, campaign.name,campaign.status, metrics.impressions, metrics.clicks, metrics.conversions, metrics.ctr, metrics.average_cpc, metrics.cost_micros, campaign.start_date, campaign.end_date FROM campaign WHERE campaign.status = 'ENABLED'";     // Issues a search stream request.     /** @var GoogleAdsServerStreamDecorator $stream */     $stream = $googleAdsServiceClient->searchStream(         SearchGoogleAdsStreamRequest::build($customerId, $query)     );     // Iterates over all rows in all messages and prints the requested field values for     // the campaign in each row.     // Initialize an array to hold campaign data    $campaigns = [];    // Iterates over all rows in all messages and collects the requested field values for    // the campaign in each row.    foreach ($stream->iterateAllElements() as $googleAdsRow) {        /** @var GoogleAdsRow $googleAdsRow */        $campaigns[] = [            'id' => $googleAdsRow->getCampaign()->getId(),            'name' => $googleAdsRow->getCampaign()->getName(),            'start_date' => $googleAdsRow->getCampaign()->getStartDate(),            'end_date' => $googleAdsRow->getCampaign()->getEndDate(),            'status' => $googleAdsRow->getCampaign()->getStatus(),            'impressions' => $googleAdsRow->getMetrics()->getImpressions(),            'clicks' => $googleAdsRow->getMetrics()->getClicks(),            'conversions' => $googleAdsRow->getMetrics()->getConversions(),            'ctr' => $googleAdsRow->getMetrics()->getCtr(),            'average_cpc' => $googleAdsRow->getMetrics()->getAverageCpc(),            'cost_micros' => $googleAdsRow->getMetrics()->getCostMicros(),        ];    }    // print_r($stream->iterateAllElements());    // Return the collected campaign data array     echo json_encode($campaigns);     exit(); } 

Suppose I want to get last week's clicks, impressions last week's cost, etc.

Reference : https://groups.google.com/g/adwords-api/c/H-6qp8v-k-o?pli=1

I've set up an OAuth2 web project as well as a Service Account. Both IDs have been added with domain-wide delegation with the adwords scope in my Google Workspace.

I have a Google Ads Manager account with a Developer Key (it's in test mode, if that matters?). The email I'm trying to authenticate with for either method is an Admin in the domain and on the relevant Ads Manager and Ads accounts.

No matter what I do, I get the following error.

{     "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.v16.errors.GoogleAdsFailure",             "errors": [                 {                     "errorCode": {                         "authenticationError": "OAUTH_TOKEN_HEADER_INVALID"                     },                     "message": "Oauth token HTTP header is malformed."                 }             ],             "requestId": "9QCN5RO9mRkmS1ULtDAKMA"         }     ] } 

If I try to use the service account email as the impersonateEmail parameter, I get a NOT_ADS_USER. I've invited it to the Ads Manager account, but am not sure how to accept that invite. I think it would result in the same OAUTH_TOKEN_HEADER_INVALID, anyways.

This is within a Laravel project.

$oauth2 = (new OAuth2TokenBuilder())                 ->withClientId(config('google.client_id'))                 ->withClientSecret(config('google.client_secret'))                 ->withRefreshToken(config('googleads.refresh_token'))                 ->build(); 
$oauth2 = (new OAuth2TokenBuilder())                 ->withJsonKeyFilePath(realpath(config('google.service.file')))                 ->withScopes('https://www.googleapis.com/auth/adwords')                 ->withImpersonatedEmail(config('googleads.impersonated_email'))                 ->build(); 

What's strange is that, using either OAuth2Token instance, I can run fetchAuthToken(), and I see that the object gets its access_token. I can also see in Google\ApiCore\CredentialsWrapper::getAuthorizationHeaderCallback that it is added as the authorization Bearer token.

Here's how my GoogleAdsClient is built:

$this->client = (new GoogleAdsClientBuilder())                 ->withOAuth2Credential($oauth2)                 ->withDeveloperToken(config('google.developer_key'))                 ->usingGapicV2Source(true)                 ->build(); 

And here's the request that fails with the OAUTH_TOKEN_HEADER_INVALID:

$requestArgs = [             // Set the language resource using the provided language ID.             'language' => $this->getLanguageConstant(),             'customer_id' => $this->getCustomerId(),             // Add the resource name of each location ID to the request. - currently an empty array             'geo_target_constants' => $this->getGeoTargetConstants(),             // Set the network. To restrict to only Google Search, change the parameter below to             'keyword_plan_network' => KeywordPlanNetwork::GOOGLE_SEARCH,         ] + $requestOptionalArgs;         $response = $ideaClient->generateKeywordIdeas(             new GenerateKeywordIdeasRequest($requestArgs)         ); 

I've been going in circles on this for over a day. Thank you in advance!

I've made a script that runs on the Google Ads API. The project on console.cloud.google.com is configured as "External" and "In Testing". The script I'm talking about needs to be run daily on a cron job. Issue is, every week I have to get a new refresh token manually, which is unnecessary in my opinion. So, is there a way to get a new refresh token without needing a user pressing "Continue" and "Accept", i.e. verifying that they allow access to Google Ads? Or does that only happen when I Publish my app on console.cloud.google.com?

So far, I either put the refresh token into the script and it works or (in another script) I use the refresh token to cURL into https://oauth2.googleapis.com/token to get an access token.

I try to make a keyword searches system for our employ and i have google ads developer token But I cannot able to find any CURL or PHP CURL setup guide.

Two reference links Ad API Examples
Method: customers.generateKeywordIdeas

An example from Google's documentation:

curl -f --request POST "https://googleads.googleapis.com/v${API_VERSION}/customers/${CUSTOMER_ID}/campaignBudgets:mutate" \ --header "Content-Type: application/json" \ --header "developer-token: ${DEVELOPER_TOKEN}" \ --header "login-customer-id: ${MANAGER_CUSTOMER_ID}" \ --header "Authorization: Bearer ${OAUTH2_ACCESS_TOKEN}" \ --data "{ 'operations': [   {     'create': {       'name': 'My Campaign Budget #${RANDOM}',       'amountMicros': 500000,     }   },   {     'create': {       'name': 'My Campaign Budget #${RANDOM}',       'amountMicros': 500000,     }   } ] }" 

I try this code but got Error

    <?          $ch = curl_init();          curl_setopt($ch, CURLOPT_URL, 'https://googleads.googleapis.com/v11/customers/(MANAGER_CUSTOMER_ID):generateKeywordIdeas');     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);     curl_setopt($ch, CURLOPT_POST, 1);     curl_setopt($ch, CURLOPT_POSTFIELDS, "{\n\n\"keywordSeed\": {\n    \"keywords\": [\n    \"cofee\"\n  ]\n  }\n}");          $headers = array();     $headers[] = 'Content-Type: application/json';     $headers[] = 'Login-Customer-Id: (MANAGER_CUSTOMER_ID)';     $headers[] = 'Developer-Token: DEVELOPER_TOKEN';     $headers[] = 'Authorization: Bearer (OAUTH_ACCESS_TOKEN)';     curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);          $result = curl_exec($ch);     if (curl_errno($ch)) {         echo 'Error:' . curl_error($ch);     }     print_r($result);     curl_close($ch); 

I'm not getting any output

We have an app with offline access_type token. Yesterday all queries were broken, because authorization failed

POST https://oauth2.googleapis.com/token 

resulted in a

400 Bad Request response: { "error": "invalid_grant", "error_description": "Bad Request" }).

We use SDK Google Ads API Client Library for PHP for any queries to API.

Code example:

// Generate a refreshable OAuth2 credential for authentication.         $oAuth2Credential = (new OAuth2TokenBuilder())->fromFile($filePathName)->build();         $loggerFactory    = new LoggerFactory();         $logger           = $loggerFactory->createLogger('TestChannel',             APPLICATION_DIRECTORY . ".log/google/adsapi.date("Y-m").".log",             'DEBUG');         // Construct a Google Ads client configured from a properties file and the         // OAuth2 credentials above.         $googleAdsClient = (new GoogleAdsClientBuilder())             ->fromFile(std::lpath($filePathName))             ->withOAuth2Credential($oAuth2Credential)             ->withLogger($logger)             ->build();         $query = "SELECT customer_client.status FROM customer_client";         $googleAdsServiceClient = $googleAdsClient->getGoogleAdsServiceClient();         $response               = $googleAdsServiceClient->search(             $customerId,             $query,             ['pageSize' => self::PAGE_SIZE]         );         return $response->getIterator()->current();

App is in production in google cloud console.

What have we already done:

  • changed password for account
  • reset secret and generate new refresh token

Create new app isn't good solution for us, because I think, we couldn't quickly increase limits to API (but in this moment we were forced to use an app with basic limits and quota)

Any idea how to solve this problem or how contact Google oAuth team with this question?

Related to https://groups.google.com/g/adwords-api/c/nvLa0xPkdUs/m/0P3LcxBgAQAJ

Update: I had found, that there is no link to my app in https://myaccount.google.com/permissions Anyone know, how to add this permissions again?