在PHP中使用Gmail API:如何使CLI应用程序在浏览器中工作?

在PHP中使用Gmail API:如何使CLI应用程序在浏览器中工作?,php,command-line-interface,gmail-api,Php,Command Line Interface,Gmail Api,我正在测试Gmail API 到目前为止,我使用的是,并将我的环境选择为“桌面”,因为“其他”不可用,而s的网站环境将无法工作 它不起作用,因为当我使用浏览器访问php文件时,我会得到: 在浏览器中打开以下链接:输入验证代码: 而且没有地方在验证后实际键入验证码 当我从终端访问它时,我只是粘贴验证码,就这样 这可能是一个愚蠢的问题,但我如何使它在页面中工作 这是我的档案: 您应该遵循以下步骤。credentials对象中存在差异,令牌将存储在会话中,这意味着您不必将其复制并粘贴到终端中 示例代码

我正在测试Gmail API

到目前为止,我使用的是,并将我的环境选择为“桌面”,因为“其他”不可用,而s的网站环境将无法工作

它不起作用,因为当我使用浏览器访问php文件时,我会得到:

在浏览器中打开以下链接:输入验证代码:

而且没有地方在验证后实际键入验证码

当我从终端访问它时,我只是粘贴验证码,就这样

这可能是一个愚蠢的问题,但我如何使它在页面中工作

这是我的档案:
您应该遵循以下步骤。credentials对象中存在差异,令牌将存储在会话中,这意味着您不必将其复制并粘贴到终端中

示例代码:

参考资料:
<?php

require_once 'vendor/autoload.php';

/**
 * Returns an authorized API client.
 * @return Google_Client the authorized client object
 */
function getClient()
{
    $client = new Google_Client();
    $client->setApplicationName('Gmail Access');
    $client->setScopes(Google_Service_Gmail::GMAIL_READONLY);
    $client->setAuthConfig(__DIR__ . 'credentials.json');
    $client->setAccessType('offline');
    $client->setPrompt('select_account consent');

    // 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("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);

            // 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;
}


// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Gmail($client);
.........