通过云函数访问Gmail API [英] Accessing Gmail API through Cloud Functions

查看:33
本文介绍了通过云函数访问Gmail API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个响应Gmail pubsub消息的电子邮件解析器。我目前可以接收和解析pubsub消息并提取History yId,但是在向Gmail API验证我的请求时遇到了问题。以下是我目前掌握的情况:

  //function defined outside the scope of the main function
  //used to create auth client
  function getAuthClient(event, callback) {
    var GoogleAuth = require('google-auth-library');

    var authFactory = new GoogleAuth();

    authFactory.getApplicationDefault(function (err, authClient) {
     if (err) {
       console.log('Unable to get application default credentials.');
       callback(err);
       return;
     }

     // Create the oAuth scopes you need
     if (authClient.createScopedRequired && authClient.createScopedRequired()) {
    console.log('creating scoped client');
      authClient = authClient.createScoped([
          'https://mail.google.com/'
      ]);
    }
   callback(null, authClient);
  });
}

exports.gmailParser = function gmailParser (event, callback) {
 var path = require('path');
 var base64 = require('base-64');

 // Set your service account key file into the environment for the auth lib 
to pick up
 process.env['GOOGLE_APPLICATION_CREDENTIALS'] = path.resolve(__dirname, 
'auth_credentials.json');
 console.log(process.env['GOOGLE_APPLICATION_CREDENTIALS']);


 console.log(__dirname);

 //parse pubsub message
 var pubsubMessage = event.data;
 var baseMessage = pubsubMessage.data;
 var decodedMessage = base64.decode(baseMessage);
 var messageJSON = JSON.parse(decodedMessage);

 // Extract emailAddress and historyId from gmail pubsub message
 var historyId = messageJSON.historyId;
 var email = messageJSON.emailAddress;

 getAuthClient(null, function(err, authClient) {

   //import necessary libraries
   var google = require('googleapis');
   var gmail = google.gmail('v1');

   if(err) {
     callback(err);
   }

  // Construct a params object
  var params = {
    userId: email,
    startHistoryId: historyId
 };


//Attempt to call gmail api. This is where the error occurs.
gmail.users.history.list(params, function(error, response) {
  if (error) {  
    console.log('Encountered error', error);
    callback(error);
  } else {
    console.log('Response', response);
    callback(response);
  }
});
 });
};

代码成功运行,但我收到以下错误:

"Error: Login Required
at Request._callback (/user_code/node_modules/googleapis/node_modules/google-auth-library/lib/transporters.js:85:15)
at Request.self.callback (/user_code/node_modules/googleapis/node_modules/request/request.js:188:22)
at emitTwo (events.js:106:13)
at Request.emit (events.js:191:7)
at Request.<anonymous> (/user_code/node_modules/googleapis/node_modules/request/request.js:1171:10)
at emitOne (events.js:96:13)
at Request.emit (events.js:188:7)
at IncomingMessage.<anonymous> (/user_code/node_modules/googleapis/node_modules/request/request.js:1091:12)
at IncomingMessage.g (events.js:291:16)
at emitNone (events.js:91:20)"   

我尝试将authClient添加到param对象,但返回"Bad Request"错误。我尝试更改了导入顺序,创建了新的凭据,但没有取得任何进展。如果谁有什么建议,我们将不胜感激。

推荐答案

此博客帖子可能会有所帮助。它详细介绍了如何使用NodeJS和Cloud函数获取OAuth令牌。我试过了,它工作得很好。

https://cloud.google.com/blog/products/application-development/adding-custom-intelligence-to-gmail-with-serverless-on-gcp

编码:https://github.com/GoogleCloudPlatform/cloud-functions-gmail-nodejs

以下代码片段请求OAuth 2.0授权码

exports.oauth2init = (req, res) => {
  // Define OAuth2 scopes
  const scopes = [
    'https://www.googleapis.com/auth/gmail.modify'
  ];

  // Generate + redirect to OAuth2 consent form URL
  const authUrl = oauth.client.generateAuthUrl({
    access_type: 'offline',
    scope: scopes,
    prompt: 'consent' // Required in order to receive a refresh token every time
  });
  return res.redirect(authUrl);
};

下面的代码片段从OAuth授权码获取访问令牌

exports.oauth2callback = (req, res) => {
  // Get authorization code from request
  const code = req.query.code;

  // OAuth2: Exchange authorization code for access token
  return new Promise((resolve, reject) => {
    oauth.client.getToken(code, (err, token) =>
      (err ? reject(err) : resolve(token))
    );
  })

这篇关于通过云函数访问Gmail API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆