In this tutorial, you will create a Flash CS3 application that searches the eBay site for items matching an advanced Shopping API query. The sample application displays the results as a list of links to the item listings on the eBay site. The application uses the eBay Shopping API, which enables developers to interact with the eBay API servers using a simple URL over HTTP.
Think of this tutorial as "Hello World" for eBay's Shopping Web Service. It shows you how easy it is to interact with the Shopping Web Service. When you complete the tutorial, you will have an application that looks like this when it runs:
The example above is actually made up of three search widgets - one to find items in the $0-$50 range, one to find items in the $50 - $200 range, and one to find items in the $201 - $500 range. This tutorial will explain how to create the first widget and then how to modify it to create the widgets with the other sets of results.
Before we begin our step-by-step procedure, let's go over the basics of using the Flex/Flash SDK 2.2. With this SDK, you can design using pre-created classes that correspond to the calls in the eBay Shopping Web Service.
If you look in the /src folder in your Flex/Flash SDK, you will see these call-specific .as files.
Since the details of the Shopping Web Service calls have been wrapped in these .as files, you can easily create an application that
incorporates any of these calls, without writing them from scratch. Each call will instantiate the types used by that call.
Within the src/com/ebay/shoppingservice directory, you will see all of the type files used by the
eBay Shopping Web Service (in the form of .as files).
Please refer to the Flash Developer Guide for general information about how to use the Flex/Flash SDK.
After running this tutorial, if you start creating your own search widgets or applications that bring traffic to the eBay web site, you can earn money through the eBay Affiliate Program. For notes about the tutorial and the eBay Affiliate Program, see Notes and next steps.
There are nine main steps for this tutorial:
Step 1: Set up the Flash (.fla) file
Step 2: Create the Main (Document) class
Step 3: Create the constructor
Step 4: Define the FindItemsAdvanced call
Step 5: Define the callback functions
Step 7: Prepare for publishing
This tutorial was designed to explain the FindItemsAdvanced sample files, located within the Samples/Flash directory of your Flex/Flash SDK, and to help you create your own applications based on these samples. Some of the steps in the tutorial may include a sub-set of the code that is actually in the sample. Please compare the tutorial to the samples as you proceed.
The SDK comes with several samples that you can run as soon as you add your appID to the .html file.
After you have downloaded and upzipped the SDK archive, you will have access to several widget samples, located in the \Samples\Flash folder. Open the FindItemsAdvanced folder and then edit the FindItemsAdvanced.html file using a text editor. You are going to add a new variable to the list of variables in the AC_FL_RunContent function.
AC_FL_RunContent(
'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0',
'width', '820',
'height', '950',
'src', 'FindItemsAdvanced',
'quality', 'high',
'pluginspage', 'http://www.macromedia.com/go/getflashplayer',
'align', 'middle',
'play', 'true',
'loop', 'true',
'scale', 'showall',
'wmode', 'window',
'devicefont', 'false',
'id', 'FindItemsAdvanced',
'bgcolor', '#ffff66',
'name', 'FindItemsAdvanced',
'menu', 'true',
'allowFullScreen', 'false',
'allowScriptAccess','sameDomain',
'movie', 'FindItemsAdvanced',
'salign', ''
); //end AC code


Before you can begin using the Flex/Flash SDK with Flash CS3, you also need to do the following:
Now you're ready to start building your application.
In this first step, we will create a Flash file (file with .fla extension), set up the libraries, and then create a blank ActionScript file to use as the Document Class for your .fla file. You can create a separate directory and save these files to it as you create them, or you can just create the files and Flash will save them in your default document directory ('My Documents' directory if you're using a PC).
Alternately, you can create a project file and add the .fla and .as files to the project, but we have chosen to use a simpler structure for this tutorial.

Now we will modify the ActionScript file that will contain your calls, parse the results of those calls, and pass the retreived information to a UI display function. As with most object- oriented languages, you can create the main class and the function definitions for the class in the same file. In this tutorial, we will create the main class first, followed by the definitions for the UI functions, the call functions, the success and failure callback functions, and the data array function.
To enter your ActionScript code, choose the tab for the .as file and type in the following ActionScript sections to create a working application.
Let's begin by importing the packages for all of the eBay Flex/Flash SDK classes and the Flash component classes that are used by the sample we're creating in this tutorial:
package {
import flash.display.Sprite;
import com.ebay.shoppingservice.*;
import flash.text.TextFieldAutoSize;
import fl.controls.Label;
import fl.controls.Button;
import fl.controls.TextInput;
import fl.controls.DataGrid;
import fl.controls.listClasses.CellRenderer;
import fl.data.DataProvider;
import flash.display.LoaderInfo;
import flash.events.Event;
import flash.events.MouseEvent;
import com.ebay.events.FaultEvent;
import com.ebay.events.Fault;
import renderer.*;
import util.*;
Now let's create a FindItemsAdvanced class which extends the Flash Sprite component. In the variables section of this class, we create the service variable (Shopping type), and the queryKeywords variable:
public class FindItemsAdvanced extends Sprite
{
private var service:Shopping;
private var queryKeywords:String = "";
Then we create the internal variables used by this sample:
//array for 3 itemList dataGrids
private var itemLists:Array = new Array();
//array for 3 priceRange labels
private var priceRanges:Array = new Array();
private var searchResultFor:Label;
private var searchButton:Button;
private var searchInput:TextInput;
private var searchLabel:Label;
private var errorLabel:Label;
private var space:int = 3; //space between UI elements
private var priceRange1:String = "$0-$50";
private var priceRange2:String = "$51-$200";
private var priceRange3:String = "$201-$500";
Use the File --> Save As command to change the name of your ActionScript file to match the name of your main class (also known in Flash as the document class).
Next, we will define the constructor of the FindItemsAdvanced class. In the constructor, we pass in query keywords, initialize the UI layout, initialize the shopping service, and then perform the search. All code in the constructor will be automatically called when the Docuemnt class is instantiated, like the 'main' function of a program.
public function FindItemsAdvanced()
{
//Read parameters passed in by the HTML container using flashvars
var paramObj:Object = LoaderInfo(this.root.loaderInfo).parameters;
queryKeywords = paramObj.QueryKeywords;
if (('' == queryKeywords) || (undefined == paramObj.QueryKeywords)) {
queryKeywords = "ipod";
}
initSearchResultForLabel();
initPriceRangeLabels();
initItemLists();
initSearchBox();
setLabelFormat();
adjustLayout();
// init shopping service
service = eBayUtil.initEBayService(paramObj);
// now that configurations are all set, search for the items
performSearch();
}
The definitions for each of the UI initialization functions are added as
private functions. For example, the initSearchBox and initItemlists functions
are shown below. Please see the Samples\Flash\FindItemsAdvanced\FindItemsAdvanced.as
file for the complete code used in the constructor functions for this sample.
private function initSearchBox():void {
searchLabel = new Label();
searchLabel.autoSize = TextFieldAutoSize.LEFT;
searchLabel.text = "Query Keyword: ";
addChild(searchLabel);
searchInput = new TextInput();
addChild(searchInput);
searchButton = new Button()
addChild(searchButton);
searchButton.label = "Go";
searchButton.toggle = true;
searchButton.addEventListener(MouseEvent.CLICK, onSearchClick);
errorLabel = new Label();
errorLabel.autoSize = TextFieldAutoSize.LEFT;
errorLabel.text = "";
addChild(errorLabel);
}
.
.
.
private function initItemLists():void {
for(var i:int = 0; i < 3; i++) {
var showBid:Boolean = false;
var itemList = new ItemList(showBid);
itemList.width = 800;
addChild(itemList);
itemLists[i] = itemList;
}
}
Now we will implement the definitions for the FindItemsAdvanced request and response. First, we create a 'getFiaReqeust' function. This function will return a FindItemsAdvancedRequestType with the specified price range.
/**
* get FindItemsAdvanced request with specified price range
* @param {int} pmax, upper limit of the price
* @param {int} pmin, lower limit of the price
* @return {FindItemsAdvancedRequestType}
*/
private function getFiaRequest(pmax:int, pmin:int):FindItemsAdvancedRequestType {
var fiaRequest:FindItemsAdvancedRequestType = new FindItemsAdvancedRequestType({
priceMax: {currencyID: CurrencyCodeType.USD, Value: pmax},
priceMin: {currencyID: CurrencyCodeType.USD, Value: pmin},
itemSort: SimpleItemSortCodeType.BestMatch,
QueryKeywords: queryKeywords,
itemType: ItemTypeCodeType.FixedPricedItem,
maxEntries: 10
});
return fiaRequest;
}
Then, we define the 'performSearch' function. In this function, we invoke FindItemsAdvanced shopping API 3 times for each price range. The FindItemsAdvanced Shopping API call will provide the connection to the eBay Shopping Web Service.
/**
* Invoke findItemsAdvanced shopping api 3 times for each price range
*/
private function performSearch():void {
var fiaRequestOne:FindItemsAdvancedRequestType = this.getFiaRequest(0, 50);
service.findItemsAdvanced(fiaRequestOne, new ShoppingCallback(onSomeItemsReturned(priceRange1,
itemLists[0], priceRanges[0]), onSomeItemsReturnedFailed(priceRange1, itemLists[0], priceRanges[0])));
var fiaRequestTwo:FindItemsAdvancedRequestType = this.getFiaRequest(51, 200);
service.findItemsAdvanced(fiaRequestTwo, new ShoppingCallback(onSomeItemsReturned(priceRange2,
itemLists[1], priceRanges[1]), onSomeItemsReturnedFailed(priceRange2, itemLists[1], priceRanges[1])));
var fiaRequestThree:FindItemsAdvancedRequestType = this.getFiaRequest(201, 500);
service.findItemsAdvanced(fiaRequestThree, new ShoppingCallback(onSomeItemsReturned(priceRange3,
itemLists[2], priceRanges[2]), onSomeItemsReturnedFailed(priceRange3, itemLists[2], priceRanges[2])));
}
We use callback functions to handle errors (if the service call fails) or to handle returned data (if the connection to the eBay Web Service succeeds). In this tutorial, the function for a failed call is 'onSomeItemsReturnedFailed' and the function for a successful call is 'onSomeItemsReturned'.
Let's add the error handling first:
/**
* return an error handling callback function,
* actionscript closure is used
* @param {String} priceRange
* @param {DataGrid} itemList
* @param {Label} priceRange Label
* @return function
*/
private function onSomeItemsReturnedFailed(range: String, itemList:DataGrid, priceRange:Label):Function {
return function(fault:FaultEvent):void {
var faultMessage:Fault = fault.fault;
errorLabel.text += ("Error: " + faultMessage.faultDetail + " in " + range + ". ");
itemList.dataProvider.removeAll();
itemList.rowCount = 0;
priceRange.text = range;
adjustLayout();
}
}
For a successful callback function, we will store the returned items in itemArray (we will
show the details of the 'getItemArray' function in the next section), and then we bind the
itemArray to the data provider of the itemList (DataGrid UI component). The result of binding
the itemArray to the DataGrid is that the data for all items will be shown in the itemList
DataGrid. In other words, data and UI binding happens in this function. See the Samples\Flash\FindItemsAdvanced\FindItemsAdvanced.as
file for the complete code for the full example, with the secondary functions.
/**
* return an items processing callback function,
* actionscript closure is used
* @param {String} priceRange
* @param {DataGrid} itemList
* @param {Label} priceRange Label
* @return function
*/
public function onSomeItemsReturned(range: String, itemList:DataGrid, priceRange: Label): Function {
return function(searchResult:FindItemsAdvancedResponseType):void {
var itemArray:Array = getItemArray(searchResult);
itemList.dataProvider.removeAll();
itemList.dataProvider.addItems(itemArray);
itemList.rowCount = itemArray.length;
if(itemArray.length > 0) {
priceRange.text = range + " (" + searchResult.totalItems + " items found)";
} else {
priceRange.text = range + " (no items found)";
}
adjustLayout();
}
}
Now we create the details for the getItemArray function. This function accepts a FindItemsAdvancedResponseType object as a parameter, filters the items that come back in the response, and returns them as an array. Thus, we use the getItemArray function to pre-process the returned items before we send them to the UI:
/**
* filter the returned items
* @param {FindItemsAdvancedResponseType}
* @return {Array}, filtered items
*/
private function getItemArray(searchResult:FindItemsAdvancedResponseType):Array {
var itemArray:Array = new Array();
if(searchResult.ack.value != AckCodeType.Success.value) {
return itemArray;
}
//filter out all items whose listing type is chinese and BuyItNow is false
if (searchResult.searchResult != null && searchResult.searchResult.length > 0) {
var i:int = 0;
var items: Array = (searchResult.searchResult[0] as SearchResultType).itemArray.item;
var count: int = items.length;
itemArray = new Array();
while ( i < count && itemArray.length < 3) {
var item:SimpleItemType = (items[i] as SimpleItemType)
if ( item.listingType.value == ListingTypeCodeType.Chinese.value
&& !item.buyItNowAvailable) {
i++;
continue;
}
itemArray.push(item);
i++;
}
}
return itemArray;
}
}
}
With the Flash application, the File -->Publish command performs the build function. You can alternately use the Properties panel to Publish, by clicking Settings and then Publish (while your .fla file is selected). Before you Publish, you may need to change the security setting from 'Local playback security' to 'Access network only' so that your application can access the eBay Shopping Service.
Before you publish your application, you must copy the \util and \renderer folders from the Samples\Flash\FindItemsAdvanced directory of your SDK to the folder where your .fla and .as files are located.
Within the \util folder, there is a file named, 'eBayUtil.as'. Modify this file to include your appID (required), siteID (optional), trackingID (optional), trackingPartnerCode (optional), and affiliateUserID (optional).
public static function initEBayService(paramObj:Object):Shopping {
var apiAppName:String = null;
var trackingID:String = null;
var trackingPartnerCode:String = null;
var affiliateUserID:String = null;
var siteID:String = null;
var service:Shopping;
//Read parameters passed in by the HTML container using flashvars
apiAppName = paramObj.ebayAppId;
if (('' == apiAppName) || (undefined == paramObj.ebayAppId)) {
//replace your 'appId' here
apiAppName = "yourappid";
}
Now you're ready to publish the application from within Flash CS3. Make sure that the tab for the .fla file is selected, and modify the settings in the Properties tab.
Set the Document class to the name of your ActionScript file (without the file extension). For this tutorial, the Document class should be 'FindItemsAdvanced'.
Use the Properties panel to Publish - by clicking Settings and then Publish (while your .fla file is selected), OR choose the File -->Publish command.
When you publish your application, Flash CS3 creates an .swf file, and an .html file, in addition to your .fla and .as files.
If you haven't added parameters (like appID) in the eBayUtil.as file mentioned above, you can still pass these parameters into the .swf file using flashVars.
If your (and your customer's) browser supports JavaScript (which is the normal case), you only need to add flashVars in the 'AC_FL_RunContent' JavaScript function call. [This is the same as the example in Running an SDK Sample above.]
AC_FL_RunContent( 'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0', 'width', '820', 'height', '950', 'src', 'FindItemsAdvanced', 'quality', 'high', 'pluginspage', 'http://www.macromedia.com/go/getflashplayer', 'align', 'middle', 'play', 'true', 'loop', 'true', 'scale', 'showall', 'wmode', 'window', 'devicefont', 'false', 'id', 'FindItemsAdvanced', 'bgcolor', '#ffff66', 'name', 'FindItemsAdvanced', 'menu', 'true', 'allowFullScreen', 'false', 'allowScriptAccess','sameDomain', 'movie', 'FindItemsAdvanced', 'salign', '', 'flashVars','yourappid' ); //end AC code ... </script>
To increase your compatibility with different types of browsers, you can add two additional flashVars: as a parameter element of an object html tag, and as a property of the embed html tag (within an object tag)::
<noscript>
<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
id="FindItemsAdvanced" width="100%" height="100%"
codebase="http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab">
<param name="movie" value="FindItemsAdvanced.swf" />
<param name="quality" value="high" />
<param name="bgcolor" value="#869ca7" />
<param name="allowScriptAccess" value="sameDomain" />
<param name="flashVars" value="YourAppID" />
<embed src="FindItemsAdvanced.swf" quality="high" bgcolor="#869ca7"
width="100%" height="100%" name="FindItemsAdvanced" align="middle"
play="true"
loop="false"
quality="high"
allowScriptAccess="sameDomain"
type="application/x-shockwave-flash"
flashVars='YourAppID'
pluginspage="http://www.adobe.com/go/getflashplayer">
</embed>
</object>
</noscript>
You should now be able to double-click the .swf file and run your application in Flash Player 9, or double-click the .html file to run the widget within a browser.
Note: as a best practice, we recommend that you save a copy of your .html file after you have modified it, because if you update your application and use the Publish command again, a new .html file will over-write the one that contains your appID.
Congratulations! You now have a working application that uses eBay Shopping Web Services.
This section contains observations about this tutorial and offers some alternate ways to achieve similar or better results. We've also provided some suggestions about where you can go from here.
Now that you've completed the Tutorial for the FindItemsAdvanced call, you may want to proceed to a more complex tutorial. The GetUserProfile tutorial uses both the FindItemsAvanced call and the GetUserProfile call to create an application that returns both item data and user data.
The eBay Affiliate Program allows you to earn money by driving traffic to the eBay site using applications or widgets you create and post on your own web page. You can think of this as a way to enhance your existing business or create a new enterprise. With just a little effort, you can earn a lot of money.
Now that you have a working search application, you can earn money with the eBay Affiliate Program! Join the affiliate program now!
Once you have joined the eBay Affiliate Program, sign up for the Affiliate API Tier of the eBay Developers Program.
As noted at the beginning of the tutorial, we tried to keep things simple. The eBay community codebase contains many excellent samples that are more complex and many give you good ideas for ways to design your applications.
The sample provided with this tutorial was built and tested on a Windows 2003 Server platform using Adobe's Flash within Creative Suite 3 Professional and Microsoft IIS 5.0.
For the tutorial, we took a minimalist approach to input parameters. The FindItemsAdvanced call supports numerous input parameters and options. Visit the Flash Developer Center for links to documentation and additional information.
Here's a list of resources for the topics and technologies introduced in this tutorial:
In order to leave a comment in this section, you must view this Tutorial via the eBay web site: online version.
© 2008 eBay Inc. All rights reserved.
eBay and the eBay logo are registered trademarks of eBay Inc.
All other brands are the property of their respective owners.