仅使用访问令牌在节点中获取Google+用户配置文件

Get google+ user profile in node using just access token

本文关键字:获取 Google+ 用户 配置文件 节点 访问令牌      更新时间:2023-09-26

我正在尝试在Node中获取用户配置文件详细信息。

流程是这样的,我有一个移动应用程序为我生成令牌(通过 Google 和本机 SDK 进行身份验证),然后将令牌发送到我的节点服务器,我想从 Google 获取有关用户的详细信息。我尝试了以下方法(假设我有来自客户端access_token):

var request = require('request');
request('https://www.googleapis.com/oauth2/v2/userinfo?access_token=' + access_token, function(err, res, body) {
  if (err) return callback(err);
  if (res.statusCode != 200) {
    return callback(new Error('Invalid access token: ' + body));
  }
  else {
    var me;
    try { me = JSON.parse(body);}
    catch (e) {
      return callback(new Error('Unable to parse user data: ' + e.toString()));
    }
    console.log('user profile:', me);
  }
});

这有效,但有时我得到不好的响应,例如空displayName字段、空email(即使我有范围),而且总体上不可靠。

我尝试使用Google API Node模块,但那里的流程假设我需要获取令牌并且不必要地复杂。

除此之外,我不明白谷歌的API版本之间的区别,也不知道什么时候使用什么。

编辑

似乎空displayName字段的问题只发生在通过 iOS SDK 生成的令牌上。使用 Android SDK 生成的令牌很好,使用它们调用 API 会在 displayName 中解析。我尝试使用iOS令牌并调用以下API:

https://www.googleapis.com/plus/v1/people/me?access_token=...

我在结果中得到了一个displayName,但是在我的服务器打了几个电话后,我得到了

{
 "error": {
  "errors": [
   {
    "domain": "usageLimits",
    "reason": "dailyLimitExceededUnreg",
    "message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.",
    "extendedHelp": "https://code.google.com/apis/console"
   }
  ],
  "code": 403,
  "message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup."
 }
}

该问题仅与我的IOS用户生成的令牌有关。

似乎我通过IOS SDK获得的令牌不适合与我在问题(https://www.googleapis.com/oauth2/v2/userinfo中提到的API调用一起使用)。Android SDK 生成的令牌在上述调用中工作正常。

因此,为了找到一个共同点,我必须从我的服务器使用以下 API 调用:

https://www.googleapis.com/plus/v1/people/me?access_token=...

你应该得到一个类似于这样的对象(省略个人字段):

{
  kind:"plus#person",
  etag:"...",
  gender:"male",
  emails:[
    {
      value:"...",
      type:"account"
    }
  ],
  urls:[
    {
      value:"...",
      label:"Buzz"
    }
  ],
  objectType:"person",
  id:"...",
  displayName:"...",
  name:{
    familyName:"...",
    givenName:"..."
  },
  url:"...",
  image:{
    url:"..."
  },
  isPlusUser:true,
  language:"en",
  ageRange:{
    min:21
  },
  verified:false,
  cover:{
    layout:"banner",
    coverPhoto:{
      url:"...",
      height:626,
      width:940
    },
    coverInfo:{
      topImageOffset:0,
      leftImageOffset:0
    }
  }
}