Google Analytics with Flash Actionscript 2

Date December 3, 2009

A little background info, Google Analytics is a free service provided by google to track site statistics, page visits, unique visitors, most visited page, etc.

Now I have been working around with flash actionscript 2 for a few months now and last week I was trying to connect to google analytics using flash actionscript 2, I know there’s already Actionscript 3 but its AS2 that was required for the project ;) After a few days of trial and error, finally got the stupid code to work, my initial code was not able to properly remove the white spaces from the returned IDs sent by Google. Weird thing is as I googled around the web, people seem to have a problem logging in and authenticating google AuthID through flash AS2 and AS3. As I understand it, there was supposed to be no way of authenticating the AuthID unless google add an option in their crossdomain.xml.

Well… seems like I was able to login and authenticate using the google account’s AuthID and retrieve my Profile list as well as used the profile data to retrieve the analytics data from my account =)

Codes are shown below on how I was able to login and authenticate the AuthID. One note, ALWAYS remove the white spaces (\r and \n) that was returned after initial login process (email & pass).

Note this is just a proof of concept and I didn’t do any clean-up,etc…
This will also work with Actionscript 3…

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
var authId:String = "";
gProfile = new LoadVars();
 
gData = new LoadVars();
 
gLogin = new LoadVars();
gLogin.Email = "yourgoogleaccount@email.com.here";
gLogin.Passwd = "password goes here";
gLogin.service = "analytics"; // what service your accessing, analytics for google analytics, mail for gmail, and so on...
gLogin.accountType = "GOOGLE"; // this should be default to GOOGLE
gLogin.source = "proj-name-0.1"; // anything goes heres, just a string for your proj
 
gLogin.onLoad = function(success) {
    if (success)
    {
        logs.text += "\ryay!";
 
    } else {
        logs.text += "\rtry again";    
    }
}
 
//header content type should be of application urlencoded form
headers = new Array(["Content-Type", "application/x-www-form-urlencoded"]);
 
gLogin.onHTTPStatus = function(httpStatus:Number) {
       logs.text +=  "\r" + httpStatus;
    }
 
 
//address where to login using the username and pass
gLogin.sendAndLoad("https://www.google.com/accounts/ClientLogin", gLogin, "POST");
 
var myAuthID:String;
 
gLogin.onData = function(ret:String) {	
	var auth:Array = ret.split("Auth=");
	authId = auth[1];	
	authId = authId.split('\n').join('');
	var auth:String = "GoogleLogin auth=" +  authId;
	logs.text += "\r" + auth;
	myAuthID = authId;
 
	//for the authentication and profile retrieval, add the "Authorization" header and the google login authid we received 
	// from google after logging in a few seconds ago. We also add X-HTTP-Method-Override with a value of "GET" to force
	// the server to accept our data as GET insted of POST method, if we don't do this, the Authorization fails.
	gProfile.addRequestHeader(["X-HTTP-Method-Override", "GET", "Authorization", "GoogleLogin auth=" + authId]);
 
	//debugging trace of the customer headers
	trace("_customHeaders = " + gProfile._customHeaders);		
 
	//authorization and profile retrieval address
	gProfile.sendAndLoad("https://www.google.com/analytics/feeds/accounts/default", gProfile, "POST");
}
 
String.prototype.replace = function(searchStr, replaceStr):String {	
    var arr:Array = this.split(searchStr);
    return arr.join(replaceStr);
};
 
gProfile.onData = function(ret:String) {
    trace("----->" + ret);
	//everytime you retrieve data/profile from google analytics, always add the Authorization header as this will 
	// be used to authenticate your account.	
	gData.addRequestHeader(["X-HTTP-Method-Override", "GET", "Authorization", "GoogleLogin auth=" + myAuthID]);
	trace("_customHeaders = " + gData._customHeaders);		
 
	//here is the string to query analytics data from a certain project, ids is the table/proj id to retrieve the metrics
	// you can read more from analytics developer api docs on how to manipulate your data retrieval...
	var str:String = "&ids=ga:1234567&dimensions=ga:source,ga:medium&metrics=ga:visits,ga:pageviews";
	gData.sendAndLoad("https://www.google.com/analytics/feeds/data?start-date=2009-10-01&end-date=2009-10-31" + str, gData, "POST");
 
}
 
gData.onData = function (ret:String){
 
	trace("======" + ret );
 
}
 
gProfile.onHTTPStatus = function(httpStatus:Number) {
       logs.text += "\r" + httpStatus ;
    }

Any suggestions and comments are very welcome.

Update: I’d like to add that this only works on your local machine, if you upload this to a live server or website, you will need a crossdomain.xml from www.google.com to allow your site.

Sources:
http://meidell.dk/archives/2005/12/30/http-authentication-with-flash/
http://code.google.com/p/ga-api-http-samples/source/browse/trunk/src/v2/accountFeed.sh

Related posts

5 Responses to “Google Analytics with Flash Actionscript 2”

  1. Fabian said:

    Hi there,

    thanks for the excellent code. I have been searching for such a solution for weeks.
    However, I still got a problem.
    Flash shows me the following error and GooglAnalytics can’t gather any data.
    Do you know the solution for that prob?

    Flash-Output:
    “_customHeaders = X-HTTP-Method-Override,GET,Authorization,GoogleLogin auth=DQAAAG8AAADSGpWgYRmBLS9RuR4psS8cYPML2-5YzJ27O0BCijHX8fllLhVJYtpAHOQPVtv4q4yhe1o-P5V1LxpZqp_8RCPD8fSebtk5YXF-b6nJUmeNbRI8dt6dOxYcLYf47j5xOSdFwwlOfOImxRcFwb0a9Bji
    —–>http://www.google.com/analytics/feeds/accounts/”e-Mail”2010-01-11T14:59:46.000-08:00Profile list for “e-Mail”Google AnalyticsGoogle Analytics111http://www.google.com/analytics/feeds/accounts/ga:251807562010-01-11T14:59:46.000-08:00″URL”ga:25180756
    _customHeaders = X-HTTP-Method-Override,GET,Authorization,GoogleLogin auth=DQAAAG8AAADSGpWgYRmBLS9RuR4psS8cYPML2-5YzJ27O0BCijHX8fllLhVJYtpAHOQPVtv4q4yhe1o-P5V1LxpZqp_8RCPD8fSebtk5YXF-b6nJUmeNbRI8dt6dOxYcLYf47j5xOSdFwwlOfOImxRcFwb0a9Bji

    Error opening the URL ‘https://www.google.com/analytics/feeds/data?start-date=2009-10-01&end-date=2009-10-31&ids=ga:1234567&dimensions=ga:source,ga:medium&metrics=ga:visits,ga:pageviews’
    ======undefined”

    regards

    fabian

  2. Chaoz said:

    Hi Fabian,

    Your problem there is your ids=ga:1234567. You should change that to one of your profile’s ID that was returned by “ret” under gProfile.onData event. If there aren’t any IDs returned then you have to login into Google Analytics and create your profile/project as that is required for this code to work.

    Don’t hesitate to ask if there are still problems :)

    thanks

  3. Fabian said:

    Hello,

    ok, thanks a lot – problem solved. ;)

    I am sure there will be more questions in the future.
    One general Issue: is it true that GoogleAnalytics will only show information within the tracking table that I post under “gData, POST” to it when using AS2?
    What does the date value here actually effect?

    thanks in advance

    fabian

  4. Chaoz said:

    Yes and No… Yes – it will only show the data under the profile/table since that is where google will retrieve your requested data. No – you can always send another request with different profile/table ID and retrieve another set of data ;)

    The data value end and start will be the basis of the range of data google will get from your request.. for example start-date is 2009-10-01 and end-data is 2009-10-13, so google will retrieve all data you requested from Oct 1, 2009 to Oct 13, 2009.

    Now the question is “what” data do you want.. you can check google analytics API and see the different possibilities. http://code.google.com/intl/de/apis/analytics/docs/gdata/gdataReferenceDimensionsMetrics.html

    My Code above just retrieved the pageview for the date range.

  5. Fabian said:

    Hi Chaoz,

    ok – I see. Thanks for the information.
    I will work myself into GoogleAnalytics and post further questions here if they occure.

    bye

    fabian

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">