Adobe
Products
Acrobat
Creative Cloud
Creative Suite
Digital Marketing Suite
Digital Publishing Suite
Elements
Photoshop
Touch Apps
Student and Teacher Editions
More products
Solutions
Digital marketing
Digital media
Education
Financial services
Government
Web Experience Management
More solutions
Learning Help Downloads Company
Buy
Home use for personal and home office
Education for students, educators, and staff
Business for small and medium businesses
Licensing programs for businesses, schools, and government
Special offers
Search
 
Info Sign in
Welcome,
My cart
My orders My Adobe
My Adobe
My orders
My information
My preferences
My products and services
Sign out
Why sign in? Sign in to manage your account and access trial downloads, product extensions, community areas, and more.
Adobe
Products Sections Buy   Search  
Solutions Company
Help Learning
Sign in Sign out My orders My Adobe
Preorder Estimated Availability Date. Your credit card will not be charged until the product is shipped. Estimated availability date is subject to change. Preorder Estimated Availability Date. Your credit card will not be charged until the product is ready to download. Estimated availability date is subject to change.
Qty:
Purchase requires verification of academic eligibility
Subtotal
Review and Checkout
Adobe Developer Connection / Adobe AIR Developer Center /

Using the In-App Billing Adobe AIR native extension for Android

by Alex Liebert

Alex Liebert
  • Milkman Games

Content

  • Setting up your app with your Android Market publishing account
  • Including the library
  • Getting started with the API
  • Making purchases
  • Understanding asynchronous events
  • Restoring managed transactions
  • Testing the API with fake item purchases
  • Testing the API with real item purchases
  • Updating your application descriptor file
  • Building and troubleshooting your app
  • Where to go from here

Created

29 May 2012

Page tools

Share on Facebook
Share on Twitter
Share on LinkedIn
Bookmark
Print
ActionScript Adobe AIR Android Flash Builder Flash Professional gaming mobile Native extensions

Requirements

Prerequisite knowledge

Experience building apps for Android with Flash Builder or Flash Professional and Adobe AIR will help you make the most of this article.

 

Additional required other products

Milkman Games In-App Billing Extension for Android

User level

Intermediate

Required products

  • Flash Builder (Download trial)
  • Flash Professional (Download trial)

With the In-App Billing Extension for Android from Milkman Games, you can rapidly integrate in-app purchasing into your mobile AIR application using ActionScript 3.

The In-App Billing Extension for Android is a 100 percent native Java solution that enables you to:

  • Offer your app for free and earn revenue with in-app purchases
  • Make a purchase with just a few lines of code
  • Jumpstart development with a complete sample application, ActionScript 3 documentation, and a getting started guide
  • Invoke testing methods to verify purchases before your app goes live

Setting up your app with your Android Market publishing account

Before you can use In-App Billing in your application, you need to set it up properly on the Android Market website.

  1. Go the Android Market Publishing Home page and login with your developer account.
  2. If you're adding In-App Billing to an existing application, select the application from the list. Click the APK Files tab, and upload a new APK file. Do not publish it yet, but click Save to save a draft.
  3. If you're adding In-App Billing to a new application, click Upload Application. Upload your new application's first draft APK file. Enter the required information and click Save, but do not click Publish yet. If you're just making a test app, the In-App Billing Extension for Android package includes a /tutorial folder with some stock screenshots and icons that you can use for this process.
  4. Next, you need to add some products that can be purchased via In-App Billing. On the home screen, begin by clicking the In-App Products link for the application to which you'd like to add products (see Figure 1).
Figure 1. Click In-App Products.
Figure 1. Click In-App Products.
  1. To add a product, click Add In-App Product.
Figure 2. Enter information for the in-app purchase.
Figure 2. Enter information for the in-app purchase.
  1. For Purchase Type, choose between Managed Per User Account and Unmanaged. A managed item is something that the user may purchase once and only once, and then owns forever, such as pack of new levels for a game. An unmanaged item is something that can be purchased again and again, such as a magic spell.
  2. For In-App Product ID, type a unique string identifier to represent your item. Take note of this ID, as you'll need to reference it in your game code later. Complete the rest of the required information, providing an appropriate title, description, and price (see Figure 2).
  3. Click Publish. This will Publish the product so it can be tested. You do not need to publish your draft application yet (and should avoid doing so during testing). When you're done, return to the Android Developers Home page from the tab bar at the top.
  4. Next, retrieve your In-App Billing Public Key by clicking Edit Profile from the Home page (see Figure 3). Also, take note of the email address listed above Edit Profile. This is the Google account associated with your developer account. In this article, I will refer to this email address as your Registered Developer Email.
Figure 3. Click Edit Profile.
Figure 3. Click Edit Profile.
  1. Copy your public key in the Licensing and In-App Billing section (see Figure 4) to the clipboard. Open a text editor, paste your key from the clipboard, and save it in a text file. You'll need this later to complete your app.
Figure 4. Copy the Public Key and specify a Test Account.
Figure 4. Copy the Public Key and specify a Test Account.
  1. In the Test Accounts area, type a Gmail address you control, other than your Registered Developer Email. If you don't have any other Gmail accounts besides your Registered Developer Email, you should create a new one now at Gmail.com for this purpose. In this article, I'll refer to this new address as your Test Account Email.
  2. Click Save.

Including the library

The next step is to add the com.milkmangames.nativeextensions.AndroidIAB.ane library to your project. (If you are not using Flash Builder 4.6 and later or Flash Professional CS6 and later you'll need to add the AndroidIABAPI.swc library instead.)

In Flash Professional CS6:

  1. Create a new project of the type AIR for Android.
  2. Choose File > Publish Settings.
  3. Click the wrench icon next to Script for ActionScript Settings.
  4. Select the Library Path tab.
  5. Click Browse For Native Extension (ANE) File and select the com.milkmangames.nativeextensions.AndroidIAB.ane file.

In Flash Builder 4.6:

  1. Go to Project Properties (right-click your project in Package Explorer and select Properties).
  2. Select ActionScript Build Path and click the Native Extensions tab.
  3. Click Add ANE and navigate to the com.milkmangames.nativeextensions.AndroidIAB.ane file.

In FlashDevelop:

  1. Copy the AndroidIABAPI.swc file to your project folder.
  2. In the explorer panel, right-click the SWC and select Add To Library.
  3. Right-click the SWC file in the explorer panel again, select Options, and then select External Library.

Getting started with the API

You can start using the In-App Billing extension with a few simple calls. See example/AndroidIAB.as for a full example that shows how to use the ActionScript API.

Follow these steps to get started:

  1. Import the API Classes:
com.milkmangames.nativeextensions.android.*; com.milkmangames.nativeextensions.android.events.*;
  1. Initialize the API by calling AndroidIAB.create() . You can check the AndroidIAB.isSupported() method first, to ensure the current platform is Android and not an unsupported platform (like iOS or Windows):
if (AndroidIAB.isSupported()) { AndroidIAB.create(); }
  1. Once create() has been called, an instance of the AndroidIAB API is available statically by accessing AndroidIAB.androidIAB. Add event listeners for all possible API responses:
// billing service ready listeners AndroidIAB.androidIAB.addEventListener(AndroidBillingEvent.SERVICE_READY,onReady); AndroidIAB.androidIAB.addEventListener(AndroidBillingEvent.SERVICE_NOT_SUPPORTED,onUnsupported); // purchase listeners AndroidIAB.androidIAB.addEventListener(AndroidBillingEvent.PURCHASE_SUCCEEDED,onPurchaseSuccess); AndroidIAB.androidIAB.addEventListener(AndroidBillingEvent.PURCHASE_REFUNDED,onPurchaseRefunded); AndroidIAB.androidIAB.addEventListener(AndroidBillingEvent.PURCHASE_CANCELLED,onPurchaseCancelled); AndroidIAB.androidIAB.addEventListener(AndroidBillingEvent.PURCHASE_USER_CANCELLED,onUserCancelled); AndroidIAB.androidIAB.addEventListener(AndroidBillingErrorEvent.PURCHASE_FAILED,onPurchaseFailed); // transaction restore listeners AndroidIAB.androidIAB.addEventListener(AndroidBillingEvent.TRANSACTIONS_RESTORED,onsRestored); AndroidIAB.androidIAB.addEventListener(AndroidBillingErrorEvent.TRANSACTION_RESTORE_FAILED,onRestoreF ailed);
  1. Call the AndroidIAB.androidIAB.startBillingService("yourPublisherPublicKeyHere") method to begin interactions with the Android In-App Billing server. Instructions on obtaining your publisher public key were provided in Setting up your app with your Android Market publishing account. If the current device does not support In-App Billing (because it doesn't have Android Market, for instance), you'll receive the AndroidBillingEvent.SERVICE_NOT_SUPPORTED event. Otherwise, when the service is ready, you'll receive the AndroidBillingEvent.SERVICE_READY event; once that happens, you may begin calling the other API methods to make purchases.
AndroidIAB.androidIAB.startBillingService("YOUR_PUBLIC_KEY_HERE"); private function onReady(e:AndroidBillingEvent):void { trace("service now ready- you can call purchase and restore methods."); } private function onUnsupported(e:AndroidBillingEvent):void { trace("sorry, in app billing won't work on this phone!"); }

Making purchases

  1. To start the item purchase process, call purchaseItem(itemId) , where itemId is one of the In-App Product IDs you created with your Android Market publishing account:
AndroidIAB.androidIAB.purchaseItem("your_itemid");
  1. When the process completes you will receive one of the following events:
  • AndroidBillingEvent.PURCHASE_SUCCEEDED – This event will fire if the purchase went through successfully. The itemId property of the event object will be the In-App Product ID of the item the user just bought.
  • AndroidBillingErrorEvent.PURCHASE_FAILED – This event will fire if an error occurred and the purchase did not go through. The itemId property of the event object will be the In-App Product ID of the item the user just attempted to buy. The errorID property will indicate the specific reason of the error (see Table 1).
  • AndroidBillingEvent.PURCHASE_USER_CANCELLED – This event will fire if the user cancelled the purchase by closing the checkout dialog box or pressing the Back button. The itemId property of the event object will be the In-App Product ID of the item the user just attempted to buy.

Table 1. AndroidBillingErrorEvent.errorID values and descriptions

AndroidBillingErrorEvent.errorID Value

Description

AndroidBillingErrorID.REASON_SERVICE_UNAVAILABLE

The Internet connection was unavailable.

AndroidBillingErrorID.REASON_BILLING_UNAVAILABLE

The connection to the Android Market service was unavailable.

AndroidBillingErrorID.REASON_DEVELOPER_ERROR

Configuration error (see below).

AndroidBillingErrorID.REASON_ITEM_UNAVAILABLE

The itemId requested was not published in the Android Market Developer website.

AndroidBillingErrorID.REASON_GENERAL_ERROR

An unknown error occurred.

If you receive AndroidBillingErrorID.REASON_DEVELOPER_ERROR then there is a problem with your code or configuration. Verify your application descriptor file is set up correctly; see Updating your application descriptor file for details. This error will also be reported if you attempt to purchase an item when the Google account associated with the device is the same as your Registered Developer Email because Google won't let you buy items from yourself. You can avoid this error by switching the Google account associated with the device to a Test Account Email, as described in Setting up your app with your Android Market publishing account.

Understanding asynchronous events

The Android Billing service works in asynchronously; in other words, events can be dispatched at any time that an item's purchase state changes, even if your application is running in the background. It is up to you as the developer to handle these events, and keep track of what items the user does or does not own.

For instance, it is possible for you to cancel or refund a purchase using the Android Market Developer website. When you do this, your application will receive an event indicating the refund or cancellation (even if it's not in the foreground). When this happens, your app should update its state appropriately, by taking away the item and setting a variable to indicate the item is no longer in the user's possession.

One way you might manage this is to keep a SharedObject instance updated locally, with information about each item that you sell. When you get an AndroidBillingEvent.PURCHASE_SUCCEEDED event, update the SharedObject instance to indicate that the item is now owned. You may also receive a AndroidBillingEvent.PURCHASE_REFUNDED or AndroidBillingEvent.PURCHASE_CANCELLED event. In these cases, you could update your SharedObject instance to indicate that the particular item has been removed.

If you have an unmanaged item, such as a consumable magic spell that can be bought and used multiple times, you are also responsible for keeping track of how many times the item has been bought and used in your application logic.

For a simple example that shows how to manage the full transaction event cycle, see the /example/IABExample.as class in the In-App Billing Extension for Android package.

Restoring managed transactions

Any In-App Purchases you marked as managed in the Android Market Developer website are treated as one-time, permanent purchases. This designation is intended for items such as an additional game level or a virtual hat your user gets to keep.

Because these items are managed, Google stores a record of whether the user has purchased them or not. Of course, you still must also maintain your own records of this within your application.

It is possible that the user will uninstall your application from the device, or get a new device and install your application on it. In this situation, you'll need to restore all items the user has previously purchased. To detect if the user has re-installed your app (or possibly just installed it for the first time), you could, for example, keep a variable named firstTimeuse with a default value of true in your SharedObject instance. If firstTimeUse is set, your app can call the restoreManagedTransactions() function, which will replay all the stored managed purchase events for that user. Your app can then listen for the events and update its records to reflect the user's purchases. It would then set firstTimeUse to false so the process is not repeated on the next application start. RestoreManagedTransactions() is not meant to be used every time your application runs, just when it is being run for the first time on a new device.

The following code demonstrates the restoreManagedTransactions() call:

// if the application has not been run since installing, call this AndroidIAB.androidIAB.restoreManagedTransactions();

After the call is made, one AndroidBillingEvent.PURCHASE_SUCCEEDED event will be fired for each managed item the user has already purchased (if any). The event handler can check the itemId property of the event object, and grant the user the item.

When there are no more items to be restored, an AndroidBillingEvent.TRANSACTIONS_RESTORED event will be dispatched.

If an error occurs with the call, AndroidBillingErrorEvent.TRANSACTION_RESTORE_FAILED will be dispatched instead.

Again, the /example/IABExample.as class in the in the In-App Billing Extension for Android package shows an example of how to manage the full transaction event cycle.

Testing the API with fake item purchases

The In-App Billing Extension for Android provides a number of built-in test methods that you can use to ensure you've set up billing correctly. These methods will attempt to contact the billing service, and dispatch the proper events for different fake item use cases, such as a refund or successful purchase. You should make sure these methods work for you before moving on to integrating your real items.

These calls will work whether the Google account associated with your device is a Registered Developer Email or a Test Account Email, as defined earlier. The following examples should be tested separately with event handlers set up to process the results; they are not intended to be called one after the other in succession.

// this will start a purchase dialog and on success callback the PURCHASE_SUCCEEDED event: AndroidIAB.androidIAB.testPurchaseItemSuccess(); // this will start a purchase dialog then fake a PURCHASE_REFUNDED event AndroidIAB.androidIAB.testPurchaseItemRefunded(); // this will start a purchase dialog then fake a PURCHASE_CANCELLED event AndroidIAB.androidIAB.testPurchaseItemCancelled(); // this will start a purchase dialog and fake a PURCHASE_FAILED error event, // with a reason of ITEM_UNAVAILABLE AndroidIAB.androidIAB.testPurchaseItemUnavailable();

Testing the API with real item purchases

It is also possible to test the purchase flow in an unpublished application using real In-App Purchase IDs, with a few restrictions:

  • The Google account associate with the device must be a Test Account Email, and not a Registered Developer Email. This is because Google will not allow you to buy items from yourself. Unfortunately, the only way to change the Google account for the device is to perform a factory reset, which is done by selecting Settings > Privacy > Factory Reset; enter your Test Account Email when prompted.
  • The application must be Saved in the Android Market Developer website, as described in Setting up your app with your Android Market publishing account. It does not need to be Published, however. You can test without making your application public.
  • The In-App Purchase IDs (each referenced as an itemId in your code) you are testing must be Published, as described in Setting up your app with your Android Market publishing account. The application itself need not be published, however.
  • Real money will be withdrawn from the account associated with the Test Account Email. You can prevent this by logging into the Android Market Developer website after making a purchase, and clicking Cancel Entire Order or Refund Some Money. This will cause an asynchronous AndroidBillingEvent.PURCHASE_CANCELLED or AndroidBillingEvent.PURCHASE_REFUNDED event to fire.
5. Refunding or cancelling a purchase.
5. Refunding or cancelling a purchase.

Updating your application descriptor file

You need to configure your AIR application descriptor file to use the AIR 3.0 SDK (or later), include the In-App Billing extension, and update the Android manifest additions with some Android Billing specific settings. For a working example, see example/app.xml.

  1. Set your AIR SDK to 3.0 in the app descriptor file:
<application xmlns="http://ns.adobe.com/air/application/3.0">
  1. Include a link to the extension in the descriptor:
<extensions> <extensionID>com.milkmangames.extensions.AndroidIAB</extensionID> </extensions>
  1. Update your Android manifest additions. The android.permission.INTERNET and com.android.vending.BILLING permissions must be present for In-App Billing to work. You also must add the com.android.vending.billing.IN_APP_NOTIFY , com.android.vending.billing.RESPONSE_CODE , and com.android.vending.billing.PURCHASE_STATE_CHANGED actions within the <intent-filter> element, as shown below:
<android> <manifestAdditions><![CDATA[ <manifest android:installLocation="auto"> <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="com.android.vending.BILLING" /> <application> <service android:name="com.milkmangames.extensions.android.IABBillingService" /> <receiver android:name="com.milkmangames.extensions.android.IABBillingReceiver"> <intent-filter> <action android:name="com.android.vending.billing.IN_APP_NOTIFY" /> <action android:name="com.android.vending.billing.RESPONSE_CODE" /> <action android:name="com.android.vending.billing.PURCHASE_STATE_CHANGED" /> </intent-filter> </receiver> </application> </manifest> ]]></manifestAdditions> </android>

Building and troubleshooting your app

If you're using Flash Builder 4.6 or later, or Flash Professional CS6 or later, and have added the In-App Billing for Android extension library as described above, then you can compile as you usually do directly from the IDE. If not and you are building your app with the extension from the command line, then you'll need to specify the directory containing the com.milkmangames.nativeextensions.AndroidIAB.ane file.

Here is an example build command line:

[PATH_TO_AIR_SDK]\bin\adt -package -target apk-debug -storetype pkcs12 -keystore [YOUR_KEYSTORE_FILE] -storepass [YOUR_PASSWORD] anesample.apk app.xml anesample.swf -extdir [DIRECTORY_CONTAINING_ANE_FILE]

If your app is not receiving events as expected, try these tips:

  • Make sure you've saved a draft of the application to the Android Market Developer Website as described in Setting up your app with your Android Market publishing account.
  • Make sure you've updated your application descriptor file as described in Updating your application descriptor file.
  • Make sure the Google email address associated with your device is a Registered Developer Email or a Test Account Email.
  • If you're testing the IABSample application as is, make sure that you've created the In-App Product IDs that it uses: a managed product named my_levelpack and an unmanaged one named my_spell . See Setting up your app with your Android Market publishing account for information on how to set up products.

Where to go from here

Now that you have the In-App Billing Extension for Android up and running, you may want to explore the ActionScript 3 documentation or check out the Game Center, iAd, AdMob or other tools from available from Milkman Games.

Creative Commons License
This work is licensed under a Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 Unported License.

More Like This

  • What's new in Adobe AIR 3
  • Installation and deployment options in Adobe AIR 3
  • Developing cross-platform Adobe AIR applications
  • 10 common mistakes when building Adobe AIR applications
  • Tips for building AIR applications that can be easily updated
  • Adobe AIR and the experience brand
  • Uploading images from CameraRoll and CameraUI
  • Getting started with Adobe AIR for Flex and ActionScript 3 developers
  • Ten tips for building better Adobe AIR applications
  • Deploying Adobe AIR applications seamlessly with badge install

Tutorials and samples

Tutorials

  • Using the iOS Simulator to test and debug AIR applications
  • Using the Amazon In-App Purchase Adobe AIR native extension for Android and Kindle Fire
  • Transferring data with AIR native extensions for iOS – Part 3
  • Exchanging Vector and Array objects between ActionScript 3 and C, C++, or Objective-C

Samples

  • Licensing Adobe AIR applications on Android
  • Using web fonts with Adobe AIR 2.5
  • Using Badger for Adobe AIR applications

AIR blogs

More
07/09/2012 Protected: Publishing Adobe AIR 3.0 for TV on Reference Devices
07/08/2012 Source Code: Adobe AIR 3.3 Retina Video Application
07/06/2012 Application specific File Storage on Adobe AIR based ios Application
07/04/2012 Recent Work - iPad/Android App: Inside My toyota

AIR Cookbooks

More
02/09/2012 Using Camera with a MediaContainer instead of VideoDisplay
01/20/2012 Skinnable Transform Tool
01/18/2012 Recording webcam video & audio in a flv file on local drive
12/12/2011 Date calculations using 'out-of-the-box' functions

Products

  • Acrobat
  • Creative Cloud
  • Creative Suite
  • Digital Marketing Suite
  • Digital Publishing Suite
  • Elements
  • Mobile Apps
  • Photoshop
  • Touch Apps
  • Student and Teacher Editions

Solutions

  • Digital marketing
  • Digital media
  • Web Experience Management

Industries

  • Education
  • Financial services
  • Government

Help

  • Product help centers
  • Orders and returns
  • Downloading and installing
  • My Adobe

Learning

  • Adobe Developer Connection
  • Adobe TV
  • Training and certification
  • Forums
  • Design Center

Ways to buy

  • For personal and home office
  • For students, educators, and staff
  • For small and medium businesses
  • For businesses, schools, and government
  • Special offers

Downloads

  • Adobe Reader
  • Adobe Flash Player
  • Adobe AIR
  • Adobe Shockwave Player

Company

  • News room
  • Partner programs
  • Corporate social responsibility
  • Career opportunities
  • Investor Relations
  • Events
  • Legal
  • Security
  • Contact Adobe
Choose your region United States (Change)
Choose your region Close

North America

Europe, Middle East and Africa

Asia Pacific

  • Canada - English
  • Canada - Français
  • Latinoamérica
  • México
  • United States

South America

  • Brasil
  • Africa - English
  • Österreich - Deutsch
  • Belgium - English
  • Belgique - Français
  • België - Nederlands
  • България
  • Hrvatska
  • Česká republika
  • Danmark
  • Eastern Europe - English
  • Eesti
  • Suomi
  • France
  • Deutschland
  • Magyarország
  • Ireland
  • Israel - English
  • ישראל - עברית
  • Italia
  • Latvija
  • Lietuva
  • Luxembourg - Deutsch
  • Luxembourg - English
  • Luxembourg - Français
  • الشرق الأوسط وشمال أفريقيا - اللغة العربية
  • Middle East and North Africa - English
  • Moyen-Orient et Afrique du Nord - Français
  • Nederland
  • Norge
  • Polska
  • Portugal
  • România
  • Россия
  • Srbija
  • Slovensko
  • Slovenija
  • España
  • Sverige
  • Schweiz - Deutsch
  • Suisse - Français
  • Svizzera - Italiano
  • Türkiye
  • Україна
  • United Kingdom
  • Australia
  • 中国
  • 中國香港特別行政區
  • Hong Kong S.A.R. of China
  • India - English
  • 日本
  • 한국
  • New Zealand
  • 台灣

Southeast Asia

  • Includes Indonesia, Malaysia, Philippines, Singapore, Thailand, and Vietnam - English

Copyright © 2012 Adobe Systems Incorporated. All rights reserved.

Terms of Use | Privacy Policy and Cookies (Updated)

Ad Choices

Reviewed by TRUSTe: site privacy statement