首页 > 解决方案 > 从谷歌表格触发云功能(通过谷歌应用脚​​本)

问题描述

我一直在尝试(几乎没有成功)通过来自谷歌表(谷歌应用程序脚本)的 http 请求触发谷歌云功能,但它似乎不起作用。一些重要的事情:

我知道这可以在 google colabs 和 Python 中很容易地完成。以下脚本将让我组织中不在GCP 项目中的用户触发云功能:

import requests
import google.auth
from google.auth.transport.requests import Request
from google.colab import auth


credentials, project_id = google.auth.default()
request = Request()
credentials.refresh(request=request)

GCF_URL = ''https://project_location-project_id.cloudfunctions.net/name-of-your-funciton'' 
resp = requests.get(GCF_URL, headers={'Authorization': f'Bearer {credentials.id_token}'})

这将对我组织内的任何用户起作用并触发云功能,但不适用于我的个人电子邮件。

现在,我想在谷歌应用程序脚本中复制这种行为,以便有权访问该工作表的最终用户只要是我组织的成员就可以触发云功能。

我尝试了一些我在网上看到的东西,例如这个例子:

function callExternalUrl() {

    var url = 'https://project_location-project_id.cloudfunctions.net/name-of-your-funciton';

    var oauthToken = ScriptApp.getOAuthToken(); // get the user who's logged into Google Sheet's OAuth token

    const data = {
        oauthToken, // 1. add the oauth token to the payload
        activeUser: param.user // 2. this here is important as it adds the userinfo.email scope to the token
        // any other data you need to send to the Cloud Function can be added here
    };

    var options = {
        'method' : 'get', // or post, depending on how you set up your Cloud Function
        'contentType': 'application/json',
        // Convert the JavaScript object to a JSON string.
        'payload' : JSON.stringify(data)
      };

    const response =  UrlFetchApp.fetch(url, options); 

    Logger.log('Response Code: ' + response.getResponseCode());

}

这会产生 403 错误,但如果我将其更改为以正确格式提供 OAuth,如下所示:

function callExternalUrl() {

    var url = 'https://project_location-project_id.cloudfunctions.net/name-of-your-funciton';

    var oauthToken = ScriptApp.getOAuthToken(); // get the user who's logged into Google Sheet's OAuth token


    var response = UrlFetchApp.fetch(url, {
    headers: {
      Authorization: 'Bearer ' + oauthToken
    }
  });
    // const response =  UrlFetchApp.fetch(url, options); 

    Logger.log('Response Code: ' + response.getResponseCode());

}

我得到一个 401(即授权失败)。现在,似乎我只需要从用户那里获得正确的身份验证才能发送此请求以使其正常工作。我已经看到了这个 github repo,它专注于从谷歌应用程序脚本(https://github.com/gsuitedevs/apps-script-oauth2)获取 OAuth2,但我似乎也无法让它工作,它必须以某种我不知道的方式适应云。

我读过了

通过 Google Apps 脚本安全地调用 Google Cloud 函数

这非常相似,但似乎没有找到问题的根源,关于如何使这个过程成为可能的任何输入?

标签: pythongoogle-apps-scriptgoogle-sheetsgoogle-cloud-functionsgoogle-oauth

解决方案


推荐阅读