Jeko Eustaquio
Jeko Eustaquio

Reputation: 69

How to connect to a Google Drive API and get the AccessToken

I'm here with a little problem to connect my script with a Google Drive API using a credentials json file.

This is my code:

$oauth_credentials = __DIR__.'\credentials.json';
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];

$client = new Google\Client();
$client->setAccessType('offline');
$client->setAuthConfig($oauth_credentials);
$client->setRedirectUri($redirect_uri);
$client->addScope("https://www.googleapis.com/auth/drive");

if (isset($_GET['code'])) {
        $token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
        var_dump($token);
}

Obviously I used composer to add google apiclient project to my script, and I used the cloud console of google to enable Drive API and create the credentials for this, and I used the credentials.json file downloaded of Google Console.

All is apparently good, I added a test account and used this account to accept permissions to use the Drive API.

Using the playground, in this URL https://developers.google.com/oauthplayground I test my credentials and I get the authorization code to create a refresh token and access token, but when i use this authorization code in my script the result is this: ""

'error' => string 'invalid_grant' (length=13)
'error_description' => string 'Bad Request' (length=11)

Any suggests? this code is exactly like the code appear in the Google examples.

Upvotes: 1

Views: 860

Answers (1)

Jeko Eustaquio
Jeko Eustaquio

Reputation: 69

My problem is that the focus is wrong way, I create a service account and generate the json credentials file and I use this code for upload a file:

putenv('GOOGLE_APPLICATION_CREDENTIALS=credentials.json');
    $client = new Google_Client();
    $client->useApplicationDefaultCredentials();
    $client->setScopes(['https://www.googleapis.com/auth/drive.file']);

    try {
        $service = new Google_Service_Drive($client);
        $file_path = 'example.txt';
        $file = new Google_Service_Drive_DriveFile();
        $file->setName('example.txt');
        $file->setParents([$this->folder_id]);
        $file->setDescription('Example description text');

        $result = $service->files->create($file,[
            'data' => file_get_contents($file_path),
            'mimeType' => 'text/plain',
            'uploadType' => 'text'
        ]);

        echo '<a href="https://drive.google.com/open?id='.$result->id.'" target="_blank">Link to the uploaded file</a>';
    }
    catch(Google_Service_Exception $gs)
    {
        $m = json_decode($gs->getMessage());
        echo $m->error->message;
    }
    catch(Exception $e)
    {
        echo $e->getMessage();
    }

Upvotes: 1

Related Questions