如何从谷歌API检索用户的数据?

时间:2016-01-12 11:24:27

标签: javascript node.js google-api

对于允许服务访问其数据的用户,我希望实现一个函数来检索和处理这些数据。

当用户第一次执行身份验证时,将显示以下屏幕: enter image description here

在Google开发者控制台中,我创建了一个服务帐户,选中了“启用Google Apps域范围的委派”,并下载了json文件并将其包含在以下代码中:

var google = require('googleapis');
var OAuth2 = google.auth.OAuth2;
var fit = google.fitness('v1');
var key = require('../../config/meelio_google_service_account.json'); 

/*
This file contains following properties:
{
  "type": "service_account",
  "project_id": "meelio-dev",
  "private_key_id": "***",
  "private_key": "-----BEGIN PRIVATE KEY-----
***",
  "client_email": "mfit-205@meelio-dev.iam.gserviceaccount.com",
  "client_id": "1022202xxx41842",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://accounts.google.com/o/oauth2/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/mfit-205%40meelio-dev.iam.gserviceaccount.com"
}
*/

var oauth2Client = new OAuth2(key.client_id, key.private_key, 'http://localhost:3000/api/auth/google/oauth2callback');

var scopes = ['https://www.googleapis.com/auth/fitness.activity.read',
    'https://www.googleapis.com/auth/fitness.activity.write',
    'https://www.googleapis.com/auth/fitness.body.read',
    'https://www.googleapis.com/auth/fitness.body.write',
    'https://www.googleapis.com/auth/fitness.location.read',
    'https://www.googleapis.com/auth/fitness.location.write'];

module.exports.listUserDataSourcesTest = function(req, res){
    var jwtClient = new google.auth.JWT(key.client_email, null, key.private_key, scopes, null);

    jwtClient.authorize(function(err, tokens) {
        if (err) {
            console.log(err);
            return;
        }
        oauth2Client.setCredentials({
            access_token: tokens.access_token
        });
        // Make an authorized request to list Drive files.
        fit.users.dataSources.list({auth: oauth2Client, userId: '104169835623446790746'}, function(err, resp){
            console.log(resp);
        });

    });
}

执行google fitness function(fit.user.dataSources.list())时会返回错误:

  

“未经授权的访问”

由于我不确定错误是否是由不恰当的权限(或其他)设置或错误的代码引起的,所以如果有人可以通过建议以正确的方式检索用户的数据和/来帮助解决此问题,我将非常感谢或修复谷歌开发者控制台中的设置。

谢谢!

1 个答案:

答案 0 :(得分:0)

根据documentation,无法使用其他用户的ID:

  

检索已识别人员的数据集。用我来表示   认证用户。目前只支持我。

可用(例如存储在数据库中)用户令牌和access_token,可以使用以下函数检索数据:

function listUserDataSources(access_token, refresh_token, res){
     oauth2Client.setCredentials({
               access_token: tokens.token,
               refresh_token: tokens.refreshToken
           });  
    fit.users.dataSources.list({auth: oauth2Client, userId: 'me'}, function(err, resp){
               res.json([resp]);      

    });
}