如何复用google/apiclient的OAuth凭证对接BetaAnalyticsDataClient拉取GA4数据
实现步骤
- 你可以直接使用两个SDK共同依赖的
google/auth内置类UserRefreshCredentials复用现有OAuth凭证,不需要走服务账号配置逻辑。 - 原有客户端配置、refresh token数据无需修改,可以直接复用。
完整可运行代码示例
<?php use Google\Analytics\Data\V1beta\BetaAnalyticsDataClient; use Google\Auth\Credentials\UserRefreshCredentials; $appName = 'My Analytics App'; // 原有客户端配置,无需修改 $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', ], ], ]; // 原有授权token数据,无需修改 $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, ]; // 构造用户刷新令牌凭证 $credentials = new UserRefreshCredentials( $authFileData['scope'], [ 'client_id' => $clientAuthFileData['web']['client_id'], 'client_secret' => $clientAuthFileData['web']['client_secret'], 'refresh_token' => $authFileData['refresh_token'] ] ); // 将凭证直接传入GA4客户端即可完成初始化 $client = new BetaAnalyticsDataClient([ 'credentials' => $credentials, 'projectId' => $clientAuthFileData['web']['project_id'] ]); // 后续可正常调用GA4 Data API接口
可选方案:复用原有
google/apiclient刷新逻辑 如果你不想调整原有token刷新逻辑,也可以直接将刷新后拿到的有效access_token传入GA4客户端:
<?php use Google\Client as Google_Client; use Google\Analytics\Data\V1beta\BetaAnalyticsDataClient; // 原有获取token的逻辑完全保留 $googleClient = new Google_Client(); $googleClient->setApplicationName( $appName ); $googleClient->setAccessType( "offline" ); $googleClient->setAuthConfig( $clientAuthFileData ); $token = $googleClient->fetchAccessTokenWithRefreshToken( $authFileData['refresh_token'] ); // 直接传入有效access_token初始化GA4客户端 $client = new BetaAnalyticsDataClient([ 'credentials' => [ 'key' => $token['access_token'] ], 'projectId' => $clientAuthFileData['web']['project_id'] ]);
注意:该方案需要你自行处理access_token过期刷新逻辑,token过期后需要重新调用刷新方法获取新的token再初始化客户端。
内容的提问来源于stack exchange,提问作者spyke01
相关产品推荐
相关产品推荐

