繁体   English   中英

如何使用JavaScript获取Gmail联系人?

[英]How do I get Gmail contacts using JavaScript?

为了使用JavaScript获得gmail联系人,我应该进行什么Ajax调用? 我已经拥有用户OAuth令牌,因为该用户使用Google签署了我的网站。

如果您通过JavaScript使用OAuth2,则可以使用Google Contacts API,但在获取访问令牌( https://www.google.com/m8/feeds时,需要通过向Google发送正确的权限范围来获得授权https://www.google.com/m8/feeds 参考

您已经知道如何获取访问令牌,就像使用正确的查询调用API一样简单。 要为您的用户获取所有联系人,就像向API异步请求所需信息一样简单。 例如,在{userEmail}是用户的电子邮件,而{accessToken}是您的访问令牌的情况下,只需为以下URI创建GET地址:

https://www.google.com/m8/feeds/contacts/{userEmail}/full?access_token={accessToken}&alt=json

您可以在此处发送查询的类型及其参数的列表:

要使用OAuth获取用户的联系人,首先需要在请求中指定联系人的范围。 如果您使用的是ChromeExAuth,则应编写:

var oauth = ChromeExOAuth.initBackgroundPage({
  'request_url' : 'https://www.google.com/accounts/OAuthGetRequestToken',
  'authorize_url' : 'https://www.google.com/accounts/OAuthAuthorizeToken',
  'access_url' : 'https://www.google.com/accounts/OAuthGetAccessToken',
  'consumer_key' : 'anonymous',
  'consumer_secret' : 'anonymous',
  'scope' : 'https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile https://www.google.com/m8/feeds/',
  'app_name' : 'MyApp'
});

上面的scope参数列出了3个范围:用户的电子邮件,个人资料和联系人( google.com/m8/feeds/contacts

为了在用户授权令牌后获得他们的联系人,您可以发送如下请求:

var url = "http://www.google.com/m8/feeds/contacts/default/full";
oauth.sendSignedRequest(url, onContacts, {
  'parameters' : {
    'alt' : 'json',
    'max-results' : 99999
  }
});

请求的回调可能如下所示:

function onContacts(text, xhr) {
  contacts = [];
  var data = JSON.parse(text);
  for (var i = 0, entry; entry = data.feed.entry[i]; i++) {
    var contact = {
      'name' : entry['title']['$t'],
      'id' : entry['id']['$t'],
      'emails' : []
    };

    if (entry['gd$email']) {
      var emails = entry['gd$email'];
      for (var j = 0, email; email = emails[j]; j++) {
        contact['emails'].push(email['address']);
      }
    }

    if (!contact['name']) {
      contact['name'] = contact['emails'][0] || "<Unknown>";
    }
    contacts.push(contact);
  }
};

要查看联系人数组,您可以仅在控制台上进行打印:

console.log(contacts);

您可以在此处签出Google OAuth教程

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM