【问题标题】:get gmail contacts Google Contacts API with javascript使用 javascript 获取 gmail 联系人 Google Contacts API
【发布时间】:2014-03-02 06:59:03
【问题描述】:

它总是说您请求的页面无效。 我如何使用 google 联系人 api 使用 javascript 获取联系人 我有有效的范围和客户 ID

google.load('gdata', '2.x');
    debugger
    google.setOnLoadCallback(function () {
        if (window.location.hash == "") {
            if (!checkLogin()) {
                logMeIn();
            } else {
                var feedUrl = "https://www.google.com/m8/feeds/contacts/default/full";
                query = new google.gdata.contacts.ContactQuery(feedUrl);
                query.setMaxResults(5000);
                myService = new google.gdata.contacts.ContactsService('exampleCo-exampleApp-1.0');
                myService.getContactFeed(query, function (result) {
                    document.cookie = "g314-scope-0=";
                    window.opener.parseGmailContacts(result.feed.entry);
                    close();
                }, function (e) {
                    alert(e.cause ? e.cause.statusText : e.message);
                });
            }
        }
    });
    function logMeIn() {
        scope = "https://www.google.com/m8/feeds";
        var token = google.accounts.user.login(scope);
    }
    function logMeOut() {
        google.accounts.user.logout();
    }
    function checkLogin() {
        scope = "https://www.google.com/m8/feeds/";
        var token = google.accounts.user.checkLogin(scope);
        return token;
    }

我觉得有问题

  var token = google.accounts.user.checkLogin(scope);
            return token;

token retuns ""(这里是空值),如何获取token的值来获取联系人,请帮忙

【问题讨论】:

  • 我认为 var myService = new google.gdata.contacts.ContactsService('exampleCo-exampleApp-1.0'); 有问题这个

标签: javascript google-contacts-api


【解决方案1】:

我遇到了同样的问题,我通过首先检索访问令牌来解决它,然后直接调用 API。这是因为 javascript api (gapi) 不支持检索 google 联系人。

由于很麻烦,我在这里写了一篇关于它的博文:https://labs.magnet.me/nerds/2015/05/11/importing-google-contacts-with-javascript.html

基本上我就是这样解决的:

<!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>

【讨论】:

  • 这适用于本地 HTML 文件,但是当我在服务器的项目中使用它时,我得到CORS header ‘Access-Control-Allow-Origin’ does not match ‘*’。有什么想法吗?
  • clientId 和 apiKey 在源代码 javascript 中不安全?
【解决方案2】:

尝试使用组件我的朋友。生活会变得更轻松、更美好。

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

【讨论】:

    【解决方案3】:

    要使用 Google plus 获取联系人列表,请使用:-

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

    在 HTML 正文中:-

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

    输出将包含一个包含电话号码的联系人字段。

    确保使用正确的重定向 uri 从谷歌开发者控制台获取客户端 ID。

    【讨论】:

      【解决方案4】:

      每次单击按钮时弹出窗口闪烁都有轻微问题。将下面的 sn-p 添加到 Wouters 解决方案将停止弹出窗口闪烁。

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

      【讨论】:

        【解决方案5】:
            <!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>
        

        【讨论】:

        • 在 Stack Overflow 上添加解释为什么您的解决方案应该有效是一种很好的做法。更多信息请阅读How To Answer
        猜你喜欢
        • 2012-08-24
        • 2011-09-30
        • 1970-01-01
        • 2014-08-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-18
        • 1970-01-01
        相关资源
        最近更新 更多