Este tutorial mostra as etapas necessárias para acessar uma conta do Google Analytics, consultar as APIs do Google Analytics, lidar com as respostas da API e gerar os resultados. A API Core Reporting v3.0, a API Management v3.0 e o OAuth2.0 são usados neste tutorial.
Etapa 1: ativar a API Google Analytics
Para começar a usar a API Google Analytics, primeiro use a ferramenta de configuração, que fornece orientações para você criar um projeto no console de APIs do Google, ativar a API e criar credenciais.
Criar um Client-ID
Na página "Credenciais":
- Clique em Criar credenciais e selecione OAuth Client-ID.
- Selecione Aplicativo da Web em TIPO DE APLICATIVO.
- Defina um nome para a credencial.
- Defina as ORIGENS JAVASCRIPT AUTORIZADAS como http://localhost:8080.
- Defina os URIS DE REDIRECIONAMENTO AUTORIZADOS como http://localhost:8080/oauth2callback.
- Clique em Criar.
Etapa 2: Configurar a amostra
Você precisará criar um arquivo chamado HelloAnalytics.html
, que conterá o código HTML e JavaScript do nosso exemplo.
- Copie ou
faça o download do código-fonte a seguir para
HelloAnalytics.html
. - Substitua
'<YOUR_CLIENT_ID>'
pelo ID do cliente. criados acima.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Hello Analytics - A quickstart guide for JavaScript</title> </head> <body> <button id="auth-button" hidden>Authorize</button> <h1>Hello Analytics</h1> <textarea cols="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. var SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']; function authorize(event) { // Handles the authorization flow. // `immediate` should be false when invoked from the button click. var useImmdiate = event ? false : true; var authData = { client_id: CLIENT_ID, scope: SCOPES, immediate: useImmdiate }; 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 a 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': '7daysAgo', '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>
Etapa 3: Executar a amostra
Depois que você ativar a API Analytics e configurar o código-fonte da amostra, ela estará pronta para ser executada.
- Publique
HelloAnalytics.html
no seu servidor da Web e carregue a página no navegador. - Clique no
botão "Autorizar" e autorize o acesso ao Google Analytics.
Quando você concluir essas etapas, a amostra gerará o nome da primeira vista (perfil) do Google Analytics do usuário autorizado, além do número de sessões dos últimos sete dias.
Com o objeto de serviço autorizado do Google Analytics, agora você pode executar qualquer uma das amostras de código nos documentos de referência da API Management. Por exemplo, tente alterar o código para usar o método accountSummaries.list.