Russian  English  All projects

Configure authorization via OAuth2 for PHP script



There is a script that logs in via OAuth2 and sends requests to Google Analytics using the Google_Service_Analytics class

You can see how the app works here https://www.kl82.com/node/add/report-ga-connector


You need to send a request using the AnalyticsAdminServiceClient class in the same way. This is a class from the Google Analytics Data API modern library https://developers.google.com/analytics/devguides/reporting/data/v1?hl=en


A working piece of old code

$analytics = new Google_Service_Analytics($client)
$accounts = $analytics->management_accountSummaries->listManagementAccountSummaries()


Code snippet that doesnt work:

$analytics = new AnalyticsAdminServiceClient([
credentials => GoogleApiCoreCredentialsWrapper::build( [
scopes => [
https://www.googleapis.com/auth/analytics,
openid,
https://www.googleapis.com/auth/analytics.readonly,
],
keyFile => [
type => authorized_user,
grant_type => authorized_user,
client_id => $client->getClientId(),
client_secret => $client->getClientSecret(),
refresh_token => $client->getRefreshToken(),
access_token => $client->getAccessToken()["access_token"]
],
] ),
] )
$accounts = $analytics->listAccounts()

Returns GuzzleHttpExceptionClientException: Client error: POST https://oauth2.googleapis.com/token resulted in a 400 Bad Request response: { "error": "unsupported_grant_type", "error_description": "Invalid grant_type: " } in GuzzleHttpExceptionRequestException::create()



15.10.2024 20:23



 Answers freelancers