get gmail contacts Google Contacts API with javascript

做~自己de王妃 提交于 2019-11-30 16:21:05

I ran into the same problem, I solved it by first retrieving an access token, and then call the API directly. This is because the javascript api (gapi) does not support retrieving google contacts.

Since it was quite the hassle, I wrote a blogpost about it here: https://labs.magnet.me/nerds/2015/05/11/importing-google-contacts-with-javascript.html

Basically this is how I solved it:

<!DOCTYPE html>
<html>
  <head>
    <meta charset='utf-8' />
    <script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
  </head>
  <body>
    <script type="text/javascript">
          var clientId = 'your Client ID';
          var apiKey = 'Your API Code';
          var scopes = 'https://www.googleapis.com/auth/contacts.readonly';

          $(document).on("click",".googleContactsButton", function(){
            gapi.client.setApiKey(apiKey);
            window.setTimeout(authorize);
          });

          function authorize() {
            gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthorization);
          }

          function handleAuthorization(authorizationResult) {
            if (authorizationResult && !authorizationResult.error) {
              $.get("https://www.google.com/m8/feeds/contacts/default/thin?alt=json&access_token=" + authorizationResult.access_token + "&max-results=500&v=3.0",
                function(response){
                  //process the response here
                  console.log(response);
                });
            }
          }
        </script>
        <script src="https://apis.google.com/js/client.js"></script>
        <button class="googleContactsButton">Get my contacts</button>
  </body>
</html>

Try using components my friend. Life's gonna be easier and prettier.

http://googlewebcomponents.github.io/google-contacts/components/google-contacts/

For fetching list of contacts using Google plus use this :-

<script src="https://apis.google.com/js/client.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
  function auth() {
    var config = {
      'client_id': 'OAUTH_CLIENT_ID',
      'scope': 'https://www.google.com/m8/feeds'
    };
    gapi.auth.authorize(config, function() {
      fetch(gapi.auth.getToken());
    });
  }

  function fetch(token) {
    $.ajax({
    url: "https://www.google.com/m8/feeds/contacts/default/full?access_token=" + token.access_token + "&alt=json",
    dataType: "jsonp",
    success:function(data) {
              console.log(JSON.stringify(data));
    }
});
}

In the HTML Body :-

<button onclick="auth();">GET CONTACTS FEED</button>

The output will have as a field with the contact containing the phone number.

Make sure to get the client id from google developer console with proper redirect uri.

I had slight issue with popup flashing every time the button is clicked. Adding the snippet below to Wouters solution will stop the popup window from flashing.

function authorize(){
    if($scope.authorizationResult){
      handleAuthorization($scope.authorizationResult);
    }else{
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate:false}, handleAuthorization);
       } 
    }
    <!DOCTYPE html>
<html>
    <head>
        <meta charset='utf-8' />
        <script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
    </head>
    <body>
        <script type="text/javascript">
        // Developed By: Garun Mishra.
            var clientId = 'Your Client Id';
            var apiKey = 'Your Api Key';
            var scopes = 'https://www.googleapis.com/auth/contacts.readonly';

            $(document).on("click", ".getGmailContact", function () {
                gapi.client.setApiKey(apiKey);
                window.setTimeout(authorize);
            });

            function authorize() {
                gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthorization);
            }

            function handleAuthorization(authorizationResult) {
                if (authorizationResult && !authorizationResult.error) {
                    $.get("https://www.google.com/m8/feeds/contacts/default/thin?alt=json&access_token=" + authorizationResult.access_token + "&max-results=500&v=3.0",
                            function (response) {
                                //process the response here
                                //console.log(response);
                                var entries = response.feed.entry;
                                var contacts = [];
                                for (var i = 0; i < entries.length; i++) {
                                    var contactEntry = entries[i];
                                    var contact = [];

                                    //console.log(contactEntry);
                                    // Get Full Name.
                                    if (typeof (contactEntry.gd$name) != "undefined") {
                                        if (typeof (contactEntry.gd$name.gd$fullName) != "undefined") {
                                            if (typeof (contactEntry.gd$name.gd$fullName.$t) != "undefined") {
                                                contact['name'] = contactEntry.gd$name.gd$fullName.$t;
                                            }
                                        }
                                    }

                                    // Get Phone Number
                                    if (typeof (contactEntry['gd$phoneNumber']) != "undefined") {
                                        var phoneNumber = contactEntry['gd$phoneNumber'];
                                        for (var j = 0; j < phoneNumber.length; j++) {
                                            if (typeof (phoneNumber[j]['$t']) != "undefined") {
                                                var phone = phoneNumber[j]['$t'];
                                                contact['phone'] = phone;
                                            }
                                        }
                                    }

                                    // get Email Address
                                    if (typeof (contactEntry['gd$email']) != "undefined") {
                                        var emailAddresses = contactEntry['gd$email'];
                                        for (var j = 0; j < emailAddresses.length; j++) {
                                            if (typeof (emailAddresses[j]['address']) != "undefined") {
                                                var emailAddress = emailAddresses[j]['address'];
                                                contact['email'] = emailAddress;
                                            }
                                        }
                                    }
                                    contacts.push(contact);


                                }
                                // To Print All contacts
                                console.log(contacts);

                                // You can fetch other information as per your requirement uncomment the given line and read the data.
                                //console.log(entries);
                            });

                }
            }
        </script>
        <script src="https://apis.google.com/js/client.js"></script>
        <button class="getGmailContact">Get My Gmail Contacts</button>
    </body>
</html>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!