-
Notifications
You must be signed in to change notification settings - Fork 0
/
googlesheets.php
49 lines (43 loc) · 1.8 KB
/
googlesheets.php
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<?php
/**
* Returns an authorized API client.
* @return Google_Client the authorized client object
*/
function getGoogleClient($headless = TRUE)
{
global $config_dir;
$client = new Google_Client();
$client->setApplicationName('Instanssiradio');
$client->setScopes(Google_Service_Sheets::SPREADSHEETS);
$client->setAuthConfig($config_dir.'credentials.json');
$client->setAccessType('offline');
// Load previously authorized credentials from a file.
$credentialsPath = $config_dir.'token.json';
if (file_exists($credentialsPath)) {
$accessToken = json_decode(file_get_contents($credentialsPath), true);
} else if ($headless) {
throw new Exception('This application must be logged in first using login.php');
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
// Check to see if there was an error.
if (array_key_exists('error', $accessToken)) {
throw new Exception(join(', ', $accessToken));
}
// Store the credentials to disk.
file_put_contents($credentialsPath, json_encode($accessToken));
printf("Credentials saved to %s\n", $credentialsPath);
}
$client->setAccessToken($accessToken);
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
}
return $client;
}