如何在 Chrome 扩展程序中使用 Google People API 获取我的联系人姓名、电子邮件、电话号码和组织

问题描述

我是 Chrome 扩展程序和 People API 的新手。我正在尝试使用 JavaScript 创建一个扩展程序,以便我可以列出我的联系人。

我收到 401 错误

错误:{代码:401,数据:未定义,消息:“请求缺少所需的身份验证凭证...ogle.com/identity/sign-in/web/devconsole-project。”} 消息:“请求缺少必需的身份验证凭据。需要 OAuth 2 访问令牌、登录 cookie 或其他有效的身份验证凭据。请参阅 https://developers.google.com/identity

获取 https://content-people.googleapis.com/v1/people/me/connections?requestMask.includeField=person.phone_numbers%2Cperson.organizations%2Cperson.email_addresses%2Cperson.names&pageSize=100&key=AIzaSyBAoWON7yo4fJimEFDk3Viony1Q1Q1Q >

manifest.json:

{
"manifest_version": 2,"key":"key..............","oauth2": {
  "client_id": "..........apps.googleusercontent.com","scopes": [
    "profile email","https://www.googleapis.com/auth/contacts","https://www.googleapis.com/auth/contacts.readonly","https://www.googleapis.com/auth/directory.readonly","https://www.googleapis.com/auth/user.addresses.read","https://www.googleapis.com/auth/user.birthday.read","https://www.googleapis.com/auth/user.emails.read","https://www.googleapis.com/auth/user.gender.read","https://www.googleapis.com/auth/user.organization.read","https://www.googleapis.com/auth/user.phonenumbers.read","https://www.googleapis.com/auth/userinfo.email","https://www.googleapis.com/auth/userinfo.profile","https://www.googleapis.com/auth/user.phonenumbers.read"
  ]
},"name": "GmailM","version": "0.1","description":"simple email extension","persistent": false,content_security_policy": "script-src 'self' 
 'unsafe-eval'; object-src 'self'","permissions": 
 ["identity","https://apis.google.com/js/api.js","https://accounts.google.com/*","https://www.googleapis.com/*"],"browser_action":{
  "default_title":"timezone finder"
  
},"background": {
  "scripts": [
      "./background.js"
 ]
 },}

test.js:

var theParent = document.querySelector("#ParentId");

if (theParent) {   
     theParent.addEventListener("click",callApi,false);
}
function callApi(e) {
    if (e.target !== e.currentTarget) {
        var clickedItem = e.target.id;

        if (clickedItem === "contacts") {
            console.log(clickedItem+ " ppl api ");
            authClick();
        }
    }
    e.stopPropagation();
}

function authClick() {
    var CLIENT_ID = '....';
    var ScopES = [
      "https://www.googleapis.com/auth/contacts","https://www.googleapis.com/auth/user.phonenumbers.read"
    ];
    gapi.auth.authorize({ 
        client_id: CLIENT_ID,scope: ScopES,immediate: false 
    },authResult);
    return false;
}

function authResult(_Result) {
    var _Div = document.getElementById('divauthresult');
    if (_Result && !_Result.error) {
        _Div.style.display = 'none';
        loadPeopleApi();
        console.log("yes");
    } else {
        // Auth Error,allowing the user to initiate authorization by
        _Div.innerText = ':( Authtentication Error : ' + _Result.error;
        console.log("no");
    }
}

function loadPeopleApi() { 
    gapi.client.setApiKey("AIzaSyBAoWON7yo4fJimEFDk3VIonx3S1YjyqeQ");         
    gapi.client.load('https://people.googleapis.com/$discovery/rest','v1',showContacts);
}

function showContacts() { 
    var request = gapi.client.people.people.connections.list({
        
        'resourceName': 'people/me','pageSize': 100,'requestMask.includeField': 'person.phone_numbers,person.organizations,person.email_addresses,person.names'
    });

    request.execute(function(resp) {
        var connections = resp.connections;
        console.log("hii");
        console.log(resp);

        if (connections.length > 0) {
            var _Html = "<table><tr><th>Name</th><th>Email</th><th>Company</th><th>Phone</th></tr>";
            var _EmptyCell = "<td> - </td>";

            for (i = 0; i < connections.length; i++) {
                var person = connections[i];
                _Html += "<tr>";

                if (person.names && person.names.length > 0)
                    _Html += "<td>" + person.names[0].displayName + "</td>";
                else
                    _Html += _EmptyCell;

                if (person.emailAddresses && person.emailAddresses.length > 0)
                    _Html += "<td>" + person.emailAddresses[0].value + "</td>";
                else
                    _Html += _EmptyCell;

                if (person.organizations && person.organizations.length > 0)
                    _Html += "<td>" + person.organizations[0].name + "</td>";
                else
                    _Html += _EmptyCell;

                if (person.phoneNumbers && person.phoneNumbers.length > 0)
                    _Html += "<td>" + 
              person.phoneNumbers[0].value + "</td>";
                else
                    _Html += _EmptyCell;

                _Html += "</tr>";
            }
            divtableresult.innerHTML = "Contacts found : 
            <br>" + _Html;
        } else {
            divtableresult.innerHTML = "";
            divauthresult.innerText = "No Contacts 
           found!";
        }
    }); 
}

解决方法

我最近一直在解决这个问题。如何,我是通过执行以下操作来解决的

步骤

  1. 使用 OAuth2 获取访问令牌
  2. 使用访问令牌获取用户信息 GET - https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=${accessToken}
  3. userinfo 对象中获取 google id
  4. 指定您的personFields。你阅读更多关于 personFields here(例如 封面照片、电子邮件地址、性别、语言环境、职业) 确保 您拥有 api 密钥,您可以观看此视频了解如何获取 Google People API 的 api 密钥。 Watch Video
  5. 因此您需要四样东西访问令牌GoogleIdApi KeypersonFields
  6. 终于 GET - https://people.googleapis.com/v1/people/${googleId}?alt=json&personFields=${personFields}&key=${apiKey}&access_token=${accessToken}