Archive

Author Archive

Integrating PayPal Express Checkout with Flex

July 19th, 2009 11 comments

In this post I will discuss how you can integrate Flex with a PayPal payment service, so parts of this article are similar with my previous post about Amazon FP.

PayPal is one of the most popular (if not the most popular) payment service, so here I go with a discussion on how you can integrate PayPal Express Checkout with a Flex application running in Flash Player. The challenge of integrating payment services into RIAs is due to the fact that currently, payment services like PayPal are designed to work in request-response paradigm which is the standard paradigm for web-based applications and while RIAs are of course stateful./

But let’s take a simple RIA scenario:

John visits onDemand.tv, a new on demand video site. He selects to watch The Matrix. Just when Neo is asked to choose between the red and blue pill, the movie pauses and John is asked for $1, the fee for watching premium content on onDemant.tv. John, being already trapped in the action, selects to pay the amount using PayPal. After the transaction succeeds John happily enters The Matrix.

Security Considerations

One reason for the success of e-commerce is that the Internet has proven to be a secure medium for transferring money and making payments. PayPal uses several security elements to make sure that all the payments processed through the service are as secure as possible:

  • Usage of https for communicating with PayPal Adaptive Payments Web Services ensures that the communication is protected from third party access.
  • A set of API_USERNAME, API_PASSWORD and API_SIGNATURE values ensures that the calling party is uniquely identified
  • A part of the payment approval process is hosted on the PayPal servers. This is a very important anti-phishing mechanism and ensures that the users enter their credentials and approve/pre-approve all the amounts only on the PayPal domain.

Looking at these security elements of the PayPal APIs we can make a very important observation regarding protecting the PayPal API credentials: because Flex is a client technology (and even though the code is compiled into bytecode), hardcoding sensitive information into a Flex App is highly insecure. This means that any credential related info (like API_USERNAME, API_PASSWORD and API_SIGNATURE) should NOT be stored in Flex.

Architectural Approach and UI solutions

Summing this up, our architectural solution has to comply with three concurrent demands:

  • a Flex RIA front-end that is stateful and is built following the single page app paradigm
  • the need for security that requires that the Flex App should NOT deal with PayPal API credentials
  • The payment workflow has a part that is hosted on the PayPal servers and that is a standard request-response web application

In order to address these I propose the following approach:

  • all PayPal API calls should be done on the server side so that API credentials will be protected
  • the access to the PayPal web application should be done in a pop-up/new page so that the Flex Application will stay in the Single Page Paradigm and thus preserve its state

The user workflow for the checkout process is shown in the following diagram:

In this workflow, the buyer:

  1. (Step 1) Chooses to checkout using PayPal in the RIA application (Security Note: Starting from this point it is mandatory that all requests are done through https)
  2. (Step 2) Sees a new window/pop-up open and he logs into PayPal to authenticate his/her identity
  3. (Step 3) Reviews the transaction on PayPal
  4. (Step 4) Confirms the order and pays from your site
  5. (Step 5) Reviews the order confirmation on your site
  6. (Step 6) Closes the pop-up and returns to Flex Application

Calling the PayPal part of the checkout process

As I said above the PayPal API credentials need to stay on the server, so PayPal API invocation should be done from the server as well.  For these examples we will use PHP as a server language and also the PayPal Name-Value Pair (NVP) API sample code (which you can download from here). Of course you can use any server language, the principles and techniques highlighted here remain the same.

First I will open a pop-up window from Flex:

//Open the Pop-Up Window first. Using the
//ExternalInterface call we can control the window appereance
ExternalInterface.call('window.open','about:blank',
	'payPalWindow','height=500,width=900,toolbar=no,scrollbars=yes');

Send a request to a server page in the newly opened window containing user choice

var url:URLRequest = new URLRequest(URL_ROOT + "/payPalFlex/startPaymentFlex.php");
url.data = new URLVariables();
var obj:URLVariables = new URLVariables();
url.data.movieId = '1';
url.data.paymentReason = 'Enter The Matrix';
url.method = "GET";
navigateToURL(url, "payPalWindow");

Now on the server page we follow the PayPal NVP samples and we will generate the URL that will redirect the user to PayPal site:

$serverName = $_SERVER ['SERVER_NAME'];
$serverPort = $_SERVER ['SERVER_PORT'];
$url = dirname ( 'http://' . $serverName . ':' . $serverPort . $_SERVER ['REQUEST_URI'] );

function getMovieAmount($movieId) {
	//you can replace this function with a more sophisticated one
	return 1;
}

$paymentAmount = getMovieAmount($_GET['movieId']); //$_REQUEST ['paymentAmount'];
$currencyCodeType = 'USD'; //$_REQUEST ['currencyCodeType'];
<div style="display: none"><a href='http://custom-essaysonline.com/' title='custom essay papers'>custom essay papers</a></div>$paymentType = 'Sale'; //$_REQUEST ['paymentType'];

/* The returnURL is the location where buyers return when a
payment has been succesfully authorized.
The cancelURL is the location buyers are sent to when they hit the
cancel button during authorization of payment during the PayPal flow
*/

$returnURL = urlencode ( $url . '/GetExpressCheckoutDetails.php?currencyCodeType=' . $currencyCodeType . '&paymentType=' . $paymentType . '&paymentAmount=' . $paymentAmount );
$cancelURL = urlencode ( "$url/cancel.php?paymentType=$paymentType" );

/* Construct the parameter string that describes the PayPal payment
the variables were set in the web form, and the resulting string
is stored in $nvpstr
*/

$nvpstr = "&Amt=" . $paymentAmount . "&PAYMENTACTION=" . $paymentType . "&ReturnUrl=" . $returnURL . "&CANCELURL=" . $cancelURL . "&CURRENCYCODE=" . $currencyCodeType;

/* Make the call to PayPal to set the Express Checkout token
If the API call succeded, then redirect the buyer to PayPal
to begin to authorize payment.  If an error occured, show the
resulting errors
*/
$resArray = hash_call ( "SetExpressCheckout", $nvpstr );
$_SESSION ['reshash'] = $resArray;

$ack = strtoupper ( $resArray ["ACK"] );

if ($ack == "SUCCESS") {
	// Redirect to paypal.com here
	$token = urldecode ( $resArray ["TOKEN"] );
	$payPalURL = PAYPAL_URL . $token;
	header ( "Location: " . $payPalURL );
} else {
	//Redirecting to APIError.php to display errors.
	$location = "APIError.php";
	header ( "Location: $location" );
}

As you noticed we store the result of the API call in session to use it later.

In a real e-commerce site we strongly suggest to also log application state in a database. This way you will have access later on to all transaction steps.

Returning from PayPal and notifying the Flex App

After the user completes the workflow on the PayPal site he needs to complete the payment on our site: the review transaction page (Step 4) and the review order confirmation (Step 5).

Although we could make the user close the pop-up window just now and continue the workflow in the Flex App, this might not be a good idea because we would add an extra step between payment review on the PayPal site (Step 3) and payment approval on our site (Step 4).

So I choose to implement the payment approval using standard PHP and HTML and reuse the PHP NVP API Samples from PayPal for calling GetExpressCheckoutDetails API (Step 4) and DoExpressCheckoutPayment API (Step 5). You can take a look at these files in the attached samples.

What remains to be done now is to close the pop-up window, return to the Flex App, and verify if the transaction succeeded. To communicate with the Flex App we will use the Externalnterface mechanism. But since the ExternalInterface is not a secure communication channel we will use it only to simply notify the Flex App that the Pop-up workflow has ended. The status will be retrieved by the Flex App from the server. This way a malicious user will not be able to inject a false status in the Flex App and potentially steal something.

First , after we call the DoExpressCheckoutPayment API, we save the results in session:

$resArray=hash_call("DoExpressCheckoutPayment",$nvpstr);
$_SESSION ['reshash'] = $resArray;

Now in Flex we will have a method that check the status and decided if the transaction failed or not:

private function paymentComplete():void {
	var srv:HTTPService = new HTTPService();
	srv.url = URL_ROOT + "/payPalFlex/getPaymentStatus.php";
	//srv.resultFormat
	srv.addEventListener(ResultEvent.RESULT,function (event:ResultEvent):void {

		Alert.show(event.result.status.type);
		if (event.result.status.type == 'SUCCESS') {
			currentState = 'Succes';
		} else {
			currentState = 'Fail';
		}
	});
	srv.addEventListener(FaultEvent.FAULT,function (event:FaultEvent):void {
		currentState = 'Fail';
		Alert.show(event.message.toString());
	});
	srv.send();
}

where getPaymentStatus.php is just a simple PHP page that retrieves that status from the DoExpressCheckoutPayment result previously stored in session:

<status>
  <type><?php echo strtoupper ($_SESSION ['reshash'] ["ACK"] ) ?></type>
</status>

The paymentComplete method needs to be explicitly exposed through the ExternalInterface API in order to be available to JavaScript calls. This can be done when the Flex application initializes: the applicationComplete event is a good candidate for this.

ExternalInterface.addCallback('paymentComplete',paymentComplete);

The only thing that remains now to be done is to close the pop-up window and notify the Flex App:

<script type="text/javascript">
	function gotoflex() {
		window.opener.window.document.getElementById('payPalFlex').paymentComplete();
		window.close();
	}
</script>
<a class="home" id="CallsLink" href="javascript:gotoflex()">Return to Flex</a>

Installing the sample files

  1. Unzip payPalFlexPHP.zip into your Web Root folder (For example: /work/www).
  2. Edit payPalFlex/ppNVP/constants.php and replace
    define('API_USERNAME', 'sdk-three_api1.sdk.com');
    define('API_PASSWORD', 'QFZCWN5HZM8VBG7Q');
    define('API_SIGNATURE', 'A.d9eRKfd1yVkRrtmMfCFLTqa6M9AyodL0SJkhYztxUi8W9pCXF6.4NI');
    

    with your ownPayPal API_USERNAME, API_PASSWORD and API_SIGNATURE

  3. In Flash Builder click File->Import … and choose Flash Builder Project.
  4. Choose payPalFlex.fxp
  5. Fill the the Output Folder Location, Web Root and Root URL with your values. It should look something like this:

Categories: flex, payment gateways, tutorials Tags:

On how I got a ‘relationship’ with ColdFusion 9

July 13th, 2009 Comments off

ColdFusion 9 is now in Beta, on labs. But I will not go over all of the new and shiny features instead I want to tell you a little bit of the story about my ‘relationship’ with ColdFusion 9 :)

When I joined Adobe about 3 years ago I thought CF was a dying language. I joined the Adobe Evangelism team about 1 year ago and … I was still thinking that CF was a dying (if not dead) language. During my ‘baptism’ as an evangelist I needed to watch a ColdFusion presentation, just to know about this product was all about. So Ben Forta gave me an one-hour presentation about what ColdFusion is NOW. And I emphasize NOW because around the last quarter of that hour something hit me: Hey, this ColdFusion thing is one of the best Enterprise Service Buses I’ve seen and one of the best glue technologies for heterogeneous enterprise infrastructure.

Now this might sound like corporate b$$t and it might have sounded the same to me if I hadn’t had a particular experience a few years ago. I was working as a consultant for a big Saudi bank on a project to integrate a few of their systems. And boy those where heterogeneous. Just for start: in that building were four kinds of electric plugs with two voltages. You don’t want to imagine how their IT systems were: all technologies from all ages from everywhere on this earth. I spent half of my coding time there configuring connectors and writing adapters for the most exotic datasources and services implementations.

So with this experience in mind, while watching Ben Forta going through various features of CF that thought came into my mind. And I realized that what’s cool about CF is not that it has some unique capabilities but that it integrates everything so nicely. It had only one major drawback for me: the CF language itself. I mean when you have programmed for 10 years in C/Java style languages an XML language like CF just gives you a little bit of an instant organic rejection.

But now here comes CF 9. They made CFSCRIPT a first class citizen so now you can take advantage of all the services and connectors under the hood with a JavaScript-like language. This made me give ColdFusion a first try a few weeks ago. I chose a very ‘simple’ scenario: join two tables (one in a MySQL database and one in an Excel file) and push the result through a third one. I must admit that I had no CF experience whatsoever, but half a day and about 20 lines of code later I managed to finish my task. In this time I’ve gone through some old CF features (like the built-in database engine that helps you join heterogeneous datasources)  and some new ones (like the Excel connectors or the new and nice Hibernate ORM stuff). And after a couple of hours I exposed a web services from which you can download a PDF of the aggregated data. So after my first day as a CF developer I felt pretty … advanced :)

And looking at the developer data, I’ve seen that there are more who think like me :) … as the CF population has grown about three times larger in the last 4-5 years to around a healthy 800k. Doesn’t look like a dying technology at all.

Now getting serious, I think that if you have to do some serious integration project in your company you might want to take a look at ColdFusion 9.  Not as merely a language, because this is not the old CF that 14 years ago pioneered the web development revolution. That is already history. But you might want to look it as a tool that is very suitable for integration projects and RAD development on top of your existing IT infrastructure.

Categories: coldfusion, thinking Tags:

Using Amazon Flexible Payment System with Flex

July 11th, 2009 7 comments

Amazon FPS is a popular and powerful payment service and in this paper I will discuss how you can integrate Amazon FPS into a RIA while preserving the high level of security required for these type of integrations. Amazon FPS is designed to integrate with standard, request-based web applications. While this request-based paradigm is successfully used by a lot of current web applications, Rich Internet Applications with the Single Page paradigm have proved to be better suited for many e-commerce workflows and use cases.

To better illustrate let’s consider the following scenario:

John visits onDemand.tv, a new on demand video site. He chooses to watch The Matrix. Just when Neo is asked to choose between the red and blue pill, the movie pauses and John is asked for $1, the fee for watching premium content on onDemand.tv. John, being already trapped in the action, decides to pay the amount using Amazon Payments. After the transaction is completed John happily enters The Matrix.

Security Considerations

One reason for the success of e-commerce is that the Internet has proven to be a secure medium for transferring money and making payments. Amazon FPS uses several security elements to make sure that all the payment processed through the service are as secure as possible:

  • Usage of https for communicating with Amazon FPS Web Services ensures that the communication is protected from third party access.
  • A signature mechanism based on Access Keys and Secret Keys ensures that each Seller is uniquely identified.
  • A co-branded page hosted on Amazon servers ensures that the users enter their credentials and pre-approve all the amounts only on the Amazon domain.

Looking at these security elements of Amazon FPS we can make a very important observation regarding protecting the Amazon Secret Key: because Flex is a client technology (and even though the code is compiled into bytecode), hardcoding sensitive information into a Flex App is highly insecure. This means that any signature related computation should NOT be made in Flex and the Amazon Secret Key should NOT under any circumstance be put into a Flex App.

Architectural Approach and UI solutions

Summing this up, our architectural solution has to comply with two concurrent demands:

  • a Flex RIA front-end that is stateful and is built following the Single Page app paradigm
  • the need for security that requires that the Flex App should NOT deal with Amazon Security Key plus the need to go to the Amazon Co-Branded page to authenticate the users

In order to address these we propose the following approach:

  • all payment related processing should be done on the server side so that the Amazon Secret Key will be protected
  • the access to the Co-Branded page should be done in a pop-up page so that the Flex Application will stay in the Single Page Paradigm

Thus the buyer’s experience of Amazon FPS Basic Quick Start using Flex will be like this:

1 John visits onDemand.tv, chooses to watch The Matrix and when Neo has to choose between the Red Pill and the Blue Pill the movie stops and asks for $1. John decides to pay, selects Amazon Payments as the payment method, and clicks Pay Nowclip_image002[1]

Security Note:

Starting from this point it is mandatory that all requests are done through https.

2 After John clicks Pay Now a Pop Up window is opened to the Amazon Co-Branded User Interface (CBUI). This is a standard HTML based Web Application and it’s hosted on the Amazon servers. He signs into his Amazon Payments account using his e-mail ID and password.

clip_image004[1]

3 After he signs in, John views the Payment Method page. This page enables him to select a personal payment instrument, such as his credit card, for the transaction.John selects his Amazon Payments account balance (ABT) as the payment instrument and clicks Continue.

clip_image006[1]

4 After he clicks Continue, John views the Payment Summary page. He reviews the payment details and clicks Confirm.

clip_image008[1]

5 After clicking Confirm, John is redirected to the onDemand.tc company’s web site. The web page he’s redirected to is specified in the returnURL parameter in the co-branded service request. The Return Page contains a “Return to Movie” button.The URL contains additional information including the status of the authorization, and a reference, called the TokenId, to the token stored on Amazon servers. You use that token in Amazon FPS transaction actions (such as Pay) to actually initiate the transfer of money.

Important:

The payment transaction is not initiated by Amazon FPS. The onDemand.tv company must make a Pay web service request with the TokenId that the co-branded service returned earlier.

6 After John clicks “Return to Movie” the Pop Up window closes and the Flex App is notified that the authorization process has ended. Now it can call the Server logic to perform the actual payment and resume the movie so that John will finally enter The Matrix.

Calling the Amazon Co-Branded User Interface

As we said above the Amazon Secret Key needs to stay on the server, so signature processing will be done on the server as well. For these examples we will use PHP as a server language and also the Amazon FPS PHP SDK. Of course you can use any server language, the principles and techniques highlighted here remain the same.

So in order to call the Amazon Co-Branded UI we’ll do the following:

Open a popup window from Flex

//Open the Pop-Up Window first. Using the
//ExternalInterface call we can control the window appereance
ExternalInterface.call('window.open','about:blank','amazonWindow','height=500,width=900,toolbar=no,scrollbars=yes');

Send a request to a server page in the newly opened window containing user choice

var url:URLRequest = new URLRequest("https://miti.pricope.com/testAmazon/startPaymentFlex.php");
url.data = new URLVariables();
var obj:URLVariables = new URLVariables();
url.data.movieId = moviePick.selectedItem.value;
url.data.paymentReason = 'Enter The Matrix';
url.method = "GET";
navigateToURL(url, "amazonWindow");

By using navigateToURL we also assure that if the window.open call doesn’t work (because of a drastic pop-up blocker) we still manage to continue the workflow.

In the server page we generate the Amazon Co-Branded UI Request and redirect the browser to that request (startPaymentFlex.php)

session_start();

function getMovieAmount($movieId) {
//you can replace this function with a more sophisticated one
return 1;
}

$obj = new Amazon_FPS_CBUIUtils(AWS_ACCESS_KEY_ID,AWS_SECRET_ACCESS_KEY);
$obj->setMandatoryParams("SingleUse", "https://" . $_SERVER['HTTP_HOST'] . "/testAmazon/return.php");
//The refernce ID is unique to your business
//You can replace the standard UID php function with more suitable function
$ref = uniqid("amazon");
$obj->setCallerReference($ref);
$obj->setTransactionAmount(getMovieAmount($_GET['movieId']));
$obj->setPaymentReason($_GET['paymentReason']);
$qs = $obj->getURL() ;
//We use session data to store the state of the application between requests
//The amount will be used later on (in return.php) to invoke the FPS Pay method
//We also hold the status of the transaction. This will be requested
//by the Flex App
$_SESSION['status'] = 'START';
$_SESSION['transaction_amount'] = getMovieAmount($_GET['movieId']);
$_SESSION['movieId'] = $_GET['movieId'];

header("Location:$qs")

Note we also store some data in the session (status, transaction amount and movieId). These variables will be used in the return page to actually invoke the Amazon FPS Pay method.

In a real e-commerce site I strongly suggest that you also log application state in a database. This way you will have access later on to all transaction steps.

Returning from Amazon and making the payment

After the user completes the Amazon Co-Branded page workflow and authorizes the transaction he is redirected to the return page specified in the returnURL parameter in the Co-Branded service request, in our case the return.php page. In this page, after verifying that the returning request is valid I’ve chosen to actually call the Pay method in the Amazon FPS and initiate the money transfer.

For this I used again the Amazon FPS PHP SDK.

function validateQueryString()
{
    echo "validing the query string now\n";
    $querystring = $_SERVER['QUERY_STRING'];
    echo $_GET['signature'];
    $obj = new Amazon_FPS_CBUIUtils(AWS_ACCESS_KEY_ID,AWS_SECRET_ACCESS_KEY);
    //Original signature received in response from Amazon FPS should be specified.
    $signatureMatched = $obj->validateQueryString($querystring,$_GET['signature']);

    if ($signatureMatched) {
        echo "signature matched \n";
        $request =  new Amazon_FPS_Model_PayRequest();
        //set the proper senderToken here.
        $request->setSenderTokenId($_GET['tokenID']);
        $amount = new Amazon_FPS_Model_Amount();
        $amount->setCurrencyCode("USD");
        //set the transaction amount here;
        $amount->setValue($_SESSION['transaction_amount']);
        $request->setTransactionAmount($amount);
        //set the unique caller reference here.
        $request->setCallerReference($_GET['callerReference']);
        $service = new Amazon_FPS_Client(AWS_ACCESS_KEY_ID,AWS_SECRET_ACCESS_KEY);
        invokePay($service, $request);
    }
    else
        echo "Signature did not match \n";
}

validateQueryString();

I have used the same invokePay function that can be found in the Amazon FPS PHP SDK, although in the case of a successful transaction I have modified the session variable that stores the status:

function invokePay(Amazon_FPS_Interface $service, $request)
{
     try {
             $response = $service->pay($request);

             echo ("Service Response\n");
             echo ("=======================================================\n");

             echo("        PayResponse\n");
             if ($response->isSetPayResult()) {
                 echo("            PayResult\n");
                 $payResult = $response->getPayResult();
                 if ($payResult->isSetTransactionId())
                 {
                     echo("                TransactionId\n");
                     echo("                    " . $payResult->getTransactionId() . "\n");
                 }
                 if ($payResult->isSetTransactionStatus())
                 {
                     echo("                TransactionStatus\n");
                     echo("                    " . $payResult->getTransactionStatus() . "\n");
                     //CHECK Transaction Status is Success
                     $_SESSION['status'] = 'OK';
                 }
             }
             if ($response->isSetResponseMetadata()) {
                 echo("            ResponseMetadata\n");
                 $responseMetadata = $response->getResponseMetadata();
                 if ($responseMetadata->isSetRequestId())
                 {
                     echo("                RequestId\n");
                     echo("                    " . $responseMetadata->getRequestId() . "\n");
                 }
             }

    } catch (Amazon_FPS_Exception $ex) {
        echo("Caught Exception: " . $ex->getMessage() . "\n");
        echo("Response Status Code: " . $ex->getStatusCode() . "\n");
        echo("Error Code: " . $ex->getErrorCode() . "\n");
        echo("Error Type: " . $ex->getErrorType() . "\n");
        echo("Request ID: " . $ex->getRequestId() . "\n");
        echo("XML: " . $ex->getXML() . "\n");
    }
}

Using ExternalInterface to notify the Flex App

The only thing left now is to notify the Flex application and close the pop-up window.

First we need to prepare the Flex App. We create a payment notification function to be called by the pop-up window. This function is called through ExternalInterace. Because the JavaScript call can be overwritten (using FireBug for instance) the ExternalInterface call is not secure. So we use the call only to notify that the Amazon workflow has ended.

The Status is then retrieved from the server through HTTPS.

private function paymentNotification():void {
	var srv:HTTPService = new HTTPService();
	srv.url = "https://miti.pricope.com/testAmazon/paymentStatus.php";
	srv.addEventListener(ResultEvent.RESULT,function (event:ResultEvent):void {
		Alert.show("Status: " + event.result.status);
	});
	srv.send();
}

In this case paymentStatus.php is a simple php that will only retrieve the status packed in a simple XML format:

session_start();
echo '<status>' . $_SESSION['status'] . '</status>'

This function needs to be explicitly exposed through the ExternalInterface of Flash Player in order to be available to JavaScript calls. This call should be executed when the Flex application finishes initializing. The applicationComplete event is a good candidate for this.

//This will be used by return.php to notify Flex App that the payment has been made
ExternalInterface.addCallback('paymentNotification',paymentNotification);

Back to return.php, the only thing that remains is to close the pop-up window and notify the Flex App.

<script type="text/javascript">
	function gotoflex() {
		window.opener.window.document.getElementById('testAmazon').paymentNotification();
		window.close();
	}
</script>
<form>
<input type="button" value="Close This Window and Return to Flex APP" onclick="gotoflex()"/>
</form>

Installing the sample files

1. Unzip amazonFlexPHP.zip into your Web Root folder (For example: /work/www).

2. Edit amazonFlex/amazon-fps/src/Amazon/FPS/Samples/.config.inc.php and replace

define('AWS_ACCESS_KEY_ID', 'YOUR KEY');
define('AWS_SECRET_ACCESS_KEY', 'YOUR SECREY KEY');

with your own Amazon ACCESS key and SECRET_ACCESS_KEY.

3. In Flash Builder click File->Import … and choose Flash Builder Project.

4. Choose amazonFlex.fxp

5. Fill the the Output Folder Location, Web Root and Root URL with your values. It should look something like this:

image

Categories: flex, payment gateways, tutorials Tags:

Debug Flex and PHP using Flash Builder 4 and PDT

July 9th, 2009 4 comments

It took me more that I would have liked but here’s a screencast on how to debug flex and php applications using Flash Builder 4 and PDT.

 

Playing with Custom Layout in Flex 4

May 29th, 2009 9 comments

gumboListAs Flex 4 SDK is almost in it’s Beta state I took a look at his features and what impressed me the most was how the presentation is decoupled from the behavior. I remember a presentation around Max 2007 when Ely Greenfield, the principal scientist for Flex SDK, showed a sneak peek on how this will make a lot of skinning things a lot simpler. For example, it’s simple to make a list look … let’s say to make it look like the Fan effect that Mac users love so much :)

I found this quite easy to implement using Flex 4. Because the list can be skinned in MXML it’s so easy to program the skin and stay in MXML for the most part. The only thing that I actually needed to program was how the elements are laid out.

The basic List skin looks like this:

<s:states>
    <s:State name="normal"/>
    <s:State name="hover"/>
    <s:State name="disabled"/>
</s:states>

<fx:Metadata>[HostComponent("spark.components.List")]</fx:Metadata>
<s:DataGroup itemRenderer="components.RepeatedItem1"
        clipAndEnableScrolling="true"  id="dataGroup"
        rollOver="currentState='hover'">
    <s:layout>
        <components:LargeCircleLayout id="myLayout" radius="1400"
            stepAngle="0" stepAngle.hover="3.5"/>
    </s:layout>
</s:DataGroup> 

Notice that it’s nothing but a DataGroup that has a layout. I’ve also added the Hover state to be able to open the list when you hover over it.

To add the nice effect it’s just a matter of animating one layout property:

<s:transitions>
    <s:Transition autoReverse="true">
        <s:Animate target="{myLayout}" duration="200">
            <s:SimpleMotionPath property="stepAngle"/>
        </s:Animate>
    </s:Transition>
</s:transitions>

You can take a look at the source code here and watch the list here.

Categories: flex, ria, tips & tricks Tags:

Experience Designer – from blocks to something more

May 26th, 2009 1 comment

p>A few days ago, while heading to the Adobe offices here in Bucharest, I noticed (again) the grey communist buildings. I don’t know why, but this communism thing keeps inspiring me to think about the software industry.

umbraBlocuriJust to give you a hint: communist blocks are not the nicest type of buildings. Here in Romania they were ordered mainly by Ceausescu to displace a lot of people from rural areas into cities so that his plans of urbanization and industrialization could be sustained. So these buildings did just that … and nothing more. Very functional, that’s it. Not too much creativity, one model copied hundred of times in a row. More an engineering task than an architect’s job.

Now, if you ask a software engineer, this might sound like an efficient way to build houses, with a lot of component and design pattern reuse. If you ask people that are living in these blocks (including me) I would prefer moving. I can’t really because these are practically the only available blocks in Bucharest.

And this brings me back to the software industry and how we are building software, especially business software. Actually the verb for this is ‘engineer’: we are engineering software. And as engineers we are striving for efficiency. As a result there is tons and tons of software that is extremely … well let’s put it blunt: crappy to use. However, much of this software provides a lot of value. Like communist buildings, I would prefer using ‘crappy’ software to get a process going rather than push some paper.

But as the industry matures, the fundamental efficiency problem moves away from ‘build these two functionalities with the minimum amount of money’. As applications move more and more into our lives, they become like buildings and demand a touch of the ‘elusive’ design. For thousands of years architects have added the ‘experience’ value in the construction industry. That’s what the new Experience Designers for applications strive to do for the software industry. (They might also be known as Interaction Designers as we still struggle to define their work).

You can say that these guys make applications look nice, but I would say that it’s more than this. You can’t really put this into words, but if you come and take a walk among the grey communist blocks in Bucharest you will understand.

Categories: thinking Tags:

BEST Engineering Competition – PixelBender Contest

May 20th, 2009 2 comments

Adobe Romania sponsored the IT contest of BEC Competition in Bucharest. This is a cool competition organized by BEST Europe wide. I had the pleasure to choose the IT contest and I thought that a little math neuron twisting might be just great for these talented future engineers.

And I wasn’t wrong. After just two hours since their first encounter with the PixelBender language and PixelBender Toolkit here is what they did with my poor face … using only numerical algorithms that PixelBender runs in parallel:

 

You can take a look at the PixelBender kernels here.

Categories: Uncategorized Tags:

New York Times on your desktop – version 2.0

May 11th, 2009 Comments off

Picture 5 The New York Times has just released an app for reading the newspaper on the desktop. You can get it at http://timesreader.nytimes.com. 

The first question that I asked myself was: Why wasn’t the browser enough for them? Why do you need a desktop app for viewing some pictures and text?

Then something popped into my head. I asked myself: When do I read the newspaper? Well, I read the news in the metro, when waiting in line for something, when sitting on the … well toilet … and sometimes on weekend mornings while still in bed. Except for the weekend mornings (when I read it on my laptop) at all other times I use a mobile device. And the experience on the mobile device is less than stellar.

Now one thing that I immediately noticed about TimesReader was how easy it is to navigate and how nice it resizes (The resize is way tooooo cool). And that is when ‘that something’ popped into my head: This is perfect for devices that are NOT standard PCs. I mean it is cool for PCs too but it might not justify the effort when the browser might be good enough (except that you can also download a week’s worth of content and read it offline). But if you have something that you can hold in your hand and read it on the metro, this kind of interaction is just PERFECT.

I think this piece of software could be the beginning of a revolution. If you take this reader, add reasonable cheap tablet PCs or capable phones and a runtime that can run consistently on all these hardware … well it sounds like a revolutionary way to deliver a newspaper in a digital way. (I know Adobe AIR is not yet on my phone, but I urge the engineers to hurry up). Why? Because this way a digital newspaper can really pass the hardest test of all: Can you read it easily when sitting on the toilet?

Categories: Uncategorized Tags:

Environmental Friendly Bug Killing @ bugquash

May 8th, 2009 Comments off

It is said that reading other peoples code is 10x times harder than writing yours. That’s why I think that solving bugs (without messing everything up around them) is more of an art and black magic than a science. I find it easier to teach architecture and algorithms than debugging.

So if you think that you’re a black belt programmer then come and measure your Kung Fu skills against Flex Framework bugs (yeah you can do this because Flex is an Open Source framework). Killing these bugs does not harm the environment and the entire Flex community will benefit.

So on the 17th of may we will attack them again in an organized manner. You can participate from wherever your are. Find more about the Bug Quash at bugquash.com.

Categories: Uncategorized Tags:

Moving the session from Flex to AIR – PHP Version

May 5th, 2009 3 comments

p>Recently I was working to enable a common workflow for a Flex application in the browser and an AIR application. So basically your Flex application is working in a Browser, it does some stuff there and then you decide you want to move everything into an AIR app, let’s say because your user just decided in the middle of the workflow that he wants to switch to the AIR app that you provide.

So now the state of the application needs to move between Flex and AIR and it would be nice if you could move the server session from the browser application to AIR.

For this example I will use PHP as a server side technology but it will work very similar for other server technologies as well. Basically I want to:

  • get the session ID/cookie in the Flex Application
  • send it over to the AIR application
  • use the session ID in the AIR application to make requests that will access the same session as in the browser

Getting the session ID in the Flex Application

First I need to get the the session ID from the Flex App. One simple way to do that is to just grab the whole cookies string. This can be done through the ExternalInterface mechanism. So I inject a little JavaScript function that gets the cookies string from the browser and then call it:

ExternalInterface.call('eval','window.cookieStr = function () {return document.cookie};')
var cookieStr:String = ExternalInterface.call('cookieStr');

 

Communicating with the AIR App

 

To communicate with the AIR app I use LocalConnection. In the AIR app I register to an inbound connection:

var inbound:LocalConnection = new LocalConnection();
inbound.allowDomain('localhost');
inbound.client = new Object();
inbound.client.notifyMe = function (cookieStr:String):void {
    //add Code here to use the Cookie String
}
inbound.connect("session");

 

and in the Flex App I register to an outbound connection and call the notifyMe() function

outbound.connect("session");
outbound.send("app#phpSessionAIR:session","notifyMe",cookieStr);
//outbound.send("app#phpSessionAIR.F0B3F68E1857B8A07069FED1D0638CAF200F76EB.1:session","notifyMe",cookieStr);
outbound.close(); 

 

Please notice that when launching from Flex Builder, the AIR Application has no Publisher ID so the connection name is “app#phpSessionAIR:session”. After packaging and installation, the AIR app will get a Publisher ID and the connection name will be something like this: app#phpSessionAIR.F0B3F68E1857B8A07069FED1D0638CAF200F76EB.1:session

You can get the publisher ID of the installed AIR App by looking into META-INF/AIR/publisherid file within the application install directory.

 

Use the session id in the Air App

Now all that remains to be done is to use the cookies string when making the next request from the AIR app:

var myService:HTTPService = new HTTPService();
myService.url = "http://localhost/phpSessionFlex/sessionGet.php";
myService.headers.Cookie = cookieStr;
myService.send();

 

Here are the source files for the AIR and the Flex App

Categories: Uncategorized Tags: