I’m working with Google Analytics at the moment, to pull information about web traffic from analytics into another system. Google have excellent APIs and that makes this job much easier. I’m using
pecl_oauth to authenticate users against their google accounts (see my post about
using OAuth from PHP), but even after I have a valid google user, working out which analytics accounts they have access to and how to refer to them is a puzzle in itself, so I thought I’d share what I learned.These examples use
pecl_http, since I have control of my platform and I find it easy to work with. I’ve tried to write this with explanations of the overall process in between the code snippets so hopefully this makes the process clear whether or not you will use exactly the same implementation.
Analytics Accounts
Your google account can have access to one or more analytics accounts. For example when I log in I have access to accounts which hold the data for lornajane.net, phpwomen.org, joind.in and a few other things I’m involved with. Only lornajane.net actually belongs to me, the others are accounts created by someone else and which I have access to. The first challenge therefore is to work out which a user has access to – the best place to start is the reference page for the Management API, part of google’s own documentation. In a nutshell, we build up a URL like this, being increasingly specific by fleshing out the values in square brackets on subsequent calls:
https://www.google.com/analytics/feeds/datasources/ga/accounts/[accountID]/
webproperties/[webPropertyID]/profiles/[profileID]/goals
First up then, is to get a list of accounts for our authorized user – I already have a valid oauth access token to use in this example Continue reading →