Connect to Google Analytics from Flash Builder
Line Break
Author: Arjan (47 Articles) - Author Website
Arjan is a SAP Consultant specialized in ABAP and Front End development techniques like Web Dynpro, Adobe Interactive Forms, Flex and AIR. In his free time he likes to create examples for Flex-Blog and other applications using Flex, AIR and PHP. Other hobbies are movies and music. He is also the co-owner of Flex-Blog.com.
Everybody that has a site somewhere sitting on the Web is probably interested in the number of visitors. There are a a lot of solutions available that can give you detailed statistics about your site. Google Analytics is one of them, and I think this is the one that’s mostly used right now. Google also has an API which you can use to get statistics, wouldn’t it be cool to have these statistics available to you in Flex? Ofcourse it’s possible, here how you do it using PHP and Flash Builder 4.
To get started I looked for a PHP class that can access the Google Analytics API on the internet. I found one written by Chris Hope that I tested quickly and I found out that it works quite well for me, thanks to Chris Hope for that.
Now to use this API I thought it would be cool to connect to PHP using the new Data Connection features of Flash Builder, available for download at Adobe. With that data connector, the ActionScript classes that call the service are automatically generated for you, a really cool feature in the new Flash Builder.
To start developing, you need to have a webserver somewhere, I use XAMPP, but you can use anything you like for this.
To get your Flex / Flash project set up create a new project with the following settings:

Klik Next and configere your server:

If the Flash Builder promps you if you want the Zend Framework to be installed, do this. Zend is going to take care of communication from the Flex application to PHP using the AMF protocol.
Ok now you got you’re initial project set up. What I did after this was creating a PHP wrapper class (GoogleAnalyticsService.php) that uses the class of Chris Hope to access the Google Analytics API, I implemented 2 methods in this class:
GoogleAnalyticsService.php
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 | <?php require_once('analytics_api.php'); require_once('GoogleAnalyticsProfile.php'); require_once('GoogleAnalyticsSummary.php'); class GoogleAnalyticsService { private $email = "your_analytics_email_here"; private $pass = "your_analytics_pass_here"; public function getProfiles() { $api = new analytics_api(); $api->login($this->email, $this->pass); $api->load_accounts(); $result = array(); foreach($api->accounts as $value) { $profile = new GoogleAnalyticsProfile(); $profile->title = $value['title']; $profile->tableId = $value['tableId']; $profile->profileId = $value['profileId']; $profile->webPropertyId = $value['webPropertyId']; $profile->accountName = $value['accountName']; $result[] = $profile; } return $result; } public function getSummary($id, $period) { $api = new analytics_api(); $api->login($this->email, $this->pass); $result = $api->get_summary($id, $period); $summary = new GoogleAnalyticsSummary(); $summary->pageViews = $result['ga:pageviews']; $summary->visits = $result['ga:visits']; $summary->timeOnSite = $result['average_time_on_site_formatted']; $summary->pagesPerVisit = $result['pages_per_visit']; return $summary; } } |
As you can see, this file needs requires additional files:
- analytics_api.php
- GoogleAnalyticsProfile.php
- GoogleAnalyticsSummary.php
The first one is the one you probably downloaded from Chris Hope’s website, if you didn’t do that now.
The second one is an Object called GoogleAnalyticsProfile, we are going to use that to create real “profile” Objects from the Arrays that the API of Chris Hope gives as results (see the getProfiles method in GoogleAnalyticsService.php)
GoogleAnalyticsProfile.php:
1 2 3 4 5 6 7 8 9 10 11 12 13 | <?php class GoogleAnalyticsProfile { public $title; public $accountId; public $accountName; public $profileId; public $tableId; public $webPropertyId; } ?> |
The same goes for GoogleAnalyticsSummary.php:
1 2 3 4 5 6 7 8 9 10 | <?php class GoogleAnalyticsSummary { public $visits; public $timeOnSite; public $pageViews; public $pagesPerVisit; } ?> |
To make sure everything was working correctly, I created an index.php file that tests these methods:
index.php
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 | <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title></title> </head> <body> <?php require_once("GoogleAnalyticsService.php"); $analytics_service = new GoogleAnalyticsService(); $profiles = $analytics_service->getProfiles(); foreach( $profiles as $value ) { echo "Title: " . $value->title . " TableId: " . $value->tableId . '<br/>'; } $someProfile = array_pop($profiles); $summary = $analytics_service->getSummary($someProfile->tableId, 'today'); echo "Summary for today for " . $someProfile->title . "<br/>"; echo "Visits: " . $summary->visits . "<br/>"; echo "Pageviews: " . $summary->pageViews . "<br/>"; echo "Average time on site: " . $summary->timeOnSite . "<br/>"; echo "Pages per visits: " . $summary->pagesPerVisit . "<br/>"; ?> </body> </html> |
As everything is working correctly, you’re at least sure that you PHP is correct. Now we can start on the Flex project.
Assuming that you have already created the project, connect to the PHP Service as follows:
Browse to the GoogleAnalyticsService.php on you local webserver and accept the default settings or change them if you want:

Hit finish, Flash Builder will generate the service for you, and you can see it in the Data/Services tab. Now we are going to configure the return type of the two methods in the PHP Service. Go to the Data/Service tab, select the first method, right-mouse click and choose configure result type:

Flash builder determine the return type by calling the method and looking at the result:

Hit next, if the call was succesfull you should see something like this:

Hit finish, Flash Builder will create the Object for you, now you have mapping of objects in PHP to objects in ActionScript set up for this method. Repeat the steps for the second method. One of the methods needs two input parameters (period and tableId), a valid value for period is ‘today’, a valid tableId can be found by running the index.php file.
The result should look something like this, you can see that getProfiles return a collection of GoogleAnalyticsProfile objects and getSummary return one object of type GoogleAnalyticsSummary.

Now you got you services set up, lets create the calls and layout:
Service definitions and call responders, plus a radiobuttongroup we’re going to use, put this between the
1 2 3 4 5 6 7 8 | <fx:Declarations> <googleanalyticsservice:GoogleAnalyticsService id="googleAnalyticsService" fault="Alert.show(event.fault.faultString + '\n' + event.fault.faultDetail)" showBusyCursor="true"/> <s:CallResponder id="getProfilesResult"/> <s:CallResponder id="getSummaryResult"/> <s:RadioButtonGroup id="period" change="getDetails()"/> </fx:Declarations> |
Call the getProfiles method on initialize (add this to the initialize event of the application):
1 2 3 4 | protected function init():void { getProfilesResult.token = googleAnalyticsService.getProfiles(); } |
The getDetails method that calls the getSummary method:
1 2 3 4 5 6 7 8 9 10 11 12 | private function getDetails():void { if( profiles.selectedItem != null ) { var analyticsProfile:GoogleAnalyticsProfile = profiles.selectedItem as GoogleAnalyticsProfile; getSummaryResult.token = googleAnalyticsService.getSummary(analyticsProfile.tableId, period.selectedValue); } else { Alert.show("Select a profile from the list","Error"); } } |
And finally, a simple layout that displays everything:
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 | <s:HGroup paddingLeft="20" paddingTop="20"> <mx:DataGrid id="profiles" dataProvider="{getProfilesResult.lastResult}" width="150" click="getDetails()"> <mx:columns> <mx:DataGridColumn headerText="Profiles" dataField="title"/> </mx:columns> </mx:DataGrid> <s:VGroup> <s:HGroup> <s:RadioButton group="{period}" value="today" label="Today" selected="true"/> <s:RadioButton group="{period}" value="yesterday" label="Yesterday"/> <s:RadioButton group="{period}" value="week" label="Week"/> </s:HGroup> <s:Line width="200" stroke="{new Stroke(0x000000, 1, 1)}"/> <s:VGroup> <mx:Text text="Visits: {(getSummaryResult.lastResult as GoogleAnalyticsSummary).visits}"/> <mx:Text text="Pageviews: {(getSummaryResult.lastResult as GoogleAnalyticsSummary).pageViews}"/> <mx:Text text="Time on site: {(getSummaryResult.lastResult as GoogleAnalyticsSummary).timeOnSite}"/> <mx:Text text="Pages per visit: {(getSummaryResult.lastResult as GoogleAnalyticsSummary).pagesPerVisit}"/> </s:VGroup> </s:VGroup> </s:HGroup> |
You’re done, check my sample application, just select www.flex-blog.com in the DataGrid to view the summary for today. Use the RadioButtons to get a summary for yesterday or for the whole week. You can use right-mouse->view source to see the complete source code.
Note: My source code contains two extra methods, one result handler on the
Related posts:
- TinyURL usage with Flash Builder
- Using ASDoc as an External Tool in Flash Builder 4
- Using States in Flash Builder
- Flex 4 / Flash Builder 4: baseColor changed to chromeColor
- Call Javascript function from Flex / Flash Builder (AS3)
Comments
10 Responses to “Connect to Google Analytics from Flash Builder”



(
Hi, can you please help me. I want to log in to my Google Analytic Account by melodramatically from a FLEX. But I could not log in to my account. I am using FLEX 3.0. It will be very very helpful if you give me the code for that in AS 3.0
Hi Anirban,
Please note that you can see the complete source of our example here. (Use Right Mouse Click -> View Source).
Hope this will help you!
Roelof
Everything goes to plan unitl it’s time to insert the two values for getSummary, I enter ga:’id number’ and ‘today’ hit next and I get the error message
“Undefined index: gavisits in analytics_php.php on line 323″
Any ideas on how to fix this?
Hi Mike,
Are you sure that the index parameter is filled? If you would like more people to look into this, please open a topic in our forum!
Cheers,
Roelof
@ Mike
Don’t use ‘today’ use ‘yesterday’ or ‘week’. My guess is that google can’t report today but only up to yesterday. I know that the tracker for flash takes a day to start tracking.
Hi!
There is a little problem. How to fix input types of parameters in service’s function? I set the types, then change something in the service’s text, save service and Flash Builder 4 resets all types to Object.
If you want to make sure that parameters stay typed like you want, make sure they are types on the server (php) side as wel. See my answer on the forum:
http://www.flex-blog.com/forum/?vasthtmlaction=viewtopic&t=3.0
hi
first thanks for this.
i am a new user for flash builder or flex. i am more used to flash, so i hope my question is not stupid.
i followed the tutorial and when i have put the code for :
i get the error that: “The prefix “googleanalyticsservice” for rlement “googleanalyticsservice:GoogleAnalyticsService” is not bound”.
what am i doing wrong?
the index.php works fine, so the classes does connect right to analytics.
best regards
Yeah, I have the same probem.
Did you find a solution to this?
Also…the step where, “Repeat the steps for the second method. One of the methods needs two input parameters (period and tableId), a valid value for period is ‘today’, a valid tableId can be found by running the index.php file.”
I’d just represent the second form of ‘Configure Data Types’.
…say, “Go to this URL: http://localhost/FOLDER/createdIndex.php“