Posts tagged with google-apps-script

I have a question about manage items stock / outstock google ads I've tried to use Google Scripts - but it decision not matched for me, because page code site has often change by developers Google Ads API - is it decisions for my requirement? Someone use it for manage ads - for stop ads if items outstock?

I am working with Google Ads Scripts. Based on my use case, I need to get the impressions, clicks, and other statistics about the products I have in my Google Ads account.

These product statistics will be analyzed in the script and based on certain criteria a Google Sheet document will be updated. The script goes like, retrieving all products (along with their statistics) from Google Ads account, see if the products impression and clicks meet a category (30 Impression, 1 click = Category "A", 20 Impressions, 0 Clicks = "Category B"), determines the product category, open Google Sheet hosted on Google Drive and updates the Category column in the Sheet based on product name or id.

Currently, I am facing an issue with retrieving Products and their statistics from Google Ads Account using Ads Script. I used the following code snippets to look for products but found no method or class that would help me achieve my desired results. I can only retrieve the productGroups, AdGroups, and Campaigns but none of them allow me to extract individual products.

function productGroup(){   var prodGroupIter = AdsApp.productGroups().get();   while (prodGroupIter.hasNext()){     Logger.log("prodGroup: ")     var prodGroup = prodGroupIter.next();     Logger.log(prodGroup.getValue());   } } function adGroup() {   var adGroupIterator = AdsApp.adGroups().get();   while (adGroupIterator.hasNext()) {     var adGroup = adGroupIterator.next();     Logger.log("adGroup: ")     Logger.log(adGroup.getName());   } } function campaign(){   var campIter = AdsApp.campaigns().get();   while (campIter.hasNext()){     var ads = campIter.next().ads().get();     while(ads.hasNext()){       Logger.log(ads.next().getStatsFor("LAST_30_DAYS"));     }   } } function sheet() {   var sheetURL = "https://docs.google.com/spreadsheets/d/1W0zhRrQa1P7qjQf0eXXw-QzdcPKAlDPiVBOcIVEfDgw/edit#gid=1428103052";   var sheet = SpreadsheetApp.openByUrl(sheetURL); } function main(){   campaign();   adGroup();   productGroup(); } 

I then reached out to the Ads Script support team and found out that it is not possible. But they suggested that I can use Shopping Performance Report, Product Partition Report, shopping_performance_view or product_group_view. They are part of AdWord API, and I do not know how to work with them.

So, I am looking for a Google Ads Script that would help me get a list of products (with detailed statistics) from Googe Ads and I am stuck with how to use the above-mentioned AdWord reporting endpoints to do it.

Here is the list of products in my Google Ads Account. They are 107 products along with their statistics.

Please, help with at least comments, ideas, and suggestions, I can write code but I am not sure what I am missing on

I am trying to use Google Ads on Google Apps Script using this guide. I created client id and client secret on Google Console's API & Services.

Not too sure if this configuration is correct but the account is linked to Google Apps Script as I have pagespeed insights as well and there are some requests on the dashboard. I added https://www.googleapis.com/auth/drive as the scope. Again not too sure if I should add Google Ads to the scope. Lastly, got my refresh token from Google Auth playground. When I run the script above I got the following error:

Error: No access token received: {   "error": "invalid_client",   "error_description": "Unauthorized" } authenticate_   @ test.gs:120 withRefreshToken    @ test.gs:144 initializeOAuthClient   @ test.gs:28 

Honestly not too sure what I am doing wrong here so any help would be very much appreciated. Thank you.

Edit Codes:

//From Google Console API & Services var CLIENT_ID = '"MY_CLIENT_ID'; var CLIENT_SECRET = 'MY_CLIENT_SECRET'; //From Google Authplayground var REFRESH_TOKEN = 'REFRESH_TOKEN'; // Enter scopes which should match scopes in File > Project properties // For this project, e.g.: https://www.googleapis.com/auth/drive var SCOPES = "https://www.googleapis.com/auth/adwords"; // Script ID taken from 'File > Project Properties' var SCRIPT_ID = 'MY_SCRIPT_ID'; var authUrlFetch; // Call this function just once, to initialize the OAuth client. function initializeOAuthClient() {   if (typeof OAuth2 === 'undefined') {     var libUrl = 'https://developers.google.com/google-ads/scripts/docs/examples/oauth20-library';     throw Error('OAuth2 library not found. Please take a copy of the OAuth2 ' +         'library from ' + libUrl + ' and append to the bottom of this script.');   }   var tokenUrl = 'https://accounts.google.com/o/oauth2/token';   authUrlFetch = OAuth2.withRefreshToken(tokenUrl, CLIENT_ID, CLIENT_SECRET,     REFRESH_TOKEN, SCOPES); } /**  * Execute a remote function.  * @param {string} remoteFunctionName The name of the function to execute.  * @param {Object[]} functionParams An array of JSON objects to pass to the  *     remote function.  * @return {?Object} The return value from the function.  */ function executeRemoteFunction(remoteFunctionName, functionParams) {   var apiParams = {     'function': remoteFunctionName,     'parameters': functionParams   };   var httpOptions = {     method: 'POST',     headers: {       'Content-Type': 'application/json'     },     payload: JSON.stringify(apiParams)   };   var url = 'https://script.googleapis.com/v1/scripts/' + SCRIPT_ID + ':run';   var response = authUrlFetch.fetch(url, httpOptions);   var data = JSON.parse(response.getContentText());   // Retrieve the value that has been returned from the execution.   if (data.error) {     throw Error('There was an error: ' + response.getContentText());   }   return data.response.result; } // Paste in OAuth2 library here, from: // https://developers.google.com/google-ads/scripts/docs/examples/oauth20-library 

I have pasted the oauth2.0 library under the codes above.

Edit 2
I fixed the part of function initializeOAuthClient. It now shows execution complete, but when I try to run function executeRemoteFunction I am getting TypeError: Cannot read property 'fetch' of undefined. I am guessing I have to input remoteFunctionName and functionParams but where do I find them?

I try to run the following ad-words from my adwords script editor.

My final goal is to be able to run query1 or query2

//conversion_action var query1 = "SELECT conversion_action.app_id, conversion_action.attribution_model_settings.attribution_model, conversion_action.attribution_model_settings.data_driven_model_status, conversion_action.category, conversion_action.click_through_lookback_window_days, conversion_action.counting_type, conversion_action.firebase_settings.event_name, conversion_action.firebase_settings.project_id, conversion_action.id, conversion_action.include_in_conversions_metric,  conversion_action.name, conversion_action.owner_customer,  conversion_action.resource_name, conversion_action.status, conversion_action.tag_snippets, conversion_action.third_party_app_analytics_settings.event_name, conversion_action.third_party_app_analytics_settings.provider_name, conversion_action.type, conversion_action.value_settings.always_use_default_value, conversion_action.value_settings.default_currency_code, conversion_action.value_settings.default_value, conversion_action.view_through_lookback_window_days,  metrics.conversion_last_conversion_date FROM conversion_action WHERE metrics.conversion_last_conversion_date > '2020-01-01'"; var TimeFrame = spreadsheet.getRangeByName("Last_x_days").getValue(); var now = new Date(); var from = new Date(now.getTime() - 10 * MILLIS_PER_DAY); var query2 = "SELECT conversion_action.firebase_settings.event_name,  conversion_action.type, conversion_action.name,conversion_action.resource_name, conversion_action.third_party_app_analytics_settings.event_name, metrics.conversion_last_conversion_date FROM conversion_action WHERE metrics.conversion_last_conversion_date > '" + Utilities.formatDate(from, AdsApp.currentAccount().getTimeZone(), 'yyyy-MM-dd') + "'"; var report = AdWordsApp.report(query2, { apiVersion: 'v8' }); 

But I get a vague error:

We're sorry, a server error occurred. Please wait a bit and try again. (file code.gs, line 25) which is the last code line here

What can it be?

I have a script that shows 10 most clicked keywords, their average CPC and conversions. While previewing the script it works fine. But when I send it to my email, only last row of the 10 rows shows. What is wrong here?

function main() {   var keywords = AdsApp.keywords()       .orderBy("Clicks DESC")   //  .orderBy("Impressions DESC")       .forDateRange("THIS_MONTH")       .withLimit(10)       .get(); Logger.log("10 most clicked keywords");   while (keywords.hasNext()) {     var keyword = keywords.next();     content = keyword.getText() + " | Clicks: " + keyword.getStatsFor("THIS_MONTH").getClicks() + " | CPC: " + keyword.getStatsFor("THIS_MONTH").getAverageCpc().toFixed(2) +      " | Conversions: " + keyword.getStatsFor("THIS_MONTH").getConversions();   }    MailApp.sendEmail({             to: 'myemail@myemail.com',             subject: "10 most clicked keywords",             htmlBody: content });      }