Posts tagged with google-ads-api

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) 

I have followed the syntax from this doc

withCondition("ColumnName IN [Value1, Value2]") 

But I get an error when running this piece of code:

  var adGroups = AdsApp     .adGroups()     .withCondition(agName)     .withCondition(campName)     .get(); 

Error:

5/25/2021 9:32:53 PM    CampaignName CONTAINS_ALL ['test', 'play'] 5/25/2021 9:32:54 PM    Invalid or inapplicable operator is used for field CampaignName. Please check the supported operators. (file Code.gs, line 52) 

I tried to clone the Google Ads GitHub library (adwords-axis-jars-and-examples) but when I try to run the GetCampaigns.java file I get this error: build output in IntelliJ

So I tried to change the compiler settings that people have recommended, still no luck. Compiler settings

I downloaded the adwords-axis-jars-and-examples, but do I need to download the adwords-axis-maven-and-examples for this GitHub library?

If you can help me with this I will Venmo or Cash App you $. I'm just learning how to program so forgive me in advance.

I'm using the latest (v7) Google Ads API to upload offline conversions for Google Ads, using the Python Client Library. This is the standard code I'm using:

import os from google.ads.googleads.client import GoogleAdsClient client = GoogleAdsClient.load_from_env(version='v7') def process_adwords_conversion(     conversion_date_time,      gclid,      conversion_action_id,      conversion_value ):     conversion_date_time = convert_datetime(conversion_date_time)     customer_id = os.environ['GOOGLE_ADS_LOGIN_CUSTOMER_ID']     click_conversion = client.get_type("ClickConversion")     conversion_action_service = client.get_service("ConversionActionService")     click_conversion.conversion_action = (         conversion_action_service.conversion_action_path(             customer_id, conversion_action_id         )     )     click_conversion.gclid = gclid     click_conversion.conversion_value = float(conversion_value)     click_conversion.conversion_date_time = conversion_date_time     click_conversion.currency_code = "USD"     conversion_upload_service = client.get_service("ConversionUploadService")     request = client.get_type("UploadClickConversionsRequest")     request.customer_id = customer_id     request.conversions = [click_conversion]     request.partial_failure = True     conversion_upload_response = (         conversion_upload_service.upload_click_conversions(             request=request,         )     )     uploaded_click_conversion = conversion_upload_response.results[0]     print(conversion_upload_response)     print(         f"Uploaded conversion that occurred at "         f'"{uploaded_click_conversion.conversion_date_time}" from '         f'Google Click ID "{uploaded_click_conversion.gclid}" '         f'to "{uploaded_click_conversion.conversion_action}"'     )     return False 

I believe the code is fine, but I'm having problems locating the conversion_action_id value to use. In the Google Ads UI there's a screen listing the different Conversion Actions, with no sign of an ID anywhere. You can click on the name and get more details, but still no ID:

The conversion action detail screen in Google Ads UI

I've tried the following:

  1. Using the ocid, ctId, euid, __u, uscid, __c, subid URL parameters from this detail page as the conversion_action_id. That always gives an error:
partial_failure_error {   code: 3   message: "This customer does not have an import conversion action that matches the conversion action provided., at conversions[0].conversion_action"   details {     type_url: "type.googleapis.com/google.ads.googleads.v7.errors.GoogleAdsFailure"     value: "\n\305\001\n\003\370\006\t\022dThis customer does not have an import conversion action that matches the conversion action provided.\0320*.customers/9603123598/conversionActions/6095821\"&\022\017\n\013conversions\030\000\022\023\n\021conversion_action"   } } 
  1. Using the standard Google answer:

https://support.google.com/google-ads/thread/1449693/where-can-we-find-google-ads-conversion-ids?hl=en

Google suggests creating a new Conversion Action and obtaining the ID in the process. Unfortunately their instructions don't correspond to the current UI version, at least for me. The sequence I follow is:

  • Click the + icon on the Conversion Actions page
  • Select "Import" as the kind of conversion I want
  • Select "Other data sources or CRMs" then "Track conversions from clicks"
  • Click "Create and Continue"

I then get the screen:

Screen following Conversion Action creation

The recommended answer says:

The conversion action is now created and you are ready to set up the tag to add it to your website. You have three options and the recommended answer in this thread is discussing the Google Tag Manager option, which is the only option that uses the Conversion ID and Conversion Label. If you do not click on the Google Tag Manager option you will not be presented with the Conversion ID and Conversion Label.

Not so! What three options? The first "Learn more" link mentions the Google Tag Manager, but in the context of collecting the GCLID, which I already have. The "three options" mentioned in the official answer have gone. Clicking "done" simply takes me back to the Conversion Actions listing.

  1. Using the REST API

I've tried authenticating and interrogating the endpoint:

https://googleads.googleapis.com/v7/customers/9603123598/conversionActions/

hoping that would give a list of conversion actions, but it doesn't. It just gives a 404.

Does anybody know a way of getting the Conversion Action ID, either from the UI or programmatically (via client library, REST or some other method)?

Thanks!

Currently we are moving from google-ads-node package to google-ads-api.

The main problem that we can not retrieve detailed information about customers ads account.

The method Client.listAccessibleCustomers work just fine but it retrieve only following data

[ `customers/${customerID}`, `customers/${customerID}`, ... ] 

But we need all the data from the customer ads account

There is a file in package ServiceFactory which extends each exported class (place in a raw mode because it's huge)

There is a getter public get customers which retrieve some methods to get them, but there is also warning that you shouldn't use it in production, so how I should retrieve this info?

Even if I try to use it I've get the following error

    {        "errors": [            {              "error_code": {                "authorization_error": 24              },              "message": "The customer can't be used because it isn't enabled."          }        ]     } 

On google-ads-node there aren't any errors and we get the result, but they advice to move to google-ads-api