Google Analytics API Tutorial Does Not Work

Asked 2 years ago, Updated 2 years ago, 140 views

I tried a tutorial on Google Analytics' official website (https://developers.google.com/analytics/devguides/config/mgmt/v3/quickstart/web-js?hl=ja), but it doesn't work.


[Tries]

①Follow the guide on the official website above to activate the API and create a client ID
②Download the official website html file (HelloAnalytics.html) and change the ' part of the code below to your client ID ('→'xxxxx.apps.googleusercontent.com')
③Place the hmtl file above in the shared folder of the vagrant environment where Apache is started and check the browser for display

<!DOCTYPE html>
<html>
<head>
  <metacharset="utf-8">
  <title>Hello Analytics-Aquickstart guide for JavaScript</title>
</head>
<body>

<button id="auth-button" hidden>Authorize</button>

<h1>Hello Analytics</h1>

<textareacols="80" rows="20" id="query-output">/textarea>

<script>

  // Replace with your client ID from the developer console.
  var CLIENT_ID = '<YOUR_CLIENT_ID>';

  // Set authorized scope.
  varSCOPES=['https://www.googleapis.com/auth/analytics.readonly'];

  function authorize (event) {
    // Handles the authorization flow.
    // `immediate`should be false when invoked from the button click.
    varuseImmediate=event?false:true;
    var authData = {
      client_id —CLIENT_ID,
      scope —SCOPES,
      immediate —useImmediate
    };

    gapi.auth.authorize(authData, function(response){
      var authButton= document.getElementById('auth-button');
      if(response.error){
        authButton.hidden=false;
      }
      else{
        authButton.hidden=true;
        queryAccounts();
      }
    });
  }

function queryAccounts() {
  // Load the Google Analytics client library.
  gapi.client.load('analytics', 'v3').then(function(){

    // Get a list of all Google Analytics accounts for this user
    gapi.client.analytics.management.accounts.list().then(handleAccounts);
  });
}

function handleAccounts (response) {
  // Handles the response from the accounts list method.
  if(response.result.items&&response.result.items.length){
    // Get the first Google Analytics account.
    var firstAccountId=response.result.items[0].id;

    // Query for properties.
    queryProperties(firstAccountId);
  } else{
    console.log('No accounts found for this user.');
  }
}

function queryProperties(accountId){
  // Get list of all the properties for the account.
  gapi.client.analytics.management.webproperties.list(
      {'accountId':accountId})
    .then(handleProperties)
    .then(null, function(err){
      // Log any errors.
      console.log(err);
  });
}

function handleProperties (response) {
  // Handles the response from the webproperties list method.
  if(response.result.items&&response.result.items.length){

    // Get the first Google Analytics account
    var firstAccountId=response.result.items[0].accountId;

    // Get the first property ID
    var firstPropertyId=response.result.items[0].id;

    // Query for Views (Profiles).
    queryProfiles(firstAccountId, firstPropertyId);
  } else{
    console.log('No properties found for this user.');
  }
}

function queryProfiles(accountId,propertyId){
  // Get a list of all Views (Profiles) for the first property
  // of the first account.
  gapi.client.analytics.management.profiles.list({
      'accountId': accountId,
      'webPropertyId': propertyId
  })
  .then(handleProfiles)
  .then(null, function(err){
      // Log any errors.
      console.log(err);
  });
}

function handleProfiles (response) {
  // Handles the response from the profiles list method.
  if(response.result.items&&response.result.items.length){
    // Get the first View (Profile) ID.
    var firstProfileId=response.result.items[0].id;

    // Query the Core Reporting API.
    queryCoreReportingApi(firstProfileId);
  } else{
    console.log('No views (profiles) found for this user.');
  }
}

function queryCoreReportingApi(profileId){
  // Query the Core Reporting API for the number sessions for
  // The past seven days.
  gapi.client.analytics.data.ga.get({
    'ids': 'ga:' + profileId,
    'start-date': '7 daysAgo',
    'end-date': 'today',
    'metrics': 'ga:sessions'
  })
  .then(function(response){
    var formattedJson=JSON.stringify(response.result, null, 2);
    document.getElementById('query-output').value=formattedJson;
  })
  .then(null, function(err){
      // Log any errors.
      console.log(err);
  });
}

  // Add an event listener to the 'auth-button'.
  document.getElementById('auth-button').addEventListener('click', authorize);
</script>

<script src="https://apis.google.com/js/client.js?onload=authorize"></script>

</body>
</html>

[Problems]

//Handles the authorization flow.
    // `immediate`should be false when invoked from the button click.
    varuseImmediate=event?false:true;
    var authData = {
      client_id —CLIENT_ID,
      scope —SCOPES,
      immediate —useImmediate
    };

    gapi.auth.authorize(authData, function(response){
      var authButton= document.getElementById('auth-button');
      if(response.error){
        authButton.hidden=false;
      }
      else{
        authButton.hidden=true;
        queryAccounts();
      }
    });
  }

"The ""Authorize"" button, which should have been displayed, is not displayed because the above authentication part?" is not working well."
Remove "hidden" from <button id="auth-button" hidden>Authorize</button> in the developer tool and
Press the button to display an error screen

↓This is the contents of the error screen

400.That's an error.

Error: invalid_request

Permission denied to generate login hint for target domain.

Request Details
response_type=permission id_token
scope=https://www.googleapis.com/auth/analytics.readonly
openid.realm=
redirect_uri=storagerlay://http/192.168.33.12?id=auth219779
client_id=xxxxx.apps.googleusercontent.com
ss_domain = http://192.168.33.12
gsiwebsdk=shim
That's all we know.

解決What I want to solve したい
①I want to find and resolve errors in this sample file and obtain arbitrary data.
②Using this sample file, I would like to use Google realtime reporting api to display the number of active users who are currently browsing by ○ on the top page of my web service.(The script will be written in jquery) (*)

*First of all, please let me know the reason why the sample file does not work.
 "If possible, it would be very helpful if you could tell me ""Is it possible to use this sample in the first place to do the process like in の above?"" and ""If possible, what kind of process should I write down?"""

Thank you for your cooperation.

88/5 19:30 Additional
Thanks to shingo.nakanishi's response, I was able to display the Authorize button.

◎ Display Method

var authData={
  client_id —CLIENT_ID,
  scope —SCOPES,
  immediate —useImmediate
};

The above part is

var authData={
  client_id —CLIENT_ID,
  scope —SCOPES,
  immediate —false
};

A button was displayed by changing to .

However, the error has not been resolved since the button was clicked.
Screenshot of error screen
It says OAuth Error, so I can guess that the authentication part before the data acquisition was set incorrectly, but I don't know exactly what to correct.

I look forward to hearing from you soon.
Thank you for your cooperation.

javascript oauth google-api google-analytics-api

2022-09-29 21:28

1 Answers

Error:invalid_request

Permission denied to generate login hint for target domain.

See

Probably

https://stackoverflow.com/questions/36020374/google-permission-denied-to-generate-login-hint-for-target-domain-not-on-localh

Your answer is

https://stackoverflow.com/questions/36020374/google-permission-denied-to-generate-login-hint-for-target-domain-not-on-localh/36162748#36162748

would be useful.

Okay, If configured this out.I was using an IP address (as in
"http://175.132.64.120") for the redirecturi, as this was a test site
on the live server, and Google only accepts actual urls(as in
"http://mycompany.com "or"http://localhost") as redirect uris.

Which, you know, THEY COULD HAVE SAID SOMEWHERE IN THE DOCUMENTATION,
but whatver.

(My translation)

I understand.I used the test site IP address ("http://175.132.64.120") for the redirect.
Google only allowed real URIs to be redirected (for example, "http://mycompany.com" or
ahttp://localhost").

Where is this written in the document?

So,

redirect_uri=storage://http/192.168.33.12?id=auth219779

If you do not name the part that appears to have been registered directly with the IP address, you will get an error.

Supplementary

The above authentication part ? is not working, or the Authorize button, which should have been displayed, is not displayed.

As I commented on the question, if you look at the contents of response.error, you may find more detailed tips in error.

add

When I wrote console.log(response.error) in the gapi.auth.authorize(authData, function(response) function and checked it with the developer tool, it was just immediate_failed...

when it comes to

https://stackoverflow.com/questions/43627474/immediate-failed-error-in-google-analytics

in the comments.

Did you try with immediate: false? – Alessandro Apr 26' 17 at 7:21

Thanks!! it works! – oihi08 Apr 26'17 at 7:29

I think the part that will help.

(My translation)

Did you try immediate:false?

Thank you!!It's working!

If you look at the sources quoted from the tutorial site,

//`immediate`should be false when invoked from the button click.
varuseImmediate=event?false:true;
var authData = {
  client_id —CLIENT_ID,
  scope —SCOPES,
  immediate —useImmediate
};

There is a part that says

immediate should be false when invoked from the button click.

(My translation)

Use false when calling from button click.

Therefore,

var authData={
  client_id —CLIENT_ID,
  scope —SCOPES,
  immediate —false
};

If this is the case, the button appears.


2022-09-29 21:28

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.