Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lutsen/d7fd470b0e247f059525fbbf34e720db to your computer and use it in GitHub Desktop.
Save lutsen/d7fd470b0e247f059525fbbf34e720db to your computer and use it in GitHub Desktop.
How to set up Google Drive push notifications for a file, and test if they work by catching them and writing them in a file with a PHP script.

Activate notifications for the file with ID [file-id] by posting some JSON to this URL: https://www.googleapis.com/drive/v3/files/[file-id]/watch Authorization: Bearer auth_token_for_current_user Content-Type: application/json

Minimal JSON you need to POST:

{
  "id": "[some unique ID for your push, you can define it yourself but it mus be unique]",
  "type": "web_hook",
  "address": "https://www.example.com/catch.php"
}

The answer if all goes well:

{
    "kind": "api#channel",
    "id": "[some unique ID for your push, you can define it yourself but it must be unique]",
    "resourceId": "[resourceId]",
    "resourceUri": "https://www.googleapis.com/drive/v3/files/[file-id]?acknowledgeAbuse=false&supportsTeamDrives=false&alt=json",
    "expiration": "1526248563000"
}

Note:

  • The push notifications will only work for one hour and need to be re-activated after that.
  • If you enable notifications for a folder, only the changes for its direct children are shown, not the changes inside the child-folders.

If you set the notifications, you might also need a new oAuth token. If you set the access-type of your app to offline, you can get one using your refresh-token.

Post to this URL: https://accounts.google.com/o/oauth2/token

Post these variables as x-www-urlencoded:

  • client_id
  • client_secret
  • refresh_token
  • grant_type = refresh_token

More info: https://developers.google.com/drive/v3/web/push

<?php
// Catch any request and write it to a file
class DumpHTTPRequestToFile {
public function execute($targetFile) {
$data = sprintf(
"%s %s %s\n\nHTTP headers:\n",
$_SERVER['REQUEST_METHOD'],
$_SERVER['REQUEST_URI'],
$_SERVER['SERVER_PROTOCOL']
);
foreach ($_SERVER as $name => $value) {
$data .= $name . ': ' . $value . "\n";
}
$data .= "\nRequest body:\n";
file_put_contents(
$targetFile,
$data . file_get_contents('php://input') . "\n\n\n\n",
FILE_APPEND
);
echo("Done!\n\n");
}
}
(new DumpHTTPRequestToFile)->execute('dump.txt');
@denismailloux
Copy link

Beginner question I know? Where do I find or generate the auth_token_for_current_user?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment