How do I get Gmail contacts using JavaScript?

2020-07-27 06:02发布

What is the Ajax call that I should make to get gmail contacts using JavaScript? I already have the user OAuth Token which I got because the user signed up to my site using Google.

2条回答
Luminary・发光体
2楼-- · 2020-07-27 06:41

If you're using OAuth2 through JavaScript, you can use the Google Contacts API, but you'll need to get authorisation by sending the correct scope of permissions to Google when getting the access token, which is https://www.google.com/m8/feeds. (reference)

As you already know how to get the access token, it's as simple as calling the API with the correct query. To get all contacts for your user, it's as simple as making an asynchronous request to the API for the required info. For example, where {userEmail} is the user's email and {accessToken} is your access token, simply make a GET address to the following URI:

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

A list of the types of queries you can send and their parameters are available here:

查看更多
成全新的幸福
3楼-- · 2020-07-27 07:02

To get users' contacts using OAuth, first you need to specify the contact's scope in your request. If you're using ChromeExAuth, then you would write:

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'
});

The scope parameter above lists 3 scopes: the user's email, profile, and contacts (google.com/m8/feeds/contacts)

To get their contacts after the user authorizes the token, you would send a request like this:

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

And the callback for the request could look like this:

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);
  }
};

To view the contacts array, you could just print on the console:

console.log(contacts);

You can checkout the Google OAuth tutorial here

查看更多
登录 后发表回答