TwitterLogger Class To Full Twitter API Access From ActionScript 3

For the last couple of days I have been working with Twitter API, trying to make the api usable for flash in browser the same way as FacebookLogger (Facebook API extension) is. Guess what, I did it! I created TwitterLogger. TwitterLogger class extends official TwitterScript (ActionScript API) and implements OAuth (and TwitterOAuth – PHP Library to support OAuth for Twitter’s REST API) authorization protocol to gain full access into Twitter API from flash in browser.

TwitterScript already contains full api access but some call requires authorization that brings you into 2 issues:

  • obtain username and password from user – unwanted operation
  • crossdomain authorization – only possible for AIR due to Twitter crossdomain policy restriction

Sets the username and password for this instance, setting the flag to use https to true. Note that this will not work at all in Flash player 9.0.115, and will only work in later versions if the remote server has the <code>allow-http-request-headers-from</code> tag set permissively in its crossdomain policy file. For more information see: Unfortunately Twitter has it set to (as of Sept 2008): <allow-http-request-headers-from domain=”*” headers=”*” secure=”true”/> which only lets in the twitter badges originating from Since that’s the case, authentication will only work for AIR.
If you use this for Flash in the browser, it will fail over to the browser’s basic auth without an issue. (described in com.twitter.api.Twitter.setAuthenticationCredentials())

This requires another method on scene. Since Twitter introduced OAuth it is possible to get connection into Twitter API via this open source secure authorization. To communicate with Twitter we gonna use server side proxy. So lets start:

1. Register a new twitter application, these settings are crucial:

Application Website:
Application Type: Browser
Callback URL:
Default Access type: Read & Write
Use Twitter for login: Yes

2. download OAuth.php and twitteroauth.php from TwitterOAuth into /library/ dir

3. create /config.php file containing:

// fill your own Twitter application Consumer key
define('CONSUMER_KEY', 'qSoF24kOuNCiPCQwWfe0yQ');

// fill your own Twitter application Consumer secret
define('CONSUMER_SECRET', 'xahJ7hpJeevq411N5NQXcTbJ5hQFWDwidtTpsbc');

// fill your Twitter application Callback URL
define('OAUTH_CALLBACK', '');

4. /connect.php file:

header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0");
header("Pragma: no-cache");
header("Last-Modified:".gmdate("D, d M Y H:i:s")." GMT");
header('Content-Type: text/html; charset=utf-8');

require_once 'config.php';
require_once 'library/twitteroauth.php';

$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
$request_token = $connection->getRequestToken(OAUTH_CALLBACK);

$_SESSION['oauth_token'] = $token = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];

$url = $connection->getAuthorizeURL($token);
header('Location: ' . $url);

5. /callback.php

require_once 'config.php';
require_once 'library/twitteroauth.php';

$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
$access_token = $connection->getAccessToken($_REQUEST['oauth_verifier']);
$_SESSION['access_token'] = $access_token;

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "">
<html xmlns="" xml:lang="sk" lang="sk" dir="ltr"> 
	<script type="text/javascript"> 
		if(window.opener && window.opener.confirmTwitterConnection)
<p>You may now close this window.</p>

6. /proxy.php

require_once 'config.php';
require_once 'library/twitteroauth.php';

$access_token = $_SESSION['access_token'];
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']);

$parameters = array();
foreach($_POST as $key => $value)
if($key != "method" && $key != "url")
	$parameters[$key] = $value;
echo $connection->OAuthRequest($_POST['url'], $_POST['method'], $parameters);

7. Create new flex project

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="" layout="vertical"

    private var connector:String = "";
    private var proxy:String = "";
    private var twitter:TwitterLogger = new TwitterLogger(connector, proxy);
    private var lastCallResult:String = "";
    private function init():void
        twitter.addEventListener(TwitterLoggerEvent.CALL_COMPLETE, callComplete); 
    private function callComplete(event:TwitterLoggerEvent):void
        lastCallResult =;
    <mx:Button label="connect" click="twitter.connect()" />
    <mx:Label text="{twitter.connected ? 'connected' : 'not connected'}" />

    <mx:TextInput id="status" text="hallo world status"/>
    <mx:Button click="twitter.setStatus(status.text)" label="update status"/>

<mx:TextArea text="{lastCallResult}" width="100%" height="100%"/>

8. Download TwitterScript classes and make sure to rewrite private to protected namespace for these methods and vars in com.twitter.api.Twitter class:

protected var loaders;
protected function addLoader(...
protected function errorHandler(...

9. Download, and classes into your flex project under the correct namespace (sk.yoz…)

10. Make sure your index.html wrapper class defines allowScriptAccess and flash id and name, it may look like something like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" ""> 
<html xmlns="" lang="cs" xml:lang="cs"> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <meta http-equiv="Content-language" content="cs" />
    <script type="text/javascript" src="js/swfobject.js"></script>
    <script type="text/javascript">
        var flashvars = {}
        var params = {
            allowScriptAccess: "sameDomain"
        var attributes = {
            id: "sz",
            name: "sz"
        swfobject.embedSWF("App.swf", "alternative", "100%", "100%", "9.0.124",
            "expressInstall.swf", flashvars, params, attributes);
		body {margin:0px;overflow:hidden;}
		html, body, object, embed {width:100%;height:100%;outline:none;}
 <body style="text-align:center;">
    <div id="alternative">
        <a href="">
            <img src="" alt="Get Adobe Flash player" />

Publish html template and copy all flash files into your application website. You should now have this structure in there (


If you do same changes, make sure all these files are on same domain because it uses PHP Session to store token and JavaScript between-window communication. Now lets see our application (

To update your satus, first click on connect, window popup opens and redirects itself into Twitter asking for permission. After you click allow in popup, popup closes itself and change status in flex near connect button to “connected”. Now you are ready to update your Twitter status. TextArea contains last Twitter appi call reply (after status update). The good thing with OAuth is, it remembers your acception for some time, so you do not have to click allow every time…

There may occur error on Twitter popup saying:

This page is no longer valid. It looks like someone already used the token information you provided. Please return to the site that sent you to this page and try again … it was probably an honest mistake.

I guess it may have something to do with cached request on connect.php, so I added few expire headers into it.

Where to go from here:

59 comments so far

  1. Shane September 26, 2013 10:54

    hi josef

    i tried with“#spiderman”)

    but it is giving me this
    Implicit coercion of a value of type String to an unrelated type com.twitter.api:TwitterSearch.

  2. Jozef Chúťka September 26, 2013 11:25

    hi Shane,
    have a closer look at and search() method:
    means you have to create instance of TwitterSearch and pass it into the search method

  3. Shane April 11, 2014 11:17

    @Boleslav how did u solved the issue of popup window of this “You may now close this window.” message

    @Jozef my callback url in twitter app is
    when i test my app in this link it works fine i connect to twitter the popup goes and my app loads.

    but the same thing when i try with the popup window stays and message appears You may now close this window and nothing happens

    will u help me in solving this

  4. Jozef Chúťka April 12, 2014 09:20

    hi Shane, there might be a crossdomain issue b/c of http vs. https. Make sure your main app is on the same protocol as twitter callback. If not, redirect twitter callback to proper protocol. You can use chrome developer tools to debug the crossdomain or any other javascript issue

  5. Shane April 15, 2014 09:27

    hi josef thanks for the reply

    I have my proxy.php,config.php,connect.php,App.swf and callback.php on the same domain folder In newdata folder all the files are there.

    I have crossdomain file on

    My callback url in twitter apps is

    when i try with it works
    but this doesnt work it shows you may close the window text.

    dont knw much about php so dont know how to redirect twitter callback to proper protocol.

  6. Jozef Chúťka April 15, 2014 11:39

    as you write, part of your stuff is on http while callback is https which may cause some crossdomain issues. You either put all your stuff to http or https. If that is not possible you might want to redirect callback from one to another, do not forget to redirect all necessary GET/POST params as well, you might want to handle it in url fragment so you do not expose sensitive data over http. redirect in php can be done via header() method, you can also do redirect via javascript, or refresh meta in html header

  7. Shane July 12, 2014 13:29

    hi josef is there any method in ur api to logout a given user twitter session

  8. Jozef Chúťka July 14, 2014 10:23

    hi Shane,
    – logout process is very well described in
    – you can also follow comments history on this page (search “logout”)

  9. shane July 15, 2014 13:46

    hi josef thanks for the reply
    i am loading username data of my twitter acc i have a logout btn to log out of twitter but dont knw how to do that. i am not good in php

    i tried this
    function onBtn(e:MouseEvent):void

    i looked through this but dont understand that.

Leave a comment

Please be polite and on topic. Your e-mail will never be published.