Posts under category google-ads-api

I'm simply trying to construct a test script that can change/mutate a specific campaign budget using the REST interface of the Google Ads API on Google Apps Scripts but I keep on running into the following error:

Exception: Request failed for https://googleads.googleapis.com returned code 400. Truncated server response: { "error": { "code": 400, "message": "Invalid JSON payload received. Unexpected token.\nvalidateOnly=true&pa\n^", "status": "INVALID_... (use muteHttpExceptions option to examine full response)

The relevant function code is as follows:

//API specific variables const developer_token = {DEVELOPER TOKEN}; const parent_mcc_id = "xxxxxxxxxx"; //Temporary placeholder values var child_customer_id = "xxxxxxxxxx"; var budget_id = "xxxxxxxxxx";   let headers = {      Authorization: "Bearer " + ScriptApp.getOAuthToken(),      "developer-token": developer_token,      "login-customer-id": parent_mcc_id   };   //Make API call to retrieve each Google Ads account   try{     let requestParams = {      method: "POST",      contentType: "application/json",      headers: headers,      payload: {        operations:        [         {           updateMask: "amount_micros",           update:{             resourceName: "customers/" + child_customer_id + "/campaignBudgets/" + budget_id,             amountMicros: "60000000"           }         }        ],       "partialFailure": true,       "validateOnly": true,       "responseContentType": "RESOURCE_NAME_ONLY"       }     }          var url = ("https://googleads.googleapis.com/v11/customers/{CHILD ACCOUNT ID}/campaignBudgets:mutate");     Logger.log(requestParams.payload);     var postChange = UrlFetchApp.fetch(url, requestParams);   }   catch(e) {    Logger.log(e);   } 

I have used similar functions with queries in the payload portion to get data through the Google Ads API, place the data in an array and dump it into a spreadsheet, so I know that my developer token, mcc ids, and child account ids are correct. Any help would be greatly appreciated!

I have the following "standard" google site tag tracking conversions on my page:

<!-- Google Code for sale Conversion Page --> <script type="text/javascript"> /* <![CDATA[ */ var google_conversion_id = AW-MYAWID; var google_conversion_language = "en"; var google_conversion_format = "3"; var google_conversion_color = "ffffff"; var google_conversion_label = "MY_LABEL"; if (1.0) {   var google_conversion_value = <?php echo round($order_total['value'],2);?>; } var google_remarketing_only = false; /* ]]> */ </script> script type="text/javascript" src="//www.googleadservices.com/pagead/conversion.js"> </script> <noscript> <div style="display:inline;"> <img height="1" width="1" style="border-style:none;" alt="" src="//www.googleadservices.com/pagead/conversion/AW-MYAWID/?value=<?php echo round($order_total['value'],2);?>&amp;label=MY_LABEL&amp;guid=ON&amp;script=0"/> </div> </noscript> 

Directly below that I have:

  <script type="text/javascript">         gtag('event', 'conversion', {             'send_to': 'AW-MYAWID/MYLABEL',             'value': <?php echo round($order_total['value'],2);?>,             'currency': 'CAD',             'transaction_id': ''         });     </script>     <!--google enhanced conversions !-->     <script type="text/javascript">         gtag('set', 'user_data', {             "email":  <?php echo $customer_info['email_address'];?>,             "phone_number": <?php echo $customer_info['telephone'];?>,             "address": {             "first_name": <?php echo $customer_info['firstname']; ?>,                 "last_name": <?php echo $customer_info['lastname']; ?>,                 "street":  <?php echo $customer_info['street_address'];?>,                 "city":<?php echo $customer_info['city'];?>,                 "region": <?php echo $customer_info['state'];?>,                 "postal_code": <?php echo $customer_info['postcode'];?>         }         });     </script> 

This is in my header:

<script async src="https://www.googletagmanager.com/gtag/js?id=UA-MYUAUD"></script> <script>     window.dataLayer = window.dataLayer || [];     function gtag(){dataLayer.push(arguments);}     gtag('js', new Date());     gtag('config', 'AW-MYAWID') ;     gtag('config', 'UA-MYUAUD'); </script> 

in tag assistant the CDATA tag is showing but for the global site tag it shows the tag with no metadata etc. am I missing something? Why is only the standard version seem to fire the event?

How to properly report conversions back to google ads when they happen on server side?

I guess my usecase is pretty common but I can't seem to find any relevant information:

  • user clicks an ad on google
  • they are redirected to my website
  • they signup for a free trial
  • I report the "sign up" event back to google analytics (GA4) using gtag
  • the sign up event is linked to google ads as an "offline" event

This works good so far.

Now when trial ends and the user is charged for the first time, I want to further report a "renewal" event with the "value" charged so google ads could further optimise. But how do I do this?

Renewal happens on the server, while I also track the renewal using GA4 api, I'm not sure how to link it to the original user so it can be attributed correctly in GA4 and then in google ads.

Seems like I need to get cookies that google ads create in browser to identify a user when the user first signs up, and then send the cookies to the server and to further pass them to GA4 every time the renewal happens. But I can't see any documentation on that neither.

So how do I report server side events back to GA4/google ads ensuring the even is attributed to the correct user?

As a note, I'm not looking to use Google Tag Manager.

I'm trying to get campaign information with Google ADS API. The sample code snippet I used is from the official googleads github repo.

import argparse import sys from google.ads.googleads.client import GoogleAdsClient from google.ads.googleads.errors import GoogleAdsException _DEFAULT_PAGE_SIZE = 1000 # [START get_campaigns_by_label] def main(client, customer_id, label_id, page_size):     """Demonstrates how to retrieve all campaigns by a given label ID.     Args:         client: An initialized GoogleAdsClient instance.         customer_id: A client customer ID str.         label_id: A label ID to use when searching for campaigns.         page_size: An int of the number of results to include in each page of             results.     """     ga_service = client.get_service("GoogleAdsService")     # Creates a query that will retrieve all campaign labels with the     # specified label ID.     query = f"""         SELECT             campaign.id,             campaign.name,             label.id,             label.name          FROM campaign_label          WHERE label.id = "{label_id}"          ORDER BY campaign.id"""     # Retrieves a google.api_core.page_iterator.GRPCIterator instance     # initialized with the specified request parameters.     request = client.get_type("SearchGoogleAdsRequest")     request.customer_id = customer_id     request.query = query     request.page_size = page_size     iterator = ga_service.search(request=request)     # Iterates over all rows in all pages and prints the requested field     # values for the campaigns and labels in each row. The results include     # the campaign and label objects because these were included in the     # search criteria.     for row in iterator:         print(             f'Campaign found with ID "{row.campaign.id}", name '             f'"{row.campaign.name}", and label "{row.label.name}".'         ) if __name__ == "__main__":     # GoogleAdsClient will read the google-ads.yaml configuration file in the     # home directory if none is specified.     googleads_client = GoogleAdsClient.load_from_storage(version="v10")     parser = argparse.ArgumentParser(         description="Lists all campaigns for specified customer."     )     # The following argument(s) should be provided to run the example.     parser.add_argument(         "-c",         "--customer_id",         type=str,         required=True,         help="The Google Ads customer ID.",     )     parser.add_argument(         "-l",         "--label_id",         type=str,         required=True,         help="A label ID associated with a campaign.",     )     args = parser.parse_args()     try:         main(             googleads_client,             args.customer_id,             args.label_id,             _DEFAULT_PAGE_SIZE,         )     except GoogleAdsException as ex:         print(             f'Request with ID "{ex.request_id}" failed with status '             f'"{ex.error.code().name}" and includes the following errors:'         )         for error in ex.failure.errors:             print(f'\tError with message "{error.message}".')             if error.location:                 for field_path_element in error.location.field_path_elements:                     print(f"\t\tOn field: {field_path_element.field_name}")         sys.exit(1) 

When I run the above .py file, I get the following error.

ValueError: Specified Google Ads API version "v10" does not exist. Valid API versions are: "v8", "v7", "v6" 

But when I change the version on "GoogleAdsClient.load_from_storage(version="v10")" to v8, this time I get the following error.

Request made: ClientCustomerId: XXXXXXX, Host: googleads.googleapis.com, Method: /google.ads.googleads.v8.services.GoogleAdsService/Search, RequestId: XXXXXXXXX,IsFault: True, FaultMessage:  Version v8 is deprecated. Requests to this version will be blocked. 

By the way, I'm sure the google-ads package is up to date. Previously, I ran the following.

pip uninstall google-ads pip install google-ads 

Thanks in advance for your help.