简体   繁体   English

如何使用 People API 和 Nodejs 创建 google 联系人

[英]How to create google contacts using People API and Nodejs

Im searching for how to create google contacts using the People API , i have followed the guide here:我正在寻找如何使用People API创建谷歌联系人,我已按照此处的指南进行操作:

https://developers.google.com/people/quickstart/nodejs https://developers.google.com/people/quickstart/nodejs

My current code:我当前的代码:

const fs = require('fs');
const readline = require('readline');
const {google} = require('googleapis');

// If modifying these scopes, delete token.json.
const SCOPES = ['https://www.googleapis.com/auth/contacts'];
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
const TOKEN_PATH = 'token.json';

// Load client secrets from a local file.
fs.readFile('credentials.json', (err, content) => {
  if (err) return console.log('Error loading client secret file:', err);
  // Authorize a client with credentials, then call the Google Tasks API.
  authorize(JSON.parse(content), listConnectionNames);
});

/**
 * Create an OAuth2 client with the given credentials, and then execute the
 * given callback function.
 * @param {Object} credentials The authorization client credentials.
 * @param {function} callback The callback to call with the authorized client.
 */
function authorize(credentials, callback) {
  const {client_secret, client_id, redirect_uris} = credentials.installed;
  const oAuth2Client = new google.auth.OAuth2(
      client_id, client_secret, redirect_uris[0]);

  // Check if we have previously stored a token.
  fs.readFile(TOKEN_PATH, (err, token) => {
    if (err) return getNewToken(oAuth2Client, callback);
    oAuth2Client.setCredentials(JSON.parse(token));
    callback(oAuth2Client);
  });
}

/**
 * Get and store new token after prompting for user authorization, and then
 * execute the given callback with the authorized OAuth2 client.
 * @param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
 * @param {getEventsCallback} callback The callback for the authorized client.
 */
function getNewToken(oAuth2Client, callback) {
  const authUrl = oAuth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: SCOPES,
  });
  console.log('Authorize this app by visiting this url:', authUrl);
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
  });
  rl.question('Enter the code from that page here: ', (code) => {
    rl.close();
    oAuth2Client.getToken(code, (err, token) => {
      if (err) return console.error('Error retrieving access token', err);
      oAuth2Client.setCredentials(token);
      // Store the token to disk for later program executions
      fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
        if (err) return console.error(err);
        console.log('Token stored to', TOKEN_PATH);
      });
      callback(oAuth2Client);
    });
  });
}

/**
 * Print the display name if available for 10 connections.
 *
 * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
 */
function listConnectionNames(auth) {
  const service = google.people({version: 'v1', auth});
  service.people.connections.list({
    resourceName: 'people/me',
    pageSize: 2,
    personFields: 'names,emailAddresses',
  }, (err, res) => {
    if (err) return console.error('The API returned an error: ' + err);
    const connections = res.data.connections;
    if (connections) {
      console.log('Connections:');
      connections.forEach((person) => {
        if (person.names && person.names.length > 0) {
          console.log(person.names[0].displayName);
        } else {
          console.log('No display name found for connection.');
        }
      });
    } else {
      console.log('No connections found.');
    }
  });

  service.people.createContact({
    requestBody: {
      emailAddresses: [{value: 'test@test.com'}],
      names: [
        {
          displayName: 'A',
          familyName: 'B',
          givenName: 'C',
        },
      ],
    },
  });
  //console.log('\n\nCreated Contact:', newContact);

}

I succeed in reading my contacts and in creating the OAuth authentication key.我成功地reading了我的联系人并创建了 OAuth 身份验证密钥。

https://developers.google.com/people/api/rest/v1/people/createContact (Sadly this link doesn't have a full working example like on the link to read contacts) https://developers.google.com/people/api/rest/v1/people/createContact (遗憾的是,此链接没有完整的工作示例,例如阅读联系人的链接)

I tried to create a contact adding this code:我试图创建一个添加此代码的联系人:

  service.people.createContact({
    requestBody: {
      emailAddresses: [{value: 'test@test.com'}],
      names: [
        {
          displayName: 'A',
          familyName: 'B',
          givenName: 'C',
        },
      ],
    },
  });

But, when i add the code, it return an error:但是,当我添加代码时,它返回一个错误:

(node:8392) UnhandledPromiseRejectionWarning: Error: Insufficient Permission
    at Gaxios.<anonymous> (C:\Users\Desktop\Nova pasta\node_modules\gaxios\build\src\gaxios.js:73:27)
    at Generator.next (<anonymous>)
    at fulfilled (C:\Users\Desktop\Nova pasta\node_modules\gaxios\build\src\gaxios.js:16:58)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:8392) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:8392) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Error: Insufficient Permission错误:权限不足

Means that you are trying to do something that you dont have permission to do.表示您正在尝试做一些您无权做的事情。

The create method requires that you have authorized the user with the following scope创建方法需要你已经授权用户有如下scope

https://www.googleapis.com/auth/contacts https://www.googleapis.com/auth/contacts

I suspect that you have have changed the scope in your code and not reauthorized your user.我怀疑您已经更改了代码中的 scope 并且没有重新授权您的用户。

  • delete token.json,删除令牌.json,
  • Have the user go to permissions find your app and remove its access.让用户 go有权找到您的应用并删除其访问权限。 then try to run your application again.然后尝试再次运行您的应用程序。

I will answer your questions in the same order that you formulate them:我将按照您提出问题的相同顺序回答您的问题:

  1. In the file credentials.json (from first link), it contains a clientID is this clientID that will be used on 'clientId':' ?在文件credentials.json (来自第一个链接)中,它包含一个clientID ,这个clientID将用于'clientId':'

Yes, the clientId is one part of the OAuth 2.0 protocol.是的, clientId是 OAuth 2.0 协议的一部分。

  1. Does scope value changes or will be the same ever? scope值会改变还是会一直保持不变?

The script scope should only change when you need it.脚本 scope 只应在您需要时更改。 Ideally, you would use the most restrictive scope unless you need a less limited one.理想情况下,除非您需要限制较少的 scope,否则您将使用最严格的 scope。 Here there is a list of valid People API scopes. 这里有一个有效的 People API 范围列表。

  1. Whats wrong with the error ReferenceError: gapi is not defined错误ReferenceError: gapi is not defined

This error warns you that the gapi variable hasn't been declared.此错误警告您尚未声明gapi变量。 The original code shared by @ChavdaMadhav is not a complete example. @ChavdaMadhav 分享的原始代码并不是一个完整的例子。 You would need to fill in the blanks to make it run, and that includes the definition of the gapi variable.您需要填写空白以使其运行,其中包括gapi变量的定义。 Please, don't hesitate to write back if you have doubts on this answer or the other ones.如果您对此答案或其他答案有疑问,请不要犹豫回信。

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

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