Post

Google Apps Script x Google APIs 快速串接整合方式

以 Google Apps Script x Firebase App Distribution API 串接為例

Google Apps Script x Google APIs 快速串接整合方式

ℹ️ℹ️ℹ️ Click here to view the English version of this article, translated by OpenAI.


Google Apps Script x Google APIs 快速串接整合方式

以 Google Apps Script x Firebase App Distribution API 串接為例

背景

之前寫了之前寫了好幾篇關於使用 Google Apps Script 的文章,其中「 使用 Google Apps Script 實現每日數據報表 RPA 自動化 」、「 簡單 3 步驟 — 打造免費 GA4 自動數據通知機器人 」介紹了如何使用 Google Apps Script 串接 Google Analytics 和 Google Sheet, Web App, Slack, Telegram… 快速建置可視化數據中台及通知服務;另外上個月發的文章「 使用 Google Apps Script Web App 表單串接 Github Action CI/CD 工作 」則是直接使用 Google Apps Script Web App 串接 Github API 作為 CI/CD GUI 表單服務;以上要馬是直接使用 Google Apps Script 內建的服務進行串接或是直接串接外部服務 (Slack, Github…) 都沒碰到需要串接 Google APIs 的場景。

這次在優化 CI/CD GUI 表單時希望打包內測版後能在 Web App 上直接顯示 Firebase Distribution 下載連結,這塊就只能串接 Google APIs 才能達成。

Google Apps Script x Firebase App Distribution API v1

如上圖,與以往串接 Google Analytics 有內建服務「AnalyticsData」不同,Firebase App Distribution 並沒有提供內建串接服務,所以要用進階方式進行串接。

本來以為要自行使用 Service Account 完成 Access Token 產生、交換(有點麻煩,可參考我之前的 評價機器人開源專案 ), 但其實不用這麼麻煩。

Google Apps Script x Google APIs 進階服務串接

串接設定

參考 官方文件描述 ,我們需要照以下步驟進行進階設定:

  1. 您必須在指令碼專案中 啟用進階服務
  2. 您必須確認在指令碼使用的 Cloud Platform (GCP) 專案 中,已啟用對應進階服務的 API。
  3. 如果指令碼專案使用的是 2019 年 4 月 8 日當天或之後建立的 預設 GCP 專案 ,您啟用進階服務並儲存指令碼專案後,API 就會自動啟用。如果您尚未同意,系統可能也會要求您同意《 Google Cloud 》和《 Google API 》服務條款。
  4. 如果指令碼專案使用 標準 GCP 專案 或較舊的預設 GCP 專案,您必須手動在 GCP 專案中 啟用進階服務的對應 API 。您必須具備 GCP 專案的編輯權限,才能進行這項變更。

1. 專案設定 —設定關聯的 Google Cloud Platform (GCP) 專案

Google Apps Script x Google APIs 進階服務串接會需要你建立 GCP 專案並關聯到 Google Apps Script,Google APIs 使用權限是依照 GCP 設定。

因此你需要建立一個 GCP 專案(同 Firebase GCP 專案亦可),記下資訊主頁的「 專案編號 」並確定這個 GCP 專案有啟用你想使用的 Google APIs 及當前登入帳號或欲使用的帳號是有該 GCP 專案、Google APIs 權限。

本文以「 Firebase App Distribution API 」為例。

專案編號 輸入到 Goolge Apps Script 專案設定下方的 Google Cloud Platform 專案編號中,當前登入帳號有該 GCP 專案權限就能自動綁定設定成功。

2. 專案設定 — 啟用 在編輯器中顯示「appsscript.json」資訊清單檔案

啟用後回到編輯器,檔案列表就會出現「 appsscript.json 」設定檔:

確保 oauthScopes 中包含以下兩個描述設定:

1
2
3
4
  "oauthScopes": [
    "https://www.googleapis.com/auth/script.external_request",
    "https://www.googleapis.com/auth/cloud-platform"
  ]

如果沒有請手動貼上儲存。

3.撰寫串接程式碼

設定好 GCP 專案之後我們就能開始撰寫串接程式碼,直接參考想串接的 Google APIs 官方文件, Firebase App Distribution API v1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
const project = "projects/[Firebase Project ID]/apps/[Firebase APP ID]"; // 請換成你的 Project ID & App ID

function debug() {
  const releases = firebaseDistribution("");

  releases.forEach(function(release) {
    // Release Object: https://firebase.google.com/docs/reference/app-distribution/rest/v1/projects.apps.releases?hl=zh-tw#Release
    Logger.log(`${release.name} Download URL: ${release.testingUri}`);
  });
}

function firebaseDistribution(releaseNote) {
  const url = "https://firebaseappdistribution.googleapis.com/v1/"+project+"/releases?filter=releaseNotes.text%3D*"+releaseNote+"*";
  // Filter: https://firebase.google.com/docs/reference/app-distribution/rest/v1/projects.apps.releases/list?hl=zh-tw
  const headers = {
    "Content-Type": "application/json; charset=UTF-8",
    "Authorization": "Bearer " + ScriptApp.getOAuthToken(), // 直接使用當前帳號換取權杖
  };
  
  const options = {
    "method": "get",
    "headers": headers
  };
  const data = UrlFetchApp.fetch(url, options);
  const result = JSON.parse(data.getContentText()).releases;
  
  if (result == undefined) {
    return [];
  }

  return result;
}

[Firebase Project ID] [Firebase APP ID] 可在 Firebase 專案設定中取得:

貼上程式碼後,第一次執行需要完成權限授權。

  • 點擊「審查權限」
  • 選擇要執行的身份帳戶,通常等於當前 Google Apps Script 帳戶

  • 選擇「進階」展開 -> 點擊「前往 XXX」 這是我們自己寫給自己用的應用程式,不需經過 Google 驗證。
  • 點擊「允許」

以上畫面不一定會出現,沒有可忽略。

允許之後再點「偵錯」或「執行」就能執行程式:

如果出現錯誤:

1
2
3
4
5
6
7
Exception: Request failed for https://firebaseappdistribution.googleapis.com returned code 403. Truncated server response: {
  "error": {
    "code": 403,
    "message": "Request had insufficient authentication scopes.",
    "status": "PERMISSION_DENIED",
    "details":... (use muteHttpExceptions option to examine full response)
...

1
Exception: Specified permissions are not sufficient to call UrlFetchApp.fetch. Required permissions: https://www.googleapis.com/auth/script.external_request

請確認 appsscript.json 的 oauthScopes 中包含以下兩個描述設定(參考步驟 2):

1
2
3
4
"oauthScopes": [
    "https://www.googleapis.com/auth/script.external_request",
    "https://www.googleapis.com/auth/cloud-platform"
  ]

如果出現錯誤:

1
2
3
4
Exception: Request failed for https://firebaseappdistribution.googleapis.com returned code 401. Truncated server response: {
  "error": {
    "code": 401,
    "message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or othe... (use muteHttpExceptions option to examine full response)

代表尚未設定綁定的 GCP 專案 (參考步驟 1. ) 或是該 GCP 專案尚未啟用欲使用的 Google APIs 或是當前帳號無該 GCP / Google APIs 使用權限或無該 Firebase App 權限,請檢查設定。

如果出現錯誤:

1
Exception: Request failed for https://firebaseappdistribution.googleapis.com returned code 404. Truncated server response:

1
2
3
4
5
6
7
Exception: Request failed for https://firebaseappdistribution.googleapis.com returned code 400. Truncated server response: {
  "error": {
    "code": 400,
    "message": "Request contains an invalid argument.",
    "status": "INVALID_ARGUMENT"
  }
}

請確認 Google APIs 請求路徑是否正確。

串接成功🎉🎉🎉

可以看到短短不到 10 行程式碼就能無痛串接 Google APIs,真的非常方;有興趣的朋友可以看一下相較之下, 自己實作 Google APIs 串接時身份驗證權杖交換的程式步驟,非常繁瑣。

下一步:

搭配之前的文章「 使用 Google Apps Script Web App 表單串接 Github Action CI/CD 工作 」串上 CI/CD 工作項目,將 Firebase App Distribution 下載連結也呈現在 Web App 上方便同仁直接在上面下載。

Demo Result

Demo Result

其他 Google APIs 也能以此類推串接。

有任何問題及指教歡迎 與我聯絡


本文首次發表於 Medium ➡️ 前往查看

ZMediumToMarkdownMedium-to-jekyll-starter 提供自動轉換與同步技術。

Improve this page on Github.

Buy me a beer

38 Total Views
Last Statistics Date: 2025-03-23 | 32 Views on Medium.
This post is licensed under CC BY 4.0 by the author.