【问题标题】:Google+ Api get user emailGoogle+ Api 获取用户电子邮件
【发布时间】:2017-05-31 11:04:36
【问题描述】:

我正在使用 Google+ API 创建一个注册。将数据插入我的用户表时,我想获取用户的电子邮件。尝试执行此操作时出现错误。我的代码如下所示:

var API_KEY = 'A*****';         

plus.people.get({
    auth: API_KEY,
    userId: req.body.userID
}, function (err, user) {
    if( err ) { res.json( JSON.stringify( err ) );  return; }
    console.log(user.emails);

    User.find({ where:{ social_id:req.body.userID, type: 2 } }).then( existingUser =>{              
    if( existingUser ) throw new Error('social_user_existing');
    if(!existingUser){
    User.build({
        username: user.displayName,
        social_id : req.body.userID, 
        social_token :req.body.token, 
        type : 2
        }).save();                      
    }                          
    }).then(function( new_g_user ){                 
        return res.json( rs.success({ username: user.displayName, user_id: user.id, jwt: new_g_user.getJwt() }) );
    }).catch(function(err){
        res.json( rs.errorCode(err.message) );
    });   
});     

我尝试使用 user.emails 和 user.emails[0].value 获取用户的电子邮件,以至少获取第一封电子邮件的值。每次,响应都是“未定义的”。我提到 user.kind 是'plus#person',而不是"plus#personOpenIdConnect"。这会导致我得到回应吗?谢谢!

【问题讨论】:

    标签: node.js google-api google-plus


    【解决方案1】:

    您正在使用 API 密钥进行身份验证,这意味着您只能访问公共数据。

    请求

    获取https://www.googleapis.com/plus/v1/people/+lindalawton

    回复

    {
     "kind": "plus#person",
     "etag": "\"Sh4n9u6EtD24TM0RmWv7jTXojqc/8CXX3KsOcUfAF5mmrG4vyB-YNig\"",
     "occupation": "Google Developer Expert, BIA Developer at Targit",
     "skills": "Experience primarily in regards Microsoft products, Visual Studio, Bids, C# and asp.net.  Past experience with PHP,JavaScript, MySQL and Linux.  In recent years I have begun focusing on Business Intelligence, Data Warehousing, SQL Server / Analysis Services / Integration Services.   Experience with OAuth2, Google Analytics API, Google Drive SDK.",
     "gender": "female",
     "urls": [
      {
       "value": "http://www.youtube.com/user/Atthena71",
       "type": "otherProfile",
       "label": "Linda Lawton"
      },
      {
       "value": "http://twitter.com/LindaLawtonDK",
       "type": "otherProfile",
       "label": "lindalawtondk"
      },
      {
       "value": "http://stackoverflow.com/users/1841839/daimto",
       "type": "otherProfile",
       "label": "Stackoverflow / StackExchange"
      },
      {
       "value": "http://www.linkedin.com/profile/edit?trk=nav_responsive_sub_nav_edit_profile",
       "type": "otherProfile",
       "label": "Linkedin"
      },
      {
       "value": "http://daimto.com/",
       "type": "contributor",
       "label": "Daimto - data import tutorials"
      },
      {
       "value": "https://github.com/LindaLawton",
       "type": "contributor",
       "label": "GitHub - projects"
      },
      {
       "value": "https://github.com/google/google-api-dotnet-client",
       "type": "contributor",
       "label": "Google APIs .Net client - GitHub"
      },
      {
       "value": "https://github.com/LindaLawton/Google-Dotnet-Samples",
       "type": "contributor",
       "label": "Google APIs .Net Samples - GitHub "
      },
      {
       "value": "https://developers.google.com/analytics/",
       "type": "other",
       "label": "Google Analytics"
      },
      {
       "value": "https://developers.google.com/",
       "type": "other",
       "label": "Google Developers"
      },
      {
       "value": "https://developers.google.com/experts/+LindaLawton",
       "type": "other",
       "label": "Google Developer Expert - Linda Lawton"
      }
     ],
     "objectType": "person",
     "id": "117200475532672775346",
     "displayName": "Linda Lawton",
     "name": {
      "familyName": "Lawton",
      "givenName": "Linda"
     },
     "tagline": "Google Developer Expert 2014 - 2017",
     "braggingRights": "Extreme Beekeeper first to recorded an Hive inspection using Google Glass with out a veil on.",
     "aboutMe": "\u003cdiv\u003e\u003cb\u003eBackground\u003c/b\u003e\u003c/div\u003e\u003cdiv\u003e\u003cdiv\u003eI have been working as an application developer since 1995. I have worked with a number of database systems Oracle, Microsoft SQL Server, and MySQL.  In recent years I have been mainly working with Microsoft products, Visual Studio, SSIS, and C#.   I the past I worked a lot with web development PHP, JavaScript, Ajax, power-builder,  Cobol and ASP.net.\u003c/div\u003e\u003c/div\u003e\u003cdiv\u003e\u003cbr /\u003e\u003c/div\u003e\u003cdiv\u003eWhile I have done front end development in the past. I find working with backed development working on automated systems fascinating.    I have spent the last 5 years creating custom SSIS (Dlls), and services and APIs for the cloud (Azure).\u003c/div\u003e\u003cdiv\u003e\u003cbr /\u003e\u003c/div\u003e\u003cdiv\u003e\u003cb\u003eGoogle API Addiction\u003c/b\u003e \u003c/div\u003e\u003cdiv\u003eIn 2012 I began working with the Google APIs, starting with the Google Analytics API.  I learned to appreciate the fact that Google is so open and willing to give us access to their systems. I started blogging about how to use the APIs writing short tutorials with sample projects.   \u003ca href=\"http://www.daimto.com/\" rel=\"nofollow\" target=\"_blank\"\u003eDaimto - Data Import Tutorials\u003c/a\u003e.   This along with my presents on a number of \u003ca href=\"http://stackoverflow.com/users/1841839/daimto\" rel=\"nofollow\" target=\"_blank\"\u003eDeveloper forms\u003c/a\u003e lead me to discovered by Google.  I became one of the first \u003ca href=\"https://developers.google.com/experts/+LindaLawton\" rel=\"nofollow\" target=\"_blank\"\u003eGoogle Developer Experts for Google Analytics\u003c/a\u003e.  \u003c/div\u003e\u003cdiv\u003e\u003cbr /\u003e\u003c/div\u003e\u003cdiv\u003eI also help support the \u003ca href=\"https://github.com/google/google-api-dotnet-client\" rel=\"nofollow\" target=\"_blank\"\u003eGoogle APIs client Library for .NET\u003c/a\u003e which provides simple, flexible, and powerful access to Google APIs such as Drive, YouTube, Calendar, Storage and Analytics.\u003c/div\u003e\u003cdiv\u003e\u003cbr /\u003e\u003c/div\u003e\u003cdiv\u003e\u003cb\u003eLife\u003c/b\u003e\u003c/div\u003e\u003cdiv\u003eI grew up in a small town in \u003ca href=\"http://en.wikipedia.org/wiki/Dartmouth,_Massachusetts\" rel=\"nofollow\" target=\"_blank\"\u003eMassachusetts\u003c/a\u003e, USA, I moved to \u003ca href=\"http://en.wikipedia.org/wiki/Denmark\" rel=\"nofollow\" target=\"_blank\"\u003eDenmark \u003c/a\u003ein 1998 and have lived here since. I have a 22 year old daughter.  My hobbies include reading science fiction, painting, and gardening.   \u003c/div\u003e",
     "url": "https://plus.google.com/+LindaLawton",
     "image": {
      "url": "https://lh5.googleusercontent.com/-a1CWlFnA5xE/AAAAAAAAAAI/AAAAAAAAdVM/sHkU9F-AwwQ/photo.jpg?sz=50",
      "isDefault": false
     },
     "organizations": [
      {
       "name": "Newberry College",
       "title": "computer science",
       "type": "school",
       "startDate": "1991",
       "endDate": "1994",
       "primary": false
      },
      {
       "name": "TARGIT",
       "title": "Business Intelligence Developer",
       "type": "work",
       "startDate": "2011",
       "primary": true
      },
      {
       "name": "Logimatic",
       "title": "developer",
       "type": "work",
       "startDate": "2008",
       "endDate": "2010",
       "primary": false
      }
     ],
     "placesLived": [
      {
       "value": "Aalborg Denmark",
       "primary": true
      },
      {
       "value": "Marathon Florida"
      },
      {
       "value": "Dartmouth Massachusetts"
      },
      {
       "value": "Ashford Connecticut"
      },
      {
       "value": "Nykøbing Mors Denmark"
      }
     ],
     "isPlusUser": true,
     "circledByCount": 2006,
     "verified": false,
     "cover": {
      "layout": "banner",
      "coverPhoto": {
       "url": "https://lh3.googleusercontent.com/t2ViXd7ar3MeiOCeTe2g86Qd7wOnbRvuf3eTW3LPrs8jwBJwKS6gsC4KWhvbRSytJ5fsDne3sw=s630-fcrop64=1,00000000ffffffff",
       "height": 528,
       "width": 940
      },
      "coverInfo": {
       "topImageOffset": 0,
       "leftImageOffset": 0
      }
     }
    }
    

    只会返回所述用户设置为公开的内容。如果他们的电子邮件不公开,您将无法看到它。

    【讨论】:

    • 感谢您快速而完整的回答!请告诉我,即使不公开,我如何获取用户的电子邮件地址?我应该用包含 clientID 和 clientSecret 的对象替换 API KEY 吗?如果是肯定的,接下来我该怎么做?
    • 据我所知,如果某人的电子邮件地址未设置为公开,则无法获取该地址。 Google 没有电子邮件地址 API,这在很多方面都很糟糕。
    • 根据本文档:developers.google.com/identity/protocols/OAuth2,说:'在您的应用程序可以使用 Google API 访问私有数据之前......',如果使用 OAuth,我可以访问私有数据。所以,我想,我必须改变我的代码。谢谢!
    • 如果您使用 google 登录,请尝试查看电子邮件范围。这应该使您可以访问与他们的帐户关联的电子邮件地址。 developers.google.com/identity/sign-in/web
    【解决方案2】:

    正如@DalmTo 所提到的,API 密钥可用于访问公共数据。如果您想访问用户的私人信息,您必须使用 OAuth。

    使用googleapis 中的OAuth2 类来设置身份验证:

    const google = require('googleapis');
    const OAuth2 = google.auth.OAuth2;
    
    const CREDENTIALS = require("./credentials.json");
    
    var googleAuth = new OAuth2(
      CREDENTIALS.web.client_id,
      CREDENTIALS.web.client_secret,
      CREDENTIALS.web.redirect_uris[0]
    );
    

    credentials.json 是您可以从您的 Google 应用程序(凭据部分)下载的文件,其中包含应用程序密钥。

    获得访问令牌后,您需要执行以下操作:

    googleAuth.setCredentials({
      access_token: yourAccessToken
    });
    

    最后,您将使用auth: googleAuth,而不是使用auth: API_KEY

    plus.people.get({
        auth: googleAuth,
        userId: req.body.userID
    }, function (err, user) {
        if( err ) { res.json( JSON.stringify( err ) );  return; }
        console.log(user.emails);
    });
    

    如果一切顺利,你应该可以从用户那里得到隐私信息。

    请注意,要访问电子邮件,您需要 https://www.googleapis.com/auth/userinfo.email 范围。


    要获取用于测试的访问令牌,您可以使用 OAuth 游乐场:

    1. 打开https://developers.google.com/oauthplayground/
    2. 输入你需要的授权范围,然后点击蓝色按钮:

      它会进行几次重定向。

    3. 第二步中再次点击蓝色按钮,将授权码转换为访问令牌。

    现在,您将在屏幕右侧看到您的access_token

    {
      "access_token": "ya29.G....OEDi", 
      "token_type": "Bearer", 
      "expires_in": 3600, 
      "refresh_token": "....hLA", 
      "id_token": ".....B1LGce02PMQHig"
    }
    

    您可以使用它进行测试。在您的应用中实现 OAuth2 时,您需要按照 OAuth2 协议规则设置重定向。

    【讨论】:

      猜你喜欢
      • 2020-06-07
      • 2019-12-22
      • 1970-01-01
      • 1970-01-01
      • 2017-10-20
      • 2014-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多