November 24, 2014
Hot Topics:

Enabling In-App Purchases in Your Windows Phone 8 Application

  • July 19, 2013
  • By Vipul Patel
  • Send Email »
  • More Articles »

Introduction

Windows Phone developers can monetize from the platform by enabling in-app purchases. There is a growing trend amongst developers to offer their application for free and upsell through digital goodies via in-app purchases.

With Windows Phone 8, Microsoft has introduced APIs to allow application developers to enable in-app purchasing scenarios.

In-App Purchase Fundamentals

To support in-app purchases, a Windows Phone developer needs to create products that can be sold in their applications and provide clear information about these. From an application standpoint, they need to create an ability to initiate an in-app purchase and also ensure product delivery/enabled upon a successful in-app purchase.

Microsoft provides a purchase user experience that is consistent across applications, and ensures authenticity of purchases in addition to the ability to pay application developers in 190 different countries.

The general flow is:

1. Application is submitted in the Dev center.

2. A virtual product list is submitted that can to be bought as an in-app purchase for the above submitted app.

3. These products should be available for listing in the application, to allow the user to choose from.

4. Upon in-app purchase initiation, the user is presented with a consistent purchasing experience, which is part of Windows Phone 8 platform.

5. Upon application launch/resumption and successful in-app purchase, the product license should be checked to ensure that the user has permissions to the content.

6. The application can get receipts (containing digital signatures) for all products purchased by the user.

7. Digital content is now available for download.

Content, which is available for in-app purchases can be durable (purchased once and then owned by the user forever) or consumable (items that need to be replenished frequently, like game points, game tokens).

Hands On

We will build a sample application, which will offer one token as to users as an in-app purchase. Upon successful purchase, the application will list the total number of tokens purchased.

Create a new Visual Studio 2012 project titled WindowsPhoneInAppPurchaseDemo.

New Visual Studio 2012 project
New Visual Studio 2012 project

When prompted, select Windows Phone OS 8.0 as the target OS.

Target Windows Phone OS Version
Target Windows Phone OS Version

Next, on MainPage.xaml, add the following controls: one checkbox titled “1 token”, one button titled “Purchase’,1 textblock titled “Purchased quantity” and one textbox to contain the total number of tokens purchased and available for use.

To enable testing without needing to deploy, we will be using the Mock in-app purchase library, which is available for download from http://code.msdn.microsoft.com/wpapps/Mock-In-App-Purchase-33080f0c.

Grab only the MockIAPLib project and copy it next to our current project. Next, add the MockIAPLib project to our current solution.

Add a reference to MockIAPLib from our project by right-clicking on our project and selecting “Add Reference”.

This mock library will allow us to simulate in-app purchases without needing to have our application submitted or our virtual item listed on Microsoft AppHub.

To ensure that we do not use the mock library in released code, add the following to the beginning of every C# file (including app.xaml.cs and MainPage.xaml.cs).

#if DEBUG
using MockIAPLib;
using Store = MockIAPLib;
#else
using Windows.ApplicationModel.Store;
#endif

Next, declare a global token counter, which will keep a tab on how many tokens we have purchased via in-app purchases.

namespace WindowsPhoneInAppPurchaseDemo
{
    public partial class MainPage : PhoneApplicationPage
    {
        int tokenCount = 0;
        // Constructor
        public MainPage()
        {

Next, we will add the code to handle the click event of the Purchase  button. We need to make sure that the item was checked and only allow the transaction if it is checked. If the purchase is completed successfully, we will call helper methods to complete the fulfillment and finally, update the token count.

In this method, we need to list all of the available items for in-app purchase for our application. If the purchase is submitted, we will call the CurrentApp.RequestProductPurchaseAsync  method with the product Id and a flag to indicate if a receipt should be included or not.

        private async void buttonPurchase_Click(object sender, RoutedEventArgs e)
        {
#if DEBUG
            MockIAPLib.ListingInformation listings = await MockIAPLib.CurrentApp.LoadListingInformationByProductIdsAsync(
                                    new string[] { "1 token"});
#else
            ListingInformation listings = await CurrentApp.LoadListingInformationByProductIdsAsync(
                                    new string[] { "1 token"});
#endif
            if (checkBoxTokens.IsChecked == true)
            {
#if DEBUG
                await MockIAPLib.CurrentApp.RequestProductPurchaseAsync(listings.ProductListings.ToList()[0].Value.ProductId, false);
#else
                await CurrentApp.RequestProductPurchaseAsync(listings.ProductListings.ToList()[0].Value.ProductId, false);
#endif
 
                CompleteFulfillMent();
            }
            textBoxCount.Text = tokenCount.ToString();
        }
 

Next, we will implement the method that handles the fulfillment completion. In this method, we will extract the current product licenses for our application and if the license is active (for a recently purchased item), the application can now start the fulfillment (download the digital goodies just purchased).

Finally, we need to wire up the mock library in our application.

Implement a method to instantiate the Mock library and provide it the catalog contents. This needs to be done in App.xaml.cs.

        private void SetupMockIAP()
        {
#if DEBUG
            MockIAP.Init();
 
            MockIAP.RunInMockMode(true);
            MockIAP.SetListingInformation(1, "en-us", "A description", "1", "1 token");
 
            // Add some more items manually.
            ProductListing p = new ProductListing
            {
                Name = "1 token",
                ProductId = "1 token",
                ProductType = Windows.ApplicationModel.Store.ProductType.Consumable,
                Keywords = new string[] { "image" },
                Description = "An image",
                FormattedPrice = "1.0",
                Tag = string.Empty
            };
            MockIAP.AddProductListing("1 token", p);
#endif
 
        }
Finall

Finally, we add code to call the newly implemented method from the end of the App’s constructor.

public App()
        {
            // Global handler for uncaught exceptions.
            UnhandledException += Application_UnhandledException;
 
            // Standard XAML initialization
            InitializeComponent();
 
            // Phone-specific initialization
            InitializePhoneApplication();
 
            // Language display initialization
            InitializeLanguage();
 
            // Show graphics profiling information while debugging.
            if (Debugger.IsAttached)
            {
                // Display the current frame rate counters.
                Application.Current.Host.Settings.EnableFrameRateCounter = true;
 
                // Show the areas of the app that are being redrawn in each frame.
                //Application.Current.Host.Settings.EnableRedrawRegions = true;
 
                // Enable non-production analysis visualization mode,
                // which shows areas of a page that are handed off to GPU with a colored overlay.
                //Application.Current.Host.Settings.EnableCacheVisualization = true;
 
                // Prevent the screen from turning off while under the debugger by disabling
                // the application's idle detection.
                // Caution:- Use this under debug mode only. Application that disables user idle detection will continue to run
                // and consume battery power when the user is not using the phone.
                PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;
            }
 
            SetupMockIAP();
 
        }

We now have a fully functional test application that can simulate an in-app purchase. If you have trouble following along, you can download the sample listing from here

Running the Application

When the application is executed in the emulator (note that you need to be compiling this as Debug to ensure the mock library will work, else you will need to register and deploy the application in AppHub before you can execute this successfully in Release mode).

Execute the App
Execute the App

Check the “1 token” checkbox and click purchase.

Mock UI
Mock UI

When you click OK, the purchase is completed  and we can see that the purchased quantity has been updated to 1.

Quantity Purchased
Quantity Purchased

As we make more in-app purchases, you will notice that the purchased quantity count goes up with every successful transaction.

Summary

In this article, we learned about in-app purchase. I hope you have found this information useful.

About the Author

Vipul Patel is a Program Manager currently working at Amazon Corporation. He has formerly worked at Microsoft in the Lync team and in the .NET team (in the Base Class libraries and the Debugging and Profiling team). He can be reached at vipul.patel@hotmail.com


Tags: application, Windows Phone 8, In-app Purchasing




Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Sitemap | Contact Us

Rocket Fuel