Here è un esempio di come impostare autenticazione lato server. Il codice precedente crea un nuovo token quando qualcuno visita il sito. È possibile visualizzare l'endpoint che ottiene quel token di accesso here.
Qui di seguito sono i punti generali per arrivare a una versione funzionante:
Fase 1: Creare un account di servizio e scaricare il JSON chiave
Fase 2: Aggiungere l'account di servizio come utente in Google Analytics
Fase 3: utilizzare i dati chiave JSON per richiedere un token di accesso
# service-account.py
import json
from oauth2client.client import SignedJwtAssertionCredentials
# The scope for the OAuth2 request.
SCOPE = 'https://www.googleapis.com/auth/analytics.readonly'
# The location of the key file with the key data.
KEY_FILEPATH = 'path/to/json-key.json'
# Load the key file's private data.
with open(KEY_FILEPATH) as key_file:
_key_data = json.load(key_file)
# Construct a credentials objects from the key data and OAuth2 scope.
_credentials = SignedJwtAssertionCredentials(
_key_data['client_email'], _key_data['private_key'], SCOPE)
# Defines a method to get an access token from the credentials object.
# The access token is automatically refreshed if it has expired.
def get_access_token():
return _credentials.get_access_token().access_token
Torna lato client:
Fase 4: Caricare la libreria Embed API.
<script>
(function(w,d,s,g,js,fs){
g=w.gapi||(w.gapi={});g.analytics={q:[],ready:function(f){this.q.push(f);}};
js=d.createElement(s);fs=d.getElementsByTagName(s)[0];
js.src='https://apis.google.com/js/platform.js';
fs.parentNode.insertBefore(js,fs);js.onload=function(){g.load('analytics');};
}(window,document,'script'));
</script>
Fase 5: Aggiungere contenitori HTML per ospitare i componenti del cruscotto.
<div id="chart-1-container"></div>
<div id="chart-2-container"></div>
Passo 6: Scrivere il codice cruscotto.
Utilizzare il token di accesso ottenuto nel passaggio 3 per autorizzare l'API di incorporamento.
gapi.analytics.ready (function() {
/**
* Authorize the user with an access token obtained server side.
*/
gapi.analytics.auth.authorize({
'serverAuth': {
'access_token': '{{ ACCESS_TOKEN_FROM_SERVICE_ACCOUNT }}'
}
});
...
il lavoro aggiuntivo di creare un endpoint che restituisce il token dipende da voi indietro realizzazione finale, ma il codice sorgente di come la demo lo si può trovare here.
https://ga-dev-tools.appspot.com/embed-api/server-side-authorization/ – Matt