Flex Blog

Search:
  • Home
  • Examples
    • Thumb

      Flex Examples

      Check out our Flex Examples!

    • Thumb

      Flash Builder Examples

      Check out our Flash Builder Examples!

    • Thumb

      AIR Examples

      Check out our AIR Examples!

    • Thumb

      Flex Mobile Examples

      Check out our Flex Mobile Examples!

    Adobe® Flex, Adobe® Flash Builder and Adobe® AIR are registered trademarks of Adobe Systems.
  • Components
    • Thumb

      WP Flex Contact Form

      Check out our WP Flex Contact Form!

    • Thumb

      Flash CountDown Plugin

      Check out our Flash CountDown Plugin!

    This is an overview of all our Flash/Flex based Components.
  • Jobs
  • Flex Books
  • Forum
  • Contact Us
Subscribe to Flex BlogSubscribe
  • Examples
  • iOS
Browse > Home / Examples / Connect to Google Analytics from Flash Builder

Connect to Google Analytics from Flash Builder

11 November 2009

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:

Flex Project Settings 1

Klik Next and configere your server:

Flex Project Settings 2

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:

  1. analytics_api.php
  2. GoogleAnalyticsProfile.php
  3. 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:

Connect to PHP 1

Browse to the GoogleAnalyticsService.php on you local webserver and accept the default settings or change them if you want:

Connect to PHP 2

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:

Configure return type 1

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

Configure return type 2

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

Configure return type 3

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.

Configure return type 4

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 tag:

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 and one filter function on the ArrayCollection. I added this to filter out other analytics profiles besides the Flex-Blog.com one.

Related posts:

  1. TinyURL usage with Flash Builder
  2. Using ASDoc as an External Tool in Flash Builder 4
  3. Using States in Flash Builder
  4. Flex 4 / Flash Builder 4: baseColor changed to chromeColor
  5. Call Javascript function from Flex / Flash Builder (AS3)

Written by Arjan · Filed Under Examples 

Was this post useful to you?

Please rate this post, follow us @ twitter, or link to this page from your website!

1 Star2 Stars3 Stars4 Stars5 Stars (4 votes, average: 4.75 out of 5)
Loading ... Loading ...

774136b18faf06be43436f9516cd8aeedelicious

Comments

10 Responses to “Connect to Google Analytics from Flash Builder”

  1. Anirban Paul on December 1st, 2009 11:37 am

    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

  2. Roelof on December 1st, 2009 5:49 pm

    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

  3. Mike on May 13th, 2010 4:35 am

    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?

  4. Roelof on May 15th, 2010 4:40 pm

    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

  5. Wesley DuSell on May 25th, 2010 11:24 am

    @ 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.

  6. Roma on May 27th, 2010 7:13 am

    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.

  7. Arjan on June 2nd, 2010 9:57 am

    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

  8. ron on December 26th, 2010 1:08 pm

    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

  9. Alkoty on March 5th, 2011 2:20 am

    Yeah, I have the same probem.

    Did you find a solution to this?

  10. Alkoty on March 5th, 2011 2:24 am

    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“

Get Adobe Flash player

  • +1?

  • Support Flex Blog!

  • $ 13 raised
    • 2012/01/13 8:22 PM Russell Brown donated $ 3.00
    • 2011/10/31 4:43 PM Steve Dakin donated $ 5.00
    • 2011/05/11 3:37 PM Roelof Albers donated $ 5.00
  • Stay in touch!

  • Popular Tags

    • AdvancedDataGrid
    • AIR
    • ArrayCollection
    • baseColor
    • Button
    • CursorManager
    • DataGrid
    • Dynamic
    • Effects
    • File
    • FileStream
    • Flash Builder
    • Flash Builder 4
    • Flex 4
    • Flex Mobile
    • Framework
    • Icon
    • Image
    • itemRenderer
    • LinkBar
    • Mobile
    • PHP
    • ProgressBar
    • Repeater
    • Style
    • SWIZ
    • Timer
    • Tree
    • Twitter
    • ViewStack
  • Advertisements

  • Recent Posts

    • Spooky Frenzy – iPad Game
    • Fountain Example
    • Reading & Writing files in Adobe AIR
    • CheckBox in List using MobileIconItemRenderer for Flex Mobile
    • Data Dependent decoratorClass in MobileIconItemRenderer Example
    • Flex 4 Resize Effect Example
    • Jump to next field using the Focus Manager
    • Searching Data using a Class Example
    • Flex Mobile: Two finger tap gesture to toggle actionBar visibility in a View (AIR for Android)
    • TabbedMobileApplication Example in Flex Mobile (AIR for Android)
  • Categories

    • Examples
    • Guest Poster
    • iOS
  • Archives

    • September 2011
    • July 2011
    • May 2011
    • March 2011
    • February 2011
    • November 2010
    • October 2010
    • September 2010
    • August 2010
    • June 2010
    • May 2010
    • April 2010
    • March 2010
    • February 2010
    • January 2010
    • December 2009
    • November 2009
    • October 2009
    • March 2009
    • February 2009
  • Blogroll

    • Adobe Flex Jobs
    • NL for Business
  • Meta

    • Register
    • Log in
    • WordPress
    • XHTML

Copyright © 2010 Flex Blog · Adobe® and Adobe® Flex are registered trademarks of Adobe Systems.

WordPress Adobe Flex Adobe Flash Builder Adobe AIR Creative Commons License

  • Popular Posts

    • Progressbar in Datagrid Example 13 votes, average: 5.00 out of 513 votes, average: 5.00 out of 513 votes, average: 5.00 out of 513 votes, average: 5.00 out of 513 votes, average: 5.00 out of 5 (5.00 out of 5)
    • Data Dependant Tree Icon with Tree in AdvancedDataGrid with iconFunction 8 votes, average: 5.00 out of 58 votes, average: 5.00 out of 58 votes, average: 5.00 out of 58 votes, average: 5.00 out of 58 votes, average: 5.00 out of 5 (5.00 out of 5)
    • List Directory with AIR in Flex 4 7 votes, average: 5.00 out of 57 votes, average: 5.00 out of 57 votes, average: 5.00 out of 57 votes, average: 5.00 out of 57 votes, average: 5.00 out of 5 (5.00 out of 5)
    • Flex FlashVars in AS3 Example 7 votes, average: 5.00 out of 57 votes, average: 5.00 out of 57 votes, average: 5.00 out of 57 votes, average: 5.00 out of 57 votes, average: 5.00 out of 5 (5.00 out of 5)
    • Flex Dynamic Chart Example 4 votes, average: 5.00 out of 54 votes, average: 5.00 out of 54 votes, average: 5.00 out of 54 votes, average: 5.00 out of 54 votes, average: 5.00 out of 5 (5.00 out of 5)