php 从Google_Service_AnalyticsReporting(google/apiclient SDK)切换到BetaAnalyticsDataClient(google/analytics-data SDK)

c9x0cxw0  于 2023-06-21  发布在  PHP
关注(0)|答案(2)|浏览(105)

我正在将Google Analytics属性从UA切换到GA 4,并试图使用Data API为GA 4属性提取Google Analytics数据。我目前使用的是google/apiclient PHP SDK for UA properties,但需要切换到google/analytics-data SDK for GA 4 properties。我能找到的所有凭证文档都是为使用服务帐户编写的。不幸的是,我们不能使用服务帐户为我们目前的设置,并需要登录为用户analytics@company.com这是电子邮件/用户已添加到我们的帐户内的属性。
对于google/apiclient SDK,我们的连接是这样的:

$appName = 'My Analytics App';
// Decoded from json file for example
$clientAuthFileData = [
    'web' => [
        'client_id'                   => '######-#######.apps.googleusercontent.com',
        'project_id'                  => 'my-project-name',
        'auth_uri'                    => 'https://accounts.google.com/o/oauth2/auth',
        'token_uri'                   => 'https://oauth2.googleapis.com/token',
        'auth_provider_x509_cert_url' => 'https://www.googleapis.com/oauth2/v1/certs',
        'client_secret'               => 'XXXXXXXXXXX',
        'redirect_uris'               =>
            [
                'https://site1.com/authorize.php',
                'https://site2.com/authorize.php',
                'https://site3.com/authorize.php',
                'https://site4.com/authorize.php',
                'https://site5.com/authorize.php',
            ],
    ],
];
// Decoded from json file for example
$authFileData       = [
    'access_token'  => 'XXXXXXXX',
    'expires_in'    => 3600,
    'refresh_token' => 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
    'scope'         => 'https://www.googleapis.com/auth/userinfo.email openid https://www.googleapis.com/auth/analytics.readonly',
    'token_type'    => 'Bearer',
    'id_token'      => 'XXXXXXXXXXXXXXXXXXXXXX.XXXXXXXXXXXXXXXXXXX',
    'created'       => 1553570124,
];

$client = new Google_Client();
$client->setApplicationName( $appName );
$client->setAccessType( "offline" );
$client->setAuthConfig( $clientAuthFileData );
$client->fetchAccessTokenWithRefreshToken( $authFileData['refresh_token'] );

$client = new Google_Service_AnalyticsReporting( $client );

要使用google/analytics-data SDK中的服务帐户执行相同的调用,它看起来像这样:

// Decoded from json file for example
$serviceAccountCredentials = '{
  "type": "service_account",
  "project_id": "my-project-name",
  "private_key_id": "XXXXXXXXXX",
  "private_key": "-----BEGIN PRIVATE KEY-----XXXXXXXXX\n-----END PRIVATE KEY-----\n",
  "client_email": "name@my-project-name.iam.gserviceaccount.com",
  "client_id": "XXXXXXXXXX",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://oauth2.googleapis.com/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/name%40my-project-name.iam.gserviceaccount.com"
}';

$client = new BetaAnalyticsDataClient( [
    'credentials' => json_decode( $serviceAccountCredentials, true ),
] );

对于GA 4,我尝试了以下方法:

/*
THROWS
Fatal error: Uncaught InvalidArgumentException: json key is missing the type field in /var/www/html/vendor/google/auth/src/CredentialsLoader.php on line 150

InvalidArgumentException: json key is missing the type field in /var/www/html/vendor/google/auth/src/CredentialsLoader.php on line 150
*/
$client = new BetaAnalyticsDataClient( [
    'credentials' => $clientAuthFileData,
] );

/*
THROWS
Fatal error: Uncaught DomainException: Could not load the default credentials. Browse to https://developers.google.com/accounts/docs/application-default-credentials for more information in /var/www/html/vendor/google/gax/src/CredentialsWrapper.php on line 267
Google\ApiCore\ValidationException: Could not construct ApplicationDefaultCredentials in /var/www/html/vendor/google/gax/src/CredentialsWrapper.php on line 267
 */
$client = new BetaAnalyticsDataClient( [
    'keyFile' => $clientAuthFileData,
] );

如何使用与google/apiclient SDK相同的OAuth细节进行连接?

tv6aics1

tv6aics11#

我是通过深入研究类文件如何处理凭证来发现这一点的。对于遇到这种情况的任何人,您可以使用以下命令:

$client = new BetaAnalyticsDataClient( [
    'credentials' => Google\ApiCore\CredentialsWrapper::build( [
        'scopes'  => [
            'https://www.googleapis.com/auth/analytics',
            'openid',
            'https://www.googleapis.com/auth/analytics.readonly',
        ],
        'keyFile' => [
            'type'          => 'authorized_user',
            'client_id'     => $clientAuthFileData['web']['client_id'],
            'client_secret' => $clientAuthFileData['web']['client_secret'],
            'refresh_token' => $authFileData['refresh_token'],
        ],
    ] ),
] );

我在这里将作用域设置为数组,因为这是类期望的方式,在JSON文件中,它们是用空格分隔的字符串,您可能会使用以下内容,但我没有测试它:

$client = new BetaAnalyticsDataClient( [
    'credentials' => Google\ApiCore\CredentialsWrapper::build( [
        'scopes'  => explode( ' ', $authFileData['scope'] ),
        'keyFile' => [
            'type'          => 'authorized_user',
            'client_id'     => $clientAuthFileData['web']['client_id'],
            'client_secret' => $clientAuthFileData['web']['client_secret'],
            'refresh_token' => $authFileData['refresh_token'],
        ],
    ] ),
] );
3phpmpom

3phpmpom2#

我设法做同样的事情,而不指定范围的。我认为这是没有必要的,因为它没有写在文档中,它对我来说工作得很好。我只使用了我的json文件,这是我的服务器端密钥。

$config = [
    'credentials' => [PATH-TO-JSON-FILE],
];

$client = new BetaAnalyticsDataClient($config);

相关问题