函数 Google\Client::authenticate() 的参数太少,在第 41 行 google.php 中传递了 0 个,预期正好是 1 个

Too few arguments to function Google\Client::authenticate(), 0 passed in google.php on line 41 and exactly 1 expected

您好,我正在尝试在 CodeIgniter

中使用 Google api 客户端 PHP 获取访问令牌

当我加载此 localhost:8080/google/callback 时出现以下错误

Too few arguments to function Google\Client::authenticate(), 0 passed in E:\wamp\www\myproject\app\Controllers\Google.php on line 41 and exactly 1 expected 

这是代码

public function callback(){
define('GOOGLE_CLIENT_ID', 'XXXX']);
define('GOOGLE_CLIENT_SECRET', 'XXXX');


// Create Client Request to access Google API
$client = new Client();
$client->setApplicationName('Mysite.dom.ain');
$client->setClientId(GOOGLE_CLIENT_ID);
$client->setClientSecret(GOOGLE_CLIENT_SECRET);
$client->setRedirectUri('http://localhost:8080/google/callback');
$client->addScope('https://www.googleapis.com/auth/youtube https://www.googleapis.com/auth/youtube.upload');
$client->setAccessType('offline');        // offline access
$client->setIncludeGrantedScopes(true);   // incremental auth
$client->setHttpClient(new GC(['verify' => false]));

        $client->authenticate();
        
    return $client->getAccessToken();
}

如果有人能帮我整理一下就太好了。

您需要将用户重定向到 createAuthUrl() 才能获得 $_GET['code']

您可以通过以下方式轻松完成

if (isset($_GET['code'])) {
    $client->authenticate($_GET['code']);
    return $client->getAccessToken();
} else {
$redirect = $client->createAuthUrl();
header('Location: ' . $redirect);
        exit();
}

如果没有请求,您可以从哪里开始检查 $_GET['code'] 是否存在。

希望这对您有所帮助。