繁体   English   中英

如何使用 php 获取带有谷歌 api 授权码的访问令牌?

[英]How fetch access token with auth code for google api using php?

我正在处理 google docs api,我想发送请求并获取授权代码,作为交换将提供访问令牌。 下面的代码工作正常,但问题是我必须复制 auth url 并将其粘贴到浏览器,然后从浏览器 url,我复制 auth 代码并将其粘贴到终端,终端返回一个 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 %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;
}

PHP 客户端库并非设计用于使用控制台应用程序或安装的应用程序为您打开 web 浏览器。 您需要向用户显示 Oauth2 浏览器链接,然后他们可以在浏览器中打开该链接,然后粘贴回代码中。

该库不支持在控制台应用程序中为您打开浏览器 window 的功能。

       // 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);
        $client->setAccessToken($accessToken);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM