I'm trying to get an access token to make REST calls to my Firestore DB. I'm using PHP (only way for now) and have taken the next steps:
And created this code:
putenv('GOOGLE_APPLICATION_CREDENTIALS='.__DIR__ .'/key.json');
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->addScope('https://www.googleapis.com/auth/datastore,https://www.googleapis.com/auth/cloud-platform');
$client->authorize();
I also replaced the
$client->useApplicationDefaultCredentials();
part with
$client->setAuthConfig(__DIR__ .'/key.json');
Now when I var_dump the $client, the token stays NULL.
I just can't figure out, how to get the access_token for my service account. Anybody an idea how I can get an access token?
If you want to add multiple scopes, you will have to use an array instead of a string. A string will only be treated as one single scope.
The $client->authorize() returns a Client instance which is authorized to to access the Google Services for the given scopes. So, $authorizedClient = $client->authorize(); would be more appropriate.
If you just want to retrieve the access token, you could use $client->fetchAccessTokenWithAssertion(), which would give you something like this:
Array
(
[access_token] => ya29.c..............
[token_type] => Bearer
[expires_in] => 3600
[created] => 1511280489
)
Here is the complete script I used to test this:
<?php
require __DIR__.'/vendor/autoload.php';
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->addScope([
'https://www.googleapis.com/auth/datastore',
'https://www.googleapis.com/auth/cloud-platform'
]);
// $client->authorize();
print_r($client->fetchAccessTokenWithAssertion());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With