Code sample: Creating an advanced application

Adv_app_UI_1940111_11

The UI for the sample application displays a list of goods and contains several buttons.

Button Description
Buy

Initiate the purchase of a digital good.

Refresh

Retrieve an array of past successful purchases.

Get Price

Get the price of the selected digital good.

Check Existing

Check to see if the selected digital good is a subscription that the user is subscribed to.

Cancel Subscription

Cancel the subscription for the selected digital good.

PaymentSystemDemo.as

package
{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.MouseEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;

	import net.rim.blackberry.events.PaymentErrorEvent;
	import net.rim.blackberry.events.PaymentSuccessEvent;
	import net.rim.blackberry.payment.PaymentSystem;
	import net.rim.blackberry.payment.Price;
	import net.rim.blackberry.payment.Purchase;

	import qnx.fuse.ui.buttons.LabelButton;
	import qnx.ui.data.DataProvider;
	import qnx.fuse.ui.listClasses.List;
	import qnx.fuse.ui.listClasses.ListSelectionMode;
	import qnx.fuse.ui.text.Label;

	import DigitalGoodsInfo;

	[SWF(height="600", width="1024", frameRate="30", backgroundColor="#FFFFFF")]

	// A simple application that offers digital goods
	public class PaymentSystemDemo extends Sprite
	{
		private var paymentSystem:PaymentSystem;
		private var buyList:List;

		private var loader:URLLoader;
		private var pastPurchases:Array = [];

		public function PaymentSystemDemo()
		{
			paymentSystem = new PaymentSystem();

			// configures the application for testing
			paymentSystem.setConnectionMode(PaymentSystem.CONNECTION_MODE_LOCAL);

			// listeners for successful and unsuccessful payment events
   paymentSystem.addEventListener(PaymentSuccessEvent.PURCHASE_SUCCESS,
          purchaseSuccessHandler);
   paymentSystem.addEventListener(PaymentErrorEvent.PURCHASE_ERROR,
          purchaseErrorHandler);

			paymentSystem.addEventListener(PaymentSuccessEvent.
     GET_EXISTING_PURCHASES_SUCCESS, getPurchasesSuccessHandler);
			paymentSystem.addEventListener(PaymentErrorEvent.
     GET_EXISTING_PURCHASES_ERROR, getPurchasesErrorHandler);

   paymentSystem.addEventListener(PaymentSuccessEvent.GET_PRICE_SUCCESS,
     getPriceSuccessHandler);
   paymentSystem.addEventListener(PaymentErrorEvent.GET_PRICE_ERROR,
     getPriceErrorHandler);

   paymentSystem.addEventListener(PaymentSuccessEvent.CHECK_EXISTING_SUCCESS,
     checkExistingSuccess);
			paymentSystem.addEventListener(PaymentErrorEvent.CHECK_EXISTING_ERROR,
     checkExistingError);

			paymentSystem.addEventListener(PaymentSuccessEvent.
       CANCEL_SUBSCRIPTION_SUCCESS, cancelSubscriptionSuccess);
   paymentSystem.addEventListener(PaymentErrorEvent.
       CANCEL_SUBSCRIPTION_ERROR, cancelSubscriptionError);

			initializeUI();
		}

		private function initializeUI():void
		{
			// creates the list that displays purchase options
			buyList = new List();
			buyList.setPosition(25,25);
			buyList.setSize(360, 250);
			buyList.columnWidth = 400;
			buyList.scrollable = true;
			buyList.allowDeselect = false;
			buyList.selectionMode = ListSelectionMode.SINGLE;
			addChild(buyList);

			// creates the Buy button
			var buyButton:LabelButton  = new LabelButton();
			buyButton.setPosition(400, 25);
			buyButton.setSize(185, 45);
			buyButton.label = "Buy";
			buyButton.addEventListener(MouseEvent.CLICK, purchaseHandler);
			addChild(buyButton);

			// creates the Refresh button
			var refreshButton:LabelButton  = new LabelButton();
			refreshButton.setPosition(400, 75);
			refreshButton.setSize(185, 45);
			refreshButton.label = "Refresh";
			refreshButton.addEventListener(MouseEvent.CLICK, refreshHandler);
			addChild(refreshButton);

			// creates the Price button
			var priceButton:LabelButton = new LabelButton();
			priceButton.setPosition(400, 125);
			priceButton.setSize(185, 45);
			priceButton.label = "Get Price";
			priceButton.addEventListener(MouseEvent.CLICK, priceHandler);
			addChild(priceButton);

			// creates the Check Existing button
			var checkExistingButton:LabelButton = new LabelButton();
			checkExistingButton.setPosition(400, 175);
			checkExistingButton.setSize(185, 45);
			checkExistingButton.label = "Check Existing";
			checkExistingButton.addEventListener(MouseEvent.CLICK,
            checkExistingHandler);
			addChild(checkExistingButton);

			// creates the Cancel Subscription button
			var cancelSubscriptionButton:LabelButton = new LabelButton();
			cancelSubscriptionButton.setPosition(400, 225);
			cancelSubscriptionButton.setSize(185, 45);
			cancelSubscriptionButton.label = "Cancel Subscription";
			cancelSubscriptionButton.addEventListener(MouseEvent.CLICK,
            cancelSubscriptionHandler);
			addChild(cancelSubscriptionButton);

			// sends an HTTPService request to retrieve a list of digital goods
			var urlRequest:URLRequest = new URLRequest();
			urlRequest.url = "http://docs.blackberry.com/digitalgoods.xml";

			loader = new URLLoader();
			loader.addEventListener(IOErrorEvent.IO_ERROR, faultHandler);
			loader.addEventListener(Event.COMPLETE, resultHandler);
			loader.load(urlRequest);
		}

		private function priceHandler(event:Event):void
		{
			// get the price of the selected digital good
			var info:DigitalGoodsInfo = buyList.selectedItem as DigitalGoodsInfo;
			paymentSystem.getPrice(null, info.sku);
		}

		private function checkExistingHandler(event:Event):void
		{
			// check to see if the selected digital good is a subscription that the
   // user is currently suscribed to
			var info:DigitalGoodsInfo = buyList.selectedItem as DigitalGoodsInfo;
			paymentSystem.checkExisting(null, info.sku);
		}

		private function cancelSubscriptionHandler(event:Event):void
		{
			// cancel the digital good subscription
			var info:DigitalGoodsInfo = buyList.selectedItem as DigitalGoodsInfo;
			var purchaseID:String = getPurchaseID(info.sku);
			paymentSystem.cancelSubscription(purchaseID);
		}

		private function getPurchaseID(sku:String):String
		{
			if(pastPurchases)
			{
				for (var i:int = 0; i < pastPurchases.length; i++)
				{
					var purchase:Purchase = pastPurchases[i] as Purchase;
					if(purchase.digitalGoodSKU == sku)
					{
						return purchase.purchaseID;
					}
				}
			}

			return null;
		}

		private function resultHandler(event:Event):void
		{
			var data:DataProvider = new DataProvider();
			var remoteData:XML;
			var dgObject:DigitalGoodsInfo;

			// creates an array of raw xml data
			remoteData = XML(loader.data);

			// loops through each object in the array of xml data, creates
			// DigitalGoodsInfo objects, and displays the names of the
			// digital goods in the list
			for each(var obj:Object in remoteData.digitalgood)
			{
				dgObject = new DigitalGoodsInfo(obj.name, obj.sku, obj.metadata);
				data.addItem(dgObject);
			}

			buyList.dataProvider = data;
			buyList.selectedIndex = 0;
		}

		private function faultHandler(event:Event):void
		{
			trace("Unable to retrieve digital goods from the server.");
		}

		private function purchaseHandler(event:MouseEvent):void
		{
			var info:DigitalGoodsInfo = buyList.selectedItem as DigitalGoodsInfo;

			// initiates a purchase using the properties of the digital good
			// that is at the equivalent position in the array as the position
			// in the list that is currently selected
			paymentSystem.purchase(null,
				info.sku,
				info.name,
				info.metadata,
				info.appName,
				info.icon);
		}

		private function refreshHandler(event:MouseEvent):void
		{
			// initiates a local request for a list of existing purchases
			paymentSystem.getExistingPurchases(false);
		}

		private function purchaseSuccessHandler(event:PaymentSuccessEvent):void
		{
			var purchase:Purchase = event.purchase;

			trace("Purchase Success - " + purchase.date
				+ " : " + purchase.digitalGoodID
				+ " : " + purchase.digitalGoodSKU
				+ " : " + purchase.licenseKey
				+ " : " + purchase.metaData
				+ " : " + purchase.itemState
				+ " : " + purchase.startDate
				+ " : " + purchase.endDate
				+ " : " + purchase.intialPeriod
				+ " : " + purchase.purchaseID);

			// Add this purchase to the past purchases array
			pastPurchases.push(purchase);
		}

		private function purchaseErrorHandler(event:PaymentErrorEvent):void
		{
			trace("Purchase Error - " + event.errorID + " : " + event.text);
		}

		private function getPurchasesSuccessHandler(event:PaymentSuccessEvent):void
		{
			var purchase:Purchase;
			pastPurchases = event.existingPurchases;

			if (pastPurchases.length == 0)
			{
				trace("No existing purchases");
			}
			else
			{
				// iterates through the list of existing purchases and prints the data
				for (var i:int = 0; i < pastPurchases.length; i++)
				{
					purchase = pastPurchases[i];

					trace("Get Existing Purchases Success - " + purchase.date
						+ " : " + purchase.digitalGoodID
						+ " : " + purchase.digitalGoodSKU
						+ " : " + purchase.licenseKey
						+ " : " + purchase.metaData
						+ " : " + purchase.itemState
						+ " : " + purchase.startDate
						+ " : " + purchase.endDate
						+ " : " + purchase.intialPeriod
						+ " : " + purchase.purchaseID);

				}
			}
		}


		private function getPurchasesErrorHandler(event:PaymentErrorEvent):void
		{
			trace("Get Existing Purchases Error - " + event.errorID + " :
              " + event.text);
		}


		private function getPriceSuccessHandler(event:PaymentSuccessEvent):void
		{
			var price:Price = event.price;
			trace("Get Price Success - " + price.price
				+ " : " + price.initialPeriod
				+ " : " + price.renewalPrice
				+ " : " + price.renewalPeriod);
		}

		private function getPriceErrorHandler(event:PaymentErrorEvent):void
		{
			trace("Get Price Error - " + event.errorID + " : " + event.text);
		}

		private function checkExistingSuccess(event:PaymentSuccessEvent):void
		{
			trace("Check Existing Success - " + event.subscriptionExists);
		}

		private function checkExistingError(event:PaymentErrorEvent):void
		{
			trace("Check Existing Error - " + event.errorID + " : " + event.text);
		}

		private function cancelSubscriptionSuccess(event:PaymentSuccessEvent):void
		{
			trace("Cancel Subscription Success");
		}

		private function cancelSubscriptionError(event:PaymentErrorEvent):void
		{
			trace("Cancel Subscription Error - " + event.errorID + " :
         " + event.text);
		}
	}
}

DigitalGoodsInfo.as

package
{
    public class DigitalGoodsInfo
    {
        //public var name:String;
								public var label: String
        public var sku:String;
        public var metadata:String;
        public var icon:String;
        public var appName:String;

        public function DigitalGoodsInfo( name:String, sku:String, 
metadata:String )
        {
            this.label = name;
            this.sku = sku;
            this.metadata = metadata;

            icon = "http://www.rim.com/products/appworld_3col.jpg";
            appName = "PaymentServiceDemo";
        }
    }
}

digitalgoods.xml

<?xml version="1.0" encoding="utf-8"?>
<digitalgoods>
    <digitalgood>
        <name>Developing for BlackBerry</name>
        <sku>123456abc123</sku>
        <metadata>1234-56-7890</metadata>
    </digitalgood>
    <digitalgood>
        <name>Intro to the BlackBerry Tablet OS</name>
        <sku>123456abc123</sku>
        <metadata>09-4567-1243</metadata>
    </digitalgood>
    <digitalgood>
        <name>Tutorial: Selling Digital Goods</name>
        <sku>123456abc123</sku>
        <metadata>654-34-29304</metadata>
    </digitalgood>
    <digitalgood>
        <name>Feature and Technical Overview</name>
        <sku>123456abc123</sku>
        <metadata>7399-29-0940</metadata>
    </digitalgood>
    <digitalgood>
        <name>Development Guide</name>
        <sku>123456abc123</sku>
        <metadata>34-90390-124</metadata>
    </digitalgood>
</digitalgoods>