I am using the Google Postmaster Tools API to get some Google Sheet reports using Google Apps Script. I had to create a project in Google Cloud to get the Oauth 2.0 credentials and so far so good, I run the script and get the data on the google sheet.
The problem is that if I try to automate it – the script must start itself once a week – I get no errors but neither do I get the data written on the sheet, and I think it depends on the fact that for authentication it is always necessary to copy the url as shown here
var authorisationUrl = service.getAuthorizationUrl(); Logger.log('Open the following URL and re-run the script: %s', authorizationUrl);
This is a simplified version of the script (taken directly from the official google developer documentation):
var CLIENT_ID = 'xxx;
var CLIENT_SECRET = 'xxx';
function run() {
var service = getService_();
if (service.hasAccess()) {
var url = 'xxxxxxx';
var response = UrlFetchApp.fetch(url, {
headers: {
Authorization: 'Bearer ' + service.getAccessToken()
}
});
var result = JSON.parse(response.getContentText());
///////// all my stuff done here!!! ################################
} else {
var authorizationUrl = service.getAuthorizationUrl();
Logger.log('Open the following URL and re-run the script: %s', authorizationUrl);
}
}
/**
* Reset the authorization state, so that it can be re-tested.
*/
function reset() {
getService_().reset();
}
/**
* Configures the service.
*/
function getService_() {
return OAuth2.createService('Google Postmaster Tools')
// Set the endpoint URLs.
.setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/v2/auth')
.setTokenUrl('https://oauth2.googleapis.com/token')
// Set the client ID and secret.
.setClientId(CLIENT_ID)
.setClientSecret(CLIENT_SECRET)
// Set the name of the callback function that should be invoked to
// complete the OAuth flow.
.setCallbackFunction('authCallback')
// Set the property store where authorized tokens should be persisted.
.setPropertyStore(PropertiesService.getUserProperties())
// Set the scope and additional Google-specific parameters.
.setScope('xxxxx')
//.setParam('access_type', 'offline')
.setParam('prompt', 'consent')
.setParam('login_hint', Session.getActiveUser().getEmail());
}
/**
* Handles the OAuth callback.
*/
function authCallback(request) {
var service = getService_();
var authorized = service.handleCallback(request);
if (authorized) {
return HtmlService.createHtmlOutput('Success!');
} else {
return HtmlService.createHtmlOutput('Denied.');')
}
}
/**
* Logs the redict URI to register in the Google Developers Console.
*/
function logRedirectUri() {
Logger.log(OAuth2.getRedirectUri());
}
Can anyone tell me how I can automate this script using apps script triggers?
I set the triggers on a time basis but nothing happens even though the log returns zero errors
Odema is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.