首页 > 解决方案 > 谷歌云功能+日历API

问题描述

我正在尝试使用谷歌云函数来处理谷歌日历 API 的授权。但是我在用代码交换令牌时遇到了麻烦。我编写了两个函数,一个生成一个使用代码引导用户登录的身份验证 url,第二个是应该将代码交换为令牌并将用户重定向到页面的函数。第二个函数只是超时并且不返回任何内容。

// The first cloud function
const { google } = require('googleapis');
const credentials = require('./credentials.json')

exports.getURL = async (req, res) => {
    const SCOPES = ["https://www.googleapis.com/auth/calendar.readonly"];
    let redirectURL, oAuth2Client, response;

    try {
        redirectURL = await authorize(credentials);
    }
    catch (e) {
        // console.log(e.message);
        response = JSON.stringify({
            statusCode: 500,
            headers: {
              'Access-Control-Allow-Origin': '*',
              'Access-Control-Allow-Credentials': 'true',
            },
            body: JSON.stringify({
              error: e.message,
            }),
        })
        return res.send(response);
    } 
    
    console.log(redirectURL);
    response = {
      statusCode: 200,
      headers: {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Credentials': 'true',
      'Cache-Control': 'no-cache',
      'Content-Type': 'text/html',
      },
      body: redirectURL,
  }
    return res.send(response);

    function authorize(credentials) {
        // const { CLIENT_SECRET, CLIENT_ID, REDIRECT_URIS } = process.env
        const {client_secret, client_id, redirect_uris} = credentials.installed
        oAuth2Client = new google.auth.OAuth2(
          client_id,
          client_secret,
          redirect_uris[0]
        );
        return getAccessToken(oAuth2Client);
    }
    
    function getAccessToken(oAuth2Client) {
        const authUrl = oAuth2Client.generateAuthUrl({
          access_type: "offline",
          scope: SCOPES,
        });
      
        // returns link that user clicks to authorize app
        return authUrl;
    }
}

第一个函数的输出是这样的:

{
    "statusCode": 200,
    "headers": {
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Credentials": "true",
        "Cache-Control": "no-cache",
        "Content-Type": "text/html"
    },
    "body": "https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcalendar.readonly&response_type=code&client_id=92706390722-rl3h6c2cmqqi15m0ou58cva56hp2vo0c.apps.googleusercontent.com&redirect_uri=https%3A%2F%2Fus-central1-learning-node-291903.cloudfunctions.net%2FgetCalEvents"
}

我不确定发生了什么,但控制台日志语句不会输出任何有用的东西。关于我可能在哪里遇到问题的任何提示?

// 2nd function that exchanges code for token
exports.getCalEvents = async (req, res) => {
  // wait for an event 
  // request comes in with code parameter and query string from 'GET' request 
  let params = req.query;
  const code = params.code;
  let token, response;

  try {
    token = await getAccessToken(code);
    console.log('token', token);
  } catch (err) {
    response = JSON.stringify({
        statusCode: 500,
      })
    return response;
  }

  async function getAccessToken(code) {
    console.log(code);
    const {client_secret, client_id, redirect_uris} = credentials.installed;
    oAuth2Client = new google.auth.OAuth2(
        client_id,
        client_secret,
        redirect_uris[2]
    );
    try {
      let accessToken = await oAuth2Client.getToken(code);
      console.log('access token', accessToken);
      return accessToken;
    } catch (e) {
      throw e;
    }
  }
  //return access token
  response = JSON.stringify({
    statusCode: 302,
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Credentials': 'true',
      'Cache-Control': 'no-cache',
    },
    body: {'token': token},
  });

  console.log(response);

  return res.send(response);
}

标签: javascriptnode.jsgoogle-cloud-functionsgoogle-calendar-api

解决方案


推荐阅读