Basic example of Google Analytics API’s PHP integration.
These initial steps are copied from Google’s PHP quickstart tutorial.
- With your Google account, create a new Google API project
- Go to that project’s Credentials page (you should see the project name in the top-left corner of the page).
- Click “Create Credentials” and create a new OAuth client ID.
- Configure your consent screen (you only need a Product Name; everything else is optional).
- For the client ID’s application type, select “Web Application.”
- Give it a name and add an authorized redirect URI:
http://localhost:8000/oauth2callback.php
*. - When you see the popup with your client ID, click “OK” and on the right side of the page click the Download icon to download your
client_secrets.json
. - Save your
client_secrets.json
in the project root. (You can see an example inclient_secrets.example.json
.) - Enable the Google Analytics API for your project in the Google API Library. (If you don’t now, you’ll get an error with a link to enable it when you try to run the project.)
*The Google Analytics tutorial uses port 8080
, but I’ve chosen to use 8000
instead.
composer install
cp config.example.php config.php
Add the View ID for the Google Analytics property/view you want to create reports for.
php -S localhost:8000 -t .
Open http://localhost:8000 in your browser and authorize the app with your Google account.
When you load the page, you should see your site’s session count for the last 7 days:
sessions: ###
Go to the Reporting API’s docs for details on how to create bigger, better, custom reports.