簡體   English   中英

使用服務帳戶為推送通知創建 Google Drive 頻道

[英]Create Google Drive channel for PUSH notification using Service Account

我正在嘗試創建一個頻道,以便在對 Google 電子表格進行編輯時接收推送通知。 該代碼將在 App Engine 標准 Java8 項目上執行。

因為一個頻道最多可以持續 24 小時,所以我正在創建一個每天更新頻道的 cron。

這是我的配置:

  • 我創建了一個服務帳戶: xxxx@yyyy.iam.gserviceaccount.com
  • 我驗證了域: yyyy.appspot.com (在Webmaster Tools
  • 我將域添加到雲控制台(部分API & Services -> Domain Verification
  • 我創建了一個處理推送通知的端點: https://yyyy.appspot.com/api/drive/push : https://yyyy.appspot.com/api/drive/push
  • sheetId 是: foo_bar (由電子表格瀏覽器 url 本身復制,如https://docs.google.com/spreadsheets/d/foo_bar/edit
  • 服務帳戶在工作表上是Can Edit

使用 Java 庫google-api-services-drive:v3-rev102-1.23.0我創建了這段代碼

public static void main(String[] args) throws IOException {
    String spreadsheetId = "foo_bar";
    InputStream json = GoogleDriveApi.class.getClassLoader().getResourceAsStream("bar.json");

    GoogleCredential credential = GoogleCredential.fromStream(json, new NetHttpTransport(), new JacksonFactory());
    if (credential.createScopedRequired()) {
        credential = credential.createScoped(Collections.singleton("https://www.googleapis.com/auth/drive.appdata"));
    }

    Drive service = new Drive.Builder(new NetHttpTransport(), new JacksonFactory(), credential).build();

    Channel channel = new Channel();
    channel.setAddress("https://example.com/api/drive/push");
    channel.setType("web_hook");
    channel.setId(UUID.randomUUID().toString());

    Watch action = service.files().watch(spreadsheetId, channel);
    System.out.println(action.execute().toPrettyString());
}

當我執行此代碼時,出現此錯誤:

com.google.api.client.googleapis.json.GoogleJsonResponseException: 404 Not Found
{
  "code" : 404,
  "errors" : [ {
    "domain" : "global",
    "location" : "fileId",
    "locationType" : "parameter",
    "message" : "File not found: foo_bar.",
    "reason" : "notFound"
  } ],
  "message" : "File not found: foo_bar."
}

從我引用的文檔中

每個通知通道都與特定用戶和特定資源(或資源集)相關聯。 除非當前用戶或服務帳戶擁有或有權訪問此資源,否則監視請求不會成功。

在我的情況下,服務帳戶不擁有資源(電子表格),但確實有權限( Can Edit權限,不僅Can View

可以使用服務帳戶在 Google 雲端硬盤上創建頻道嗎?

file.watch API 需要https://www.googleapis.com/auth/drive范圍,在主要示例中我只使用https://www.googleapis.com/auth/drive.appdata

使用以下行,示例工作正常

credential = credential.createScoped(Collections.singleton("https://www.googleapis.com/auth/drive"));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM