本頁說明如何使用 subscriptions.update()
方法續訂 Google Workspace 方案。您可以使用這個方法更新訂閱項目的到期時間,包括將訂閱項目續訂至最長到期時間,或是更新要接收目標資源相關事件的事件類型清單。
Apps Script
- Google Workspace 訂閱方案。如要建立訂閱項目,請參閱「建立訂閱項目」一文。
需要使用一或多個支援訂閱項目所有事件類型的範圍進行使用者驗證。
- Apps Script 專案:
- 使用 Google Cloud 專案,而非 Apps Script 自動建立的預設專案。
- 針對您新增的所有範圍,以設定 OAuth 同意畫面,您也必須將範圍新增至 Apps Script 專案的
appsscript.json
檔案。舉例來說,如果您指定chat.messages
範圍,請新增下列項目: - 啟用
Google Workspace Events
進階服務。
"oauthScopes": [ "https://www.googleapis.com/auth/chat.messages" ]
Python
- Python 3.6 以上版本
- pip 套件管理工具
- 最新版 Python 適用的 Google 用戶端程式庫。如要安裝或更新這些工具,請在指令列介面中執行下列指令:
pip3 install --upgrade google-api-python-client google-auth-oauthlib
- Google Workspace 訂閱方案。如要建立訂閱項目,請參閱「建立訂閱項目」一文。
需要使用一或多個支援訂閱項目所有事件類型的範圍進行使用者驗證。
續訂 Google Workspace 方案
在本節中,您將使用 Google Workspace Events API 的 subscriptions.update()
方法,將訂閱項目續訂至最長到期時間。如要指定最長到期時間,請將 Subscription
資源的 ttl
欄位更新為 0
。
最長到期時間取決於事件酬載中包含的資源資料。如要進一步瞭解到期時間,請參閱「Google Workspace 事件的事件資料」。
如要續訂 Google Workspace 方案,請按照下列步驟操作:
Apps Script
在 Apps Script 專案中,建立名為
updateSubscription
的新指令碼檔案,並新增下列程式碼:function updateSubscription() { // The name of the subscription to update. const name = 'subscriptions/SUBSCRIPTION_ID'; // Call the Workspace Events API using the advanced service. const response = WorkspaceEvents.Subscriptions.patch({ ttl: '0s', }, name); console.log(response); }
更改下列內容:
如要更新 Google Workspace 訂閱方案,請在 Apps Script 專案中執行
updateSubscription
函式。
Python
在工作目錄中,建立名為
update_subscription.py
的檔案,並加入下列程式碼:"""Update subscription.""" from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build # Specify required scopes. SCOPES = [SCOPES] # Authenticate with Google Workspace and get user authentication. flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES) CREDENTIALS = flow.run_local_server() # Call the Workspace Events API using the service endpoint. service = build( 'workspaceevents', 'v1', credentials=CREDENTIALS, ) BODY = { 'ttl': {'seconds': 0}, } NAME = 'subscriptions/SUBSCRIPTION_ID' response = ( service.subscriptions() .patch(name=NAME, updateMask='ttl', body=BODY) .execute() ) print(response)
更改下列內容:
SCOPES
:支援訂閱項目中各事件類型的 OAuth 範圍。格式為字串陣列。如要列出多個範圍,請以半形逗號分隔。 例如:'https://www.googleapis.com/auth/chat.spaces.readonly', 'https://www.googleapis.com/auth/chat.memberships.readonly'
。SUBSCRIPTION_ID
:訂閱 ID。如要取得 ID,可以使用下列任一方法:
請確認工作目錄中已儲存 OAuth 用戶端 ID 憑證,且檔案名為
credentials.json
。程式碼範例會使用這個 JSON 檔案向 Google Workspace 進行驗證,並取得使用者憑證。如需操作說明,請參閱「建立 OAuth 用戶端 ID 憑證」。如要更新 Google Workspace 訂閱方案,請在終端機中執行下列指令:
python3 update_subscription.py
Subscription
資源的執行個體。如要取得更新後 Subscription
資源的詳細資料,請使用 operations.get()
方法,並指定從 subscriptions.update()
要求傳回的 Operation
資源。否則,如果您指定先前訂閱方案版本的 Operation
資源,回應會是空白。