永久授权令牌适用于php的Google API表格

时间:2019-06-19 09:36:39

标签: php google-sheets google-api

我正在开发一个项目,在该项目中,您需要使用Google Api for Google Sheets服务通过php进行更改,但是通过单击授权链接获得的访问令牌只能使用2个小时。问题是将令牌的有效性延长了两个小时以上,请协助完成此任务。以下是我获取Google客户端的函数示例:

$client = new Google_Client();
$client->setApplicationName('My Project 45639');
//$client->setScopes(Google_Service_Sheets::SPREADSHEETS);
$client->setAuthConfig('credentials.json');
$client->setAccessType('offline');
$client->setPrompt('select_account consent');
$client->setScopes('https://www.googleapis.com/auth/spreadsheets');

// Load previously authorized token from a file, if it exists.
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
$tokenPath = 'token.json';
if (file_exists($tokenPath)) {
    $accessToken = json_decode(file_get_contents($tokenPath), true);
    $client->setAccessToken($accessToken);
}

// If there is no previous token or it's expired.
if ($client->isAccessTokenExpired()) {
    // Refresh the token if possible, else fetch a new one.
    if ($client->getRefreshToken()) {
        $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
    } else {
        // Request authorization from the user.
        //$authUrl = $client->createAuthUrl();
        //printf("%s", $authUrl);
        $authCode = trim('4/aQHXC2H_MmBA3ifDlXmJiDHyEk2m2QCoKrP1YDdAbBZSZBPUMmbINxg');

        // Exchange authorization code for an access token.
        $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
        $client->setAccessToken($accessToken);

        // Check to see if there was an error.
        if (array_key_exists('error', $accessToken)) {
            throw new Exception(join(', ', $accessToken));
        }
    }
    // Save the token to a file.
    if (!file_exists(dirname($tokenPath))) {
        mkdir(dirname($tokenPath), 0700, true);
    }
    file_put_contents($tokenPath, json_encode($client->getAccessToken()));
}
return $client;

0 个答案:

没有答案