0
votes

I have turned on my Analytics API in Google Developers Console and my credentials (client ID and client secret) are input correctly. Here is my code in my Google Apps Script:

var clientId = "(censored)";
var consumerSecret = "(censored)";

var oAuthConfig = UrlFetchApp.addOAuthService('analytics');
oAuthConfig.setAccessTokenUrl("https://accounts.google.com/o/oauth2/token");
oAuthConfig.setRequestTokenUrl("https://accounts.google.com/o/oauth2/token?scope=https://www.googleapis.com/auth/analytics.readonly");
oAuthConfig.setAuthorizationUrl("https://accounts.google.com/o/oauth2/auth");
oAuthConfig.setConsumerKey(clientId);
oAuthConfig.setConsumerSecret(consumerSecret);

var url = "https://www.googleapis.com/analytics/v3/data/ga?ids=ga:91669545&start-date=2014-12-01&end-date=2014-12-31&metrics=ga:sessions,ga:bounces";
var response = UrlFetchApp.fetch(url,{"muteHttpExceptions":true});
Logger.log(response);

My "response" returns a 401 error, meaning it is not even submitting the authorization info at the API, otherwise it would return saying my credentials were incorrect. The Google Apps Script application is also throwing this error at me:

Access Not Configured. The API is not enabled for your project, or there is a per-IP or per-Referer restriction configured on your API key and the request does not match these restrictions. Please use the Google Developers Console to update your configuration.

Any ideas on why I can't get oauth to work here? Thanks!

1

1 Answers

0
votes

UrlFetchApp.setOAuthService() doesn't support OAuth2 which it appears you are trying to use.

ref an answer from one of the Google team to a request for it on the issue tracker.: Update #9 to issue #929

There are 1 or 2 ways to make OAuth2 connections from Apps Script, but not this way.

The method referenced in the answer linked: https://github.com/googlesamples/apps-script-oauth2 or http://ramblings.mcpher.com/Home/excelquirks/oauthtoo/ezyoauth2


Try the Apps Script in-built Analytics API methods - this may cover what you need for Analytics integration: https://developers.google.com/apps-script/advanced/analytics