How to connect to Google Analytics Data API in Flash

In one of my previous post, I explained how to connect to Google Analytics Data API in AIR. The problem with that way of connecting was that it only worked in AIR. In Flash it works locally, but as soon as you put in on your web server it stops working. Not it is cool to build an AIR (desktop) application that pulls data from Google Analytics, but it would also be cool to build a web application that does the same thing. Well I found out how to do just that. It is a bit more complicated because it involves a bit of server side coding, in this case PHP.

How the process works is that first you login to Google Analytics, Google will then send you a token that you must use when asking for data. So we will have two simple PHP files; one to login in and one to ask for data.

The first one looks like this:

<?php
//this file is called get_token.php
$user = $_REQUEST[user];
$pass = $_REQUEST[pass]
 
require_once 'curl.php';
$curl = new Curl;
$response = $curl-&gt;post('https://www.google.com/accounts/ClientLogin', array(accountType => "GOOGLE",  Email =>$user, Passwd => $pass, service => "analytics", source => "zedia-GAStats-0" ));
$tempArray = explode("Auth=", $response);
?>
<root>
	<token><?php echo ($tempArray[1] ); ?></token>
</root>

The second one looks like this:

<?php
//this file is called call_ga.php
require_once 'curl.php';
$url = $_REQUEST["url"];
$token = $_REQUEST["token"];
 
$curl2 = curl_init();
curl_setopt($curl2, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl2, CURLOPT_HEADER, "0");
curl_setopt($curl2, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl2, CURLOPT_URL, $url);
 
curl_setopt($curl2, CURLOPT_HTTPHEADER, array('Authorization: GoogleLogin auth=' . $token));
$response2 = curl_exec($curl2);
echo ($response2);
?>

As you can see to make my calls to Google I am using the cURL library that is usually already installed on your server if you have PHP. Also for the get_token.php I am also using the Curl class, made by Sean Huber, that just makes it easier to work with cURL.  Upload these files to your server. Now that we have the server side figured out, we can move on to the Flash part;  here it is:

package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLVariables;
import flash.text.TextField;
 
public class Main extends Sprite
{
  private var loader:URLLoader;
  private var _loader2:URLLoader;
  private var _textField:TextField;
  private var _token:String;
  private var _buffer:String = "";
  public function Main():void
  {
    loader = new URLLoader();
    loader.addEventListener(Event.COMPLETE, _onTokenLoaded, false, 0, true);
   //this call will load the token
 
    loader.load(new URLRequest("http://www.YOUR_URL_WHERE_THE_PHP_RESIDE.net/get_token.php?user=YOUR_USERNAME&pass=YOUR_PASSWORD"));
 
    _textField = new TextField();
    _textField.height = 300;
    _textField.width = 300;
    _textField.multiline = true;
    _textField.wordWrap = true;
 
    addChild(_textField);
  }
 
  private function _onTokenLoaded(event:Event):void {
    var tempString:String = String(loader.data);
    tempString = tempString.substring(1, tempString.length);
    var tempXML:XML = XML(tempString);
    _token = tempXML.token;
 
    _textField.text = _token;
 
    _loader2 = new URLLoader();
    _loader2.addEventListener(Event.COMPLETE, _onFeedLoaded, false, 0, true);
 
    var request:URLRequest = new URLRequest("http://www.YOUR_URL_WHERE_THE_PHP_RESIDE.net/call_ga.php");
    var urlVar:URLVariables = new URLVariables();
    urlVar.token = _token;
    urlVar.url = "https://www.google.com/analytics/feeds/accounts/default";
    request.data = urlVar;
 
    _loader2.load(request);
  }
 
  private function _onFeedLoaded(event:Event):void {
    _textField.text = String (_loader2.data);
  }
 }
}

What you basically do is that you use your server to do all the communication between the Flash and Google. Everytime you will want a different feed to get different data you will call the call_ga.php file. It is that simple. If you have any question on this feel free to ask them in the comments.

, , , , , ,

  1. #1 by Jens Wegar - June 6th, 2009 at 05:28

    Hey,

    great that you found a solution to this, although a bit of a let down that it has to involve server side scripting. But still, better than nothing. :)

    In the URLRequest to get_token.php you send the username and password as GET variables, apparently in plain text. Why not store those in the PHP script on the server side instead so you don’t have to send them across the wire? Would be one less potential security risk.

    btw. Could the reason for not being able to call GA API directly from flash in the browser be that GA doesn’t have a crossdomain policy file? I haven’t tried the GA API myself yet, so just wondering…

  2. #2 by zedia.net - June 7th, 2009 at 15:42

    @ Jens Wegar
    I pass the username and password because I was lazy, but you could pass them as POST variables. Why I want to pass them is because I wanted to show that you could build a web application where the users could enter in their username password and then the application would connect to Google. It’s just a bit more generic.

    As for why you can’t call directly I don’t think it has to do with crossdomain; GData also offer other means to login to their service for web application, but it involves redirecting to a Google page and then redirecting back to your application which I think is a bad user experience.

  3. #3 by patrick - October 5th, 2009 at 14:21

    I was really happy to found your example.
    Are you use that the first Script get_token.php is working well?
    In my Case im not getting any feedback. $response Variable is not returning anything. I fixed the request with parts of following Post: http://entwickler-forum.de/showpost.php?p=152605&postcount=2.
    I suppose I did a mistake somewhere…if I take in consideration my poor knowledge of php.

  4. #4 by MM - October 5th, 2009 at 17:46

    Hey,

    great that you found a solution to this, although a bit of a let down that it has to involve server side scripting. But still, better than nothing. :)

    In the URLRequest to get_token.php you send the username and password as GET variables, apparently in plain text. Why not store those in the PHP script on the server side instead so you don’t have to send them across the wire? Would be one less potential security risk.

    btw. Could the reason for not being able to call GA API directly from flash in the browser be that GA doesn’t have a crossdomain policy file? I haven’t tried the GA API myself yet, so just wondering…

  5. #5 by Jon - November 30th, 2009 at 14:29

    Im sorry but these instructions are a waste of space, the php code gives parse errors, there are no instructions how to use the package within Flex. A complete waste of time, learn how to post code

  6. #6 by zedia.net - November 30th, 2009 at 16:31

    @Jon
    Haha, thank you for your comment. There is indeed an error in the code, WordPress doesn’t like greater than signs. I will correct this. As for Flex, this is independent on either Flash or Flex because it is just pure ActionScript so I don’t understand what I need to explain specifically for Flex. I hope you find reasons to smile elsewhere.

  7. #7 by zedia.net - November 30th, 2009 at 16:49

    Actually WordPress doesn’t like the php tags so if I edit the post, it will eat some part of it so in the first code segment it should be $response = $curl->post (…)

  8. #8 by Raj Dye - December 1st, 2009 at 06:18

    On my server PHP5 hosted at Hostgator I had to change the first file to:

  9. #9 by alex_mc - January 13th, 2010 at 06:04

    When you use a GET or POST request to send an Authorization header (using XML.addRequestHeader() and LoadVars.addRequestHeader() in ActionScript 2.0, or URLRequest.requestHeaders in ActionScript 3.0), the request fails and the header is not sent.

    Starting with Adobe Flash Player 9.0.115.0 the Authorization header was added to the blacklist of HTTP headers and, only in this version, was blocked by Flash Player

    So we should have one, two and more simple at least PHP files :) for tricks like that.

  10. #10 by Sharedtut - February 4th, 2010 at 12:20

    You’ve done a great job, thank you for putting this together and sharing it.

  11. #11 by Stefan H. - July 26th, 2010 at 05:47

    Hi thx a lot !

(will not be published)
Subscribe to comments feed