我正在开发谷歌文档api,我想发送请求并获得身份验证代码,作为交换,该代码将提供访问令牌。下面的代码运行良好,但问题是我必须复制身份验证url并将其粘贴到浏览器,然后从浏览器url复制身份验证代码并粘贴到终端,作为回报,在我的目录中创建了一个token.json文件。但问题是,我想在我的项目中实现同样的东西,我不能像这样把url从一个地方复制到另一个地方。我希望一切都是动态的。
有人能帮我们修改下面的代码来发送auth-url请求吗?作为回报,我得到了auth代码,我可以从中获取访问令牌,而无需将其复制并粘贴到终端进行处理。
function getClient()
{
$client = new Google_Client();
$client->setApplicationName('Google Docs API PHP Quickstart');
$client->setScopes([
"https://www.googleapis.com/auth/documents",
"https://www.googleapis.com/auth/drive.file",
"https://www.googleapis.com/auth/drive"
]);
$client->setAuthConfig('credentials.json');
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
// Load previously authorized credentials from a file.
$credentialsPath = expandHomeDirectory('token.json');
if (file_exists($credentialsPath)) {
$accessToken = json_decode(file_get_contents($credentialsPath), true);
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
$authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
// Store the credentials to disk.
if (!file_exists(dirname($credentialsPath))) {
mkdir(dirname($credentialsPath), 0700, true);
}
file_put_contents($credentialsPath, json_encode($accessToken));
// printf("Credentials saved to %sn", $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;
}
PHP客户端库不是为使用控制台应用程序或已安装的应用程序打开web浏览器而设计的。您需要向用户显示Oauth2浏览器链接,然后他们可以在浏览器中打开该链接,然后将其粘贴回代码中。
该库不支持在控制台应用程序中为您打开浏览器窗口的功能。
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:n%sn", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);