Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Firestore access token for REST api with google-api-php lib

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:

  • Created a service account in the Firebase console and downloaded the key JSON
  • Downloaded the Google-api-php library from https://developers.google.com/api-client-library/php/ and included in my code

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?

like image 662
P Bee Avatar asked Jan 28 '26 13:01

P Bee


1 Answers

  1. 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.

  2. 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.

  3. 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());
like image 93
jeromegamez Avatar answered Jan 31 '26 02:01

jeromegamez