使用 google-api-php 库获取 REST api 的 Firestore 访问令牌

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

我正在尝试获取访问令牌以对我的 Firestore 数据库进行 REST 调用。我正在使用 PHP(目前唯一的方法)并采取了后续步骤:

并创建了这段代码:

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

我也换了

$client->useApplicationDefaultCredentials();  

分手

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

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

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

  1. 如果要添加多个作用域,则必须使用数组而不是字符串。一个字符串只会被视为一个范围。

  2. $client->authorize()returns一个Client实例被授权访问给定范围的Google服务。所以,$authorizedClient = $client->authorize();会更合适。

  3. 如果您只想检索访问令牌,您可以使用 $client->fetchAccessTokenWithAssertion(),这会给您这样的结果:

    Array
    (
        [access_token] => ya29.c..............
        [token_type] => Bearer
        [expires_in] => 3600
        [created] => 1511280489
    )
    

这是我用来测试的完整脚本:

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