Search code examples
phpgoogle-apigoogle-oauthgoogle-api-php-client

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


Hello I am trying to get access token using Google api client PHP in CodeIgniter

when I load this localhost:8080/google/callback i am getting following error

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 

here is code

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();
}

it will be a great if anybody can help me sorting this.


Solution

  • You need to redirect user to createAuthUrl() to get $_GET['code']

    You can simply do it by following way

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

    where you can initially check $_GET['code'] is exist if not request for it.

    Hope this might help you.