关于Firebase:使用google-api-php lib获取REST api的Firestore访问令牌

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

我正在尝试获取访问令牌以对我的Firestore数据库进行REST调用。我正在使用PHP(目前仅此方式),并已采取了以下步骤:

  • 在Firebase控制台中创建了一个服务帐户,并下载了密钥JSON
  • 从https://developers.google.com/api-client-library/php/下载了Google-api-php库,并将其包含在我的代码中

并创建此代码:

1
2
3
4
5
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();

我也替换了

1
$client->useApplicationDefaultCredentials();

带有

的部分

1
$client->setAuthConfig(__DIR__ .'/key.json');

现在当我var_dump $ client时,令牌保持为NULL。

我只是不知道如何获取我的服务帐户的access_token。有人知道我如何获得访问令牌吗?


  • 如果要添加多个作用域,则必须使用数组而不是字符串。字符串将仅被视为一个单一作用域。

  • $client->authorize()返回一个Client实例,该实例有权访问给定范围的Google服务。因此,$authorizedClient = $client->authorize();更合适。

  • 如果您只想检索访问令牌,则可以使用$client->fetchAccessTokenWithAssertion(),这将为您提供以下信息:

    1
    2
    3
    4
    5
    6
    7
    Array
    (
        [access_token] => ya29.c..............
        [token_type] => Bearer
        [expires_in] => 3600
        [created] => 1511280489
    )
  • 这是我用来测试此脚本的完整脚本:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    <?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());