Google Analytics Embed API: How to retireve access token?

前端 未结 1 1115
甜味超标
甜味超标 2020-12-10 20:56

I\'ve used the code provided in this question to gain access to the Google Analytics Embed API. I want to display the statistics from my website without the need for users w

1条回答
  •  忘掉有多难
    2020-12-10 21:48

    You can absolutely use a service account with the Embed API. The trick is getting an access token from the .p12 file, but once you have a valid access token, your code will work just fine.

    I've just verified this myself. Here are the steps I took:

    I created a service account, and then I followed the steps listed on the google-oauth-jwt node module documentation page to get an access token. (If you're not using Node.js, just do a Google search for how this works in other languages, this devguide describes the process for PHP.)

    I converted the .p12 file to a .pem file (required to work with Node) with this command:

    openssl pkcs12 -in downloaded-key-file.p12 -out your-key-file.pem -nodes
    

    I ran the following Node program to get an access token from the .pem file:

    var googleAuth = require('google-oauth-jwt');
    var authOptions = {
      email: 'my-service-account@developer.gserviceaccount.com',
      keyFile: './key.pem',
      scopes: ['https://www.googleapis.com/auth/analytics']
    };
    
    googleAuth.authenticate(authOptions, function (err, token) {
      console.log(token);
    });
    

    Once I had the access token, I just substituted it into the code you have in your questions, fired up a local server, and everything worked just fine.

    0 讨论(0)
提交回复
热议问题