Posts tagged with google-ads-script

I'm trying to find all my accounts with cost == 0.

 var query =    'SELECT AccountDescriptiveName, Cost FROM ACCOUNT_PERFORMANCE_REPORT DURING LAST_7_DAYS WHERE Cost > 0';  var recommendationResult = AdsApp.search(query, { apiVersion: 'v8' }); 

But I get this exception:

Exception: Could not identify resource for search query "SELECT AccountDescriptiveName, Cost FROM ACCOUNT_PERFORMANCE_REPORT DURING LAST_7_DAYS WHERE Metric.Cost == 0". Double-check your FROM clause. (file Code.gs, line 18)

I wanted to build it from scratch using the Query Builder but I haven't found ACCOUNT_PERFORMANCE_REPORT report (AW API) or it GA API equivalent.

Also, using the GAds connector to data studio. Is there a way to fetch the query behind some table?

I am trying to get data for the conversion and the assigned final url using Google Ads API & GAQL. From what I saw, it is possible to click such a report using graphical tools, but in the API I do not see any way of combining this type of data into one report.

From the campaign level, it is not possible to simply add the final url field. https://developers.google.com/google-ads/api/fields/v7/campaign_query_builder

So my question is: \how can I get conversion data + final url from Google Ads using GAQL or AdsApp?

My current code, or rather query, looks like this:

... var report_conversion = AdsApp.report(   "SELECT campaign.name, " +   "segments.conversion_action_name, " +   "metrics.conversions, metrics.conversions_value" +    "FROM campaign WHERE segments.date > '2021-01-01' AND segments.date < '2021-01-31'" ); report_conversion.exportToSheet(sheet) 

On my website i generate leads via iframe forms. Based on the 'thank you page' i add an value to the url string like:

https//www.website.nl/thank-you?ids=5

the ids value of 5 is the value from the lead conversion (let's say $5,-)

with this script i push the value to Google Ads.

    <?php if ( is_page(123) ) { if (isset($_GET["ids"]) && (is_numeric($_GET["ids"])) ) {         $value = (float)str_replace(",",".",$_GET["ids"]);       $value = sprintf("%01.2f", $value); }else{          $value = sprintf("%01.2f", 0);  } echo '<script>  gtag("event", "conversion", {    "send_to": "AW-*****",        "value": '. $value .',     "currency": "EUR"  }); </script>';  }?> 

The above code worked great until my partner added automaticly a lead ID on the end of the url. now the thank-you url is e.g. https//www.website.nl/thank-you?ids=5&id=12345

Now my script won't work anymore... how to fix? any ideas? probably i can't add my ids to the end of the url, because i need to fill in the thank-you url in the iframe static.

hope anyone can help me out to measure conversion values again and send them over to Google Ads :)

I want to modify these API calls to use a GCP service account instead of my identity.

var report = AdsApp.search(searchQuery);    var table = BigQuery.Tables.insert(table, projectId, dataSetId); BigQuery.Jobs.insert(job, BIGQUERY_PROJECT_ID); 

I read this article but wasn't sure how to find the url for AdsApp and BigQuery.

I searched this post, but still haven't been sure.

Hi,

I want to write an Ads-script to call GoogleAds url nad BQ url using a service account.

I saw this code. Are my urls to the GAds and BQ api correct?

Thanks!

=====================

  // Natural Language API Sentiment URL   var url =       'https://language.googleapis.com/v1beta1/documents:analyzeEntities';   var options = {     method: 'POST',     contentType: 'application/json',     payload: JSON.stringify(body)   };   var response = authUrlFetchApp.fetch(url, options);   var result = JSON.parse(response.getContentText());   Logger.log(result);   if (result.entities) {     // return a list of identified entities     return result.entities;   }   throw Error('No entities response returned'); } 

It's been more than a week and I haven't been to figure out where I'm going wrong.
I'm trying to use a keyword planner and getting a continuous Authentication error. I have my test manager account and have created a google test ads account from that. I have also my client_id, client_secret, and refresh_token from console.developer.google.com
I'm using a developer token from the production account which is not verified.
Thanks in advance.
Here is the error Message:

 Your default encoding, cp1252, is not UTF-8. Please run this script with UTF-8 encoding to avoid errors. Error summary: {'faultMessage': "[QuotaCheckError.INVALID_TOKEN_HEADER @ ; trigger:'New developers must use the Google Ads API.']", 'requestId': 'foobar', 'serviceName': 'TrafficEstimatorService', 'methodName': 'get', 'operations': '1', 'responseTime': '83'} Traceback (most recent call last):   File "env\lib\site-packages\googleads\common.py", line 984, in MakeSoapRequest      return soap_service_method(   File "env\lib\site-packages\zeep\proxy.py", line 46, in __call__     return self._proxy._binding.send(   File "env\lib\site-packages\zeep\wsdl\bindings\soap.py", line 135, in send          return self.process_reply(client, operation_obj, response)  File "env\lib\site-packages\zeep\wsdl\bindings\soap.py", line 229, in process_reply     return self.process_error(doc, operation)   File "env\lib\site-packages\zeep\wsdl\bindings\soap.py", line 329, in process_error     raise Fault( zeep.exceptions.Fault: [QuotaCheckError.INVALID_TOKEN_HEADER @ ; trigger:'New developers must use the Google Ads API.']      During handling of the above exception, another exception occurred: Traceback (most recent call last):   File "test.py", line 181, in <module>     main(adwords_client)   File "test.py", line 97, in main     estimates = traffic_estimator_service.get(selector)          File "env\lib\site-packages\googleads\common.py", line 996, in MakeSoapRequest      raise googleads.errors.GoogleAdsServerFault( googleads.errors.GoogleAdsServerFault: [QuotaCheckError.INVALID_TOKEN_HEADER @ ; trigger:'New developers must use the Google Ads API.'] 

Here is my google ads file:

adwords: # AdWordsClient configurations   developer_token: mydevtoken1234   client_customer_id: 123-123-123   validate_only: False   client_id: myclientId.apps.googleusercontent.com   client_secret: myclientsecret   refresh_token: myrefreshtoken # AdManagerClient configurations ad_manager:   developer_token: EZ-x_JXs6mtX6tDO_8VauA   application_name: get-keyword-ideas   # path_to_private_key_file: INSERT_PATH_TO_JSON_KEY_FILE_HERE   client_id: myclientId.apps.googleusercontent.com   client_secret: myclientsecret   refresh_token: myrefreshtoken 

And Here is my Python code for trafficEstimator

#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # #      http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This example retrieves keyword traffic estimates. The LoadFromStorage method is pulling credentials and properties from a "googleads.yaml" file. By default, it looks for this file in your home directory. For more information, see the "Caching authentication information" section of our README. """ from googleads import adwords def main(client):   # Initialize appropriate service.   traffic_estimator_service = client.GetService(       'TrafficEstimatorService', version='v201809')   # Construct selector object and retrieve traffic estimates.   keywords = [       {'text': 'mars cruise', 'matchType': 'BROAD'},       {'text': 'cheap cruise', 'matchType': 'PHRASE'},       {'text': 'cruise', 'matchType': 'EXACT'}   ]   negative_keywords = [       {'text': 'moon walk', 'matchType': 'BROAD'}   ]   keyword_estimate_requests = []   for keyword in keywords:     keyword_estimate_requests.append({         'keyword': {             'xsi_type': 'Keyword',             'matchType': keyword['matchType'],             'text': keyword['text']         }     })   for keyword in negative_keywords:     keyword_estimate_requests.append({         'keyword': {             'xsi_type': 'Keyword',             'matchType': keyword['matchType'],             'text': keyword['text']         },         'isNegative': 'true'     })   # Create ad group estimate requests.   adgroup_estimate_requests = [{       'keywordEstimateRequests': keyword_estimate_requests,       'maxCpc': {           'xsi_type': 'Money',           'microAmount': '1000000'       }   }]   # Create campaign estimate requests.   campaign_estimate_requests = [{       'adGroupEstimateRequests': adgroup_estimate_requests,       'criteria': [           {               'xsi_type': 'Location',               'id': '2840'  # United States.           },           {               'xsi_type': 'Language',               'id': '1000'  # English.           }       ],   }]   # Create the selector.   selector = {       'campaignEstimateRequests': campaign_estimate_requests,   }   # Optional: Request a list of campaign-level estimates segmented by   # platform.   selector['platformEstimateRequested'] = True   # Get traffic estimates.   estimates = traffic_estimator_service.get(selector)   campaign_estimate = estimates['campaignEstimates'][0]   # Display the campaign level estimates segmented by platform.   if 'platformEstimates' in campaign_estimate:     platform_template = ('Results for the platform with ID: "%d" and name: '                          '"%s".')     for platform_estimate in campaign_estimate['platformEstimates']:       platform = platform_estimate['platform']       DisplayEstimate(platform_template % (platform['id'],                                            platform['platformName']),                       platform_estimate['minEstimate'],                       platform_estimate['maxEstimate'])   # Display the keyword estimates.   if 'adGroupEstimates' in campaign_estimate:     ad_group_estimate = campaign_estimate['adGroupEstimates'][0]     if 'keywordEstimates' in ad_group_estimate:       keyword_estimates = ad_group_estimate['keywordEstimates']       keyword_template = ('Results for the keyword with text "%s" and match '                           'type "%s":')       keyword_estimates_and_requests = zip(keyword_estimates,                                            keyword_estimate_requests)       for keyword_tuple in keyword_estimates_and_requests:         if keyword_tuple[1].get('isNegative', False):           continue         keyword = keyword_tuple[1]['keyword']         keyword_estimate = keyword_tuple[0]         DisplayEstimate(keyword_template % (keyword['text'],                                             keyword['matchType']),                         keyword_estimate['min'], keyword_estimate['max']) def _CalculateMean(min_est, max_est):   if min_est and max_est:     return (float(min_est) + float(max_est)) / 2.0   else:     return None def _FormatMean(mean):   if mean:     return '%.2f' % mean   else:     return 'N/A' def DisplayEstimate(message, min_estimate, max_estimate):   """Displays mean average cpc, position, clicks, and total cost for estimate.   Args:     message: str message to display for the given estimate.     min_estimate: zeep.objects.StatsEstimate containing a minimum estimate from the       TrafficEstimatorService response.     max_estimate: zeep.objects.StatsEstimate containing a maximum estimate from the       TrafficEstimatorService response.   """   # Find the mean of the min and max values.   mean_avg_cpc = (_CalculateMean(min_estimate['averageCpc']['microAmount'],                                  max_estimate['averageCpc']['microAmount'])                   if 'averageCpc' in min_estimate                   and min_estimate['averageCpc'] else None)   mean_avg_pos = (_CalculateMean(min_estimate['averagePosition'],                                  max_estimate['averagePosition'])                   if 'averagePosition' in min_estimate                   and min_estimate['averagePosition'] else None)   mean_clicks = _CalculateMean(min_estimate['clicksPerDay'],                                max_estimate['clicksPerDay'])   mean_total_cost = _CalculateMean(min_estimate['totalCost']['microAmount'],                                    max_estimate['totalCost']['microAmount'])   print(message)   print('  Estimated average CPC: %s' % _FormatMean(mean_avg_cpc))   print('  Estimated ad position: %s' % _FormatMean(mean_avg_pos))   print('  Estimated daily clicks: %s' % _FormatMean(mean_clicks))   print('  Estimated daily cost: %s' % _FormatMean(mean_total_cost)) if __name__ == '__main__':   # Initialize client object.   adwords_client = adwords.AdWordsClient.LoadFromStorage('googleads.yaml')   main(adwords_client)