Government 2013

Volume 28 Number 10A

Windows Phone - Enhance Citizen Services with Windows Phone 8 Wallet and NFC

By Joel Reyes

City governments all over the world face tremendous challenges dealing with shrinking budgets while attempting to provide high-quality services to increasingly tech-savvy citizens. With enhanced mobile application capabilities and support for convenient payment and loyalty programs, Windows Phone 8 Near Field Communication (NFC) and Wallet functionality can help governments meet these challenges.

In this article, we’ll take a look at the details of these technologies, as well as a sample app involving a fictional local transit system. The example presented here could easily be adapted to fit other scenarios involving justice, public safety, health care and other government services. You can download the sample app from msdn.com/magazine/msdnmaggov13.

Wallet and NFC Platform Elements

Windows Phone 8 provides a Wallet app and NFC capabilities that are separate yet complementary. The idea of a digital wallet is to free users from the burden of the concrete, non-virtual version, but without losing any of the functionality. The Windows Phone 8 Wallet can store a variety of cards—such as credit and debit cards, loyalty cards, membership cards, and coupons—and supports payment transactions. You can also track card balances and transactions, set up payment cards for purchasing apps and games, browse for local deals, and more. Figure 1 shows the Windows Phone 8 Wallet hub app.

Windows Phone 8 Wallet Hub App
Figure 1 Windows Phone 8 Wallet Hub App

Windows Phone 8 NFC lets devices in close proximity share content such as photos or contacts. It can also establish a Bluetooth connection with something like a wireless speaker, for example. NFC standards deliver data packets between such devices using low-powered radio technology operating at 13.56 MHz. A range of mobile devices use NFC, including Windows Phone 8 and Windows 8 devices, wireless speakers, phone-charging stands, and payment terminals, as well as inexpensive NFC tags that can be embedded in or affixed to objects via stickers.

NFC tags can contain small amounts of data, such as URLs or map coordinates, that a device with an NFC antenna can read. NFC tags don’t require their own power source because they’re driven by the electro-magnetic field of the NFC device reading the tag. A common scenario could be NFC posters in transit stations that bring up a system map when the user taps on the poster.

The NFC Forum (nfc-forum.org) is the primary organization that standardizes communications between participating NFC devices. The most important specification for our purposes is the NFC Data Exchange Format (NDEF) that describes messages exchanged between NFC devices and tags. The specification defines a binary structure that can encode multiple records with different types of payloads. These are identified by headers for parsing the payload contents.

There are NDEF record types defined for a variety of uses. NDEF URI records work across platforms to open Web pages, or apps can listen for a specific URI regardless of mobile OS. NDEF launching records can target specific platforms. The LaunchApp record, for example, is designed to invoke an application on the Windows Phone 8 platform. The NDEF record contains a GUID for a Windows Phone 8 app, as well as other parameters that provide context to the application launch, such as a transit station ID:

Windows.com/LaunchApp\tWindowsPhone&{1c3daa50-856d-46e1-bffb-5d91f2768c88}\tstationid=5

Encoding multiple types of records on a single tag message lets a single tag support a variety of devices and capabilities without diminishing the UX.

Integrating an App with the Wallet

A Windows Phone 8 application can integrate with the Wallet API at different levels, as Figure 2illustrates.

Integrating the Wallet API into a Windows Phone 8 App
Figure 2 Integrating the Wallet API into a Windows Phone 8 App

A Wallet application on Windows Phone can create, read, update and delete (CRUD) Wallet items using the Wallet APIs provided in the Windows Phone SDK. A Wallet item will show up in the Wallet, and can have links that navigate to the application that created the item. You can also pin Wallet items to Start for fast access.

Wallet agents are specialized background agents an application can use to update Wallet items. They update Wallet data without direct execution by the owning application. This way, Wallet items can be updated with an application’s supporting services when the user interacts with the Wallet hub.

NFC payment and NFC transactions with the Wallet require close collaboration between services providers, mobile operators and Microsoft. Drilling into the specifics of this collaboration is beyond the scope of this article.

The Wallet API

The core entry point to the Wallet API is the Wallet class, which has methods to retrieve or delete Wallet items. Several classes are derived from the Wallet Item class based on the type of information the Wallet item contains. For example, there could be items whose properties are used for deals and coupons, and those that represent cards with a transaction history. Figure 3 represents the types used in a Wallet app. 

Windows Phone 8 Wallet Object Model
Figure 3 Windows Phone 8 Wallet Object Model

OnlinePaymentInstrument handles payment cards, such as debit and credit cards. WalletTransactionItem handles cards used for membership, loyalty or other programs that can also store a list of transactions. Deal represents coupons or prepaid offers.

AddWalletItemTask is part of the Microsoft.Phone.Tasks namespace. This lets an application launch the Wallet application and display a dialog to save a Wallet item to the Wallet. The user can then choose to add the item to his Wallet.

Windows Phone 8 apps use a manifest file called WMApp­Manifest.xml to define an app’s feature set. New capabilities have been added to Windows Phone 8 to support the Wallet.

ID_CAP_WALLET is the basic point of entry for using Wallet features for membership and loyalty cards and deals, such as the one we’ll create in our sample application. Use IP_CAP_PAYMENT­INSTRUMENTS and IP_CAP_WALLET_SECUREELEMENT with apps that require payment card or secure NFC functionality. We’ll also enable ID_CAP_PROXIMITY, which supports the NFC features of the Proximity API. (You can also require NFC support from the Requirements tab by selecting ID_REQ_NFC.)

The Proximity API

The Proximity API is a cross-platform library for Windows Phone 8 and Windows 8 that supports a wide range of scenarios for establishing communications using proximity technologies. NFC tag support is a subset that centers on the ProximityDevice class. You can see a complete list of key methods in the ProximityDevice class at bit.ly/1avHJP4.

NDEF Library for Proximity APIs/NFC

The open source NDEF Library lets you easily parse and create NDEF records with the Windows Proximity APIs (NFC) for Windows 8 and Windows Phone 8. It extends the basic NDEF message support of the Proximity API with an object model for standardized NDEF record types, including the LaunchApp protocol for Windows Phone 8 apps that we use in our mobile Contoso Transit sample application. You can find the NDEF Library at bit.ly/XalLON or import it via the NuGet package manager in Visual Studio.

The creator of the NFC interactor (aka.ms/NDEFLibrary) contributed the NDEF Library to the development community. This excellent Windows Phone 8 app can not only create any NFC tag type, but also read and clone existing tags and dive into the guts of NDEF messages to assist in debugging any message format issues.

Debrief: Windows Phone 8 Wallet/NFC

The ubiquity of mobile technology has changed our lives—as well as what we expect of government services. This article explores the digital wallet and Near Field Communication (NFC) technology built into Windows Phone 8, which can enable powerful new scenarios for citizen services.

IT Brief:

Technology decision makers and developers alike are responsible for finding new opportunities to reduce costs, increase revenue and enhance citizen engagement. They must also maximize current infrastructure investments. Windows Phone 8 is built with that in mind and lets IT managers conceive new solutions without sacrificing current investment in the Microsoft platform. 

Wallet and NFC are capabilities built directly into the Windows Phone 8 platform, which allows the development of new apps reusing the same skills, tools and development platform you already have. People from all walks of life are already using mobile devices. IT planners now have the opportunity to deliver mobile city services that are engaging and profitable.

Windows Phone 8 Wallet and NFC can help city IT departments:

  • Envision new delivery scenarios
  • Increase citizen participation and engagement
  • Accelerate and increase revenue
  • Derive new value from current infrastructure investments

Dev Brief:

The Windows Phone Wallet API makes it simple to implement cards into any mobile app. The platform does the heavy lifting for the NFC plumbing, and the API exposes a simple proximity object model that abstracts all the underlying communication protocols. This means developers can stay focused on creating the best application features.

With the full programmability of the Wallet API and NFC, developers can:

  • Take full control of Wallet items so they can be read, updated and deleted
  • Create custom NFC tags by writing to the tags
  • Leverage familiar skills and tools

More Information:

The Contoso Transit App

Now let’s look at a sample transit agency application for the fictional City of Contoso that integrates with Windows Phone 8 Wallet and NFC functionality (see Figure 4). This mobile app offers basic informational services for a set of transit stations, including the arrival time of the next train. It also provides a loyalty card integrated with the Windows Phone 8 Wallet that tracks rider activities, lets users accrue points and offers deals for discounts with affiliated businesses.

The Contoso Transit App
Figure 4 The Contoso Transit App

The app’s NFC functionality lets a rider tap an NFC tag located in a train station and launch the app to the appropriate station. If the user has the loyalty card enabled, the app will automatically check him in for loyalty points and deal offerings. If the application isn’t installed on the device, it will prompt the user to download it from the store. 

The sample solution consists of three Visual Studio projects:

  1. Windows Phone 8 application project with the core application functionality
  2. Windows Phone 8 library housing the mock Web service that represents the loyalty program back-end systems
  3. Windows Phone 8 Background Task project with the code for the Wallet agent

Creating the Wallet Loyalty Card

The MainPage.xaml page is the application hub. This has links to navigate to stations, display or create the loyalty card associated with the app, or write out data to an NFC tag.

The application wires up a reference to the mock Web service for the transit agency back end in the constructor to display the stations. It also sets up an AddWalletItemTask object, which is key to creating a new wallet item after prompting the user:

public MainPage()
{
  InitializeComponent();
  service = new MockTransitService();
  addTask = new AddWalletItemTask();
  addTask.Completed +=task_Completed;
}
MockTransitService service;
WalletTransactionItem walletCard;
AddWalletItemTask addTask;

The Wallet.FindItem method is used to materialize a reference to the Wallet item representing the loyalty card, if it exists. If the card is found, we display the current balance, one of the properties available on the Wallet­TransactionItem class:

protected override void OnNavigatedTo(NavigationEventArgs e)
{
  ... // Code removed for clarity
  walletCard = Wallet.FindItem("LoyaltyCard") as
    WalletTransactionItem;
  if (walletCard != null)
  {
    balanceTxt.Text = walletCard.DisplayBalance;
  }
  ... // Code removed for clarity       
}

The code to add the Wallet calls the mock Web service to get the user’s loyalty card data:

LoyaltyCardModel loyaltyCard = service.GetLoyaltyCard("123456");
WalletTransactionItem item = new WalletTransactionItem("LoyaltyCard");
item.CustomerName = loyaltyCard.Name;
item.AccountNumber = loyaltyCard.UserId;
item.DisplayName = "Contoso Transit";
item.IssuerName = "Contoso Transit";
item.IssuerPhone.Business = "888-555-1212";
item.IssuerWebsite = new Uri("http://microsoft.com");
item.DisplayBalance = loyaltyCard.PointBalance + " points";

Here you can also include the code to add an image for the item.

If no card is found, the code invokes the AddWalletItemTask to prompt the user to create the card. Then it receives a callback to update the UI with the balance:

if (e.TaskResult == TaskResult.OK)
{
  walletCard = e.Item as WalletTransactionItem;
  balanceTxt.Text = walletCard.DisplayBalance;
  NavigationService.Navigate(new Uri("/CardPage.xaml", UriKind.Relative));
}

In the sample app, we preload the account so it already has a balance and a transaction. At that point, it navigates to the CardPage.xaml page, which shows the details. A real-world app would include a signup or authentication process on the front end to identify a user. 

You can go to the Wallet app directly in Windows Phone 8 to see we created a card with all the details. You can also see the back link to the app that lets the user go back to the Transit app from the Wallet.

Station Check-In Function and Updating the Card

The StationPage provides details on station time, as well as a check-in function if there’s a loyalty card enabled. The check-in button code updates the points balance after checking in with the mock Transit Web service and looks for a deal to add to the Wallet. This is a simple idea for rewarding users with points and deals that could easily be expanded for all kinds of interesting scenarios. Updating the WalletTransactionItem is as simple as updating its properties and calling its SaveAsync method, as shown in Figure 5.

Figure 5 Updating a Loyalty Card in the Wallet

private async Task UpdateLoyaltyCard(int stationId)
{           
  int balance = service.UpdatePointsOnCheckIn(walletCard.AccountNumber, stationId);
  walletCard.DisplayBalance = balance + " points";
  DealModel deal = service.GetDealForStationCheckIn(stationId);
  if (deal != null)
  {
    string prompt = String.Format("A deal is available for {0} from {1}. 
      Add to wallet?", deal.Name, deal.Issuer);
    MessageBoxResult result = MessageBox.Show(
      prompt, "Coupon available", MessageBoxButton.OKCancel);
    if (result == MessageBoxResult.OK)
    {
      await AddDealToWallet(deal);
    }
}
  await walletCard.SaveAsync();
}

The Deal class represents the coupons in the Wallet. It has a variety of properties that describe a wide range of deals. It also includes images so you can embed barcodes to support redemption systems with optical readers. Instead of having to create a deal with a special task, you simply instantiate the class and call its SaveAsync, as shown in Figure 6. The sample app prompts the user to determine whether to add the deal to his Wallet.

Figure 6 Adding a Deal to the Wallet

private static async Task AddDealToWallet(DealModel model)
{
  Deal deal = new Deal();
  deal.DisplayName = model.Name;
  deal.IssuerName = model.Issuer;
  deal.StartDate = DateTime.Now;
  deal.ExpirationDate = DateTime.Now.AddDays(model.DaysValid);
  deal.IsUsed = false;
  deal.Code = model.Code;
  deal.MerchantName = model.Issuer;
  deal.MerchantPhone.Business = model.MerchantPhone;
  await deal.SaveAsync();
}

You can include code for adding bitmap images here as well.

Updating the Transaction History in the Wallet Agent

The Wallet Agent project shows how an agent updates Wallet items in the background. The key method is OnRefreshData, shown in Figure 7. This works with the mock Transit Web service to update the transaction details by creating WalletTransactionItem objects and adding them to the card’s TransactionHistory dictionary. We use the datetime of the transaction to ensure the entries are in the collection and up-to-date. 

Figure 7 The OnRefreshData Method

protected override async void OnRefreshData(RefreshDataEventArgs args)
{
  MockTransitService service = new MockTransitService();
  foreach (WalletItem item in args.Items)
  {
    WalletTransactionItem walletCard = item as WalletTransactionItem;
    if (walletCard != null)
    {
      LoyaltyCardModel loyaltyCard = service.GetLoyaltyCard(
        walletCard.AccountNumber);
      if (loyaltyCard != null)
      {
        foreach (var scan in loyaltyCard.StationsScanned.Keys)
        {
          if (!walletCard.TransactionHistory.ContainsKey(scan.ToString()))
          {
            StationModel station = loyaltyCard.StationsScanned[scan];
            WalletTransaction txn = new WalletTransaction();
            txn.TransactionDate = DateTime.Now;
            txn.Description = station.Name;
            txn.DisplayAmount = station.Points + " points";
            walletCard.TransactionHistory.Add(DateTime.Now.ToString(), txn);
          }
        }
      }
    await walletCard.SaveAsync();
    }
  }
  NotifyComplete();
}

Checking in at a Station with an NFC Tag

The sample’s NFC functionality lets a properly formatted tag launch the app and navigate to a station using the LaunchApp protocol. Windows Phone 8 translates the parameters passed from this NFC record into a special-purpose URL parameter named ms_nfp_launchargs. You can identify this in the startup page of your app, as shown in Figure 8.

Figure 8 The ms_nfp_launchargs Parameter

protected override void OnNavigatedTo(NavigationEventArgs e)
  {
    String launchArgs;
    if (NavigationContext.QueryString.TryGetValue(
      "ms_nfp_launchargs", out launchArgs))
    {
      if (launchArgs.Contains("stationid="))
      {
        string stationId = launchArgs.Substring(
          launchArgs.IndexOf("stationid=") + 10);
        NavigationService.Navigate(new Uri(
          "/StationPage.xaml?checkin=true&stationid=" +
          stationId, UriKind.Relative));
        NavigationService.RemoveBackEntry();
      }
    }
... // Code removed for clarity

We parse the message to get the appropriate station ID, and then navigate there with a special parameter the station uses to automatically check in the user. If a user taps a tag, the device will prompt him to confirm that he wants to handle the tag contents with the Contoso Transit app.

Writing an NFC tag

To test the NFC scenario, the app contains a small writing page named WriteTag.xaml. This shows how to use the Proximity API for locating and writing to a tag. The first step is to get the default ProximityDevice representing the NFC hardware on the phone in the page constructor:

public WriteTagPage()
  {
    InitializeComponent();
    device = ProximityDevice.GetDefault();
    service = new MockTransitService();
  }

When the end user selects the station to which he wants to write, we call the SubscribeForMessage method to find a writeable tag, as shown in Figure 9.

Figure 9 The SubscribeForMessage Method

private void writeBtn_Click(object sender, RoutedEventArgs e)
  {
    station = stationLst.SelectedItem as StationModel;
    if (station != null)
    {
      if (device != null)
      {
        writeBtn.Visibility = System.Windows.Visibility.Collapsed;
        device.SubscribeForMessage("WriteableTag", TagLocated);
        statusTxt.Text = "Tap tag you wish to write";
      }
      else
      {
        MessageBox.Show("Unable to initialize NFC hardware");
      }
    }
    else
    {
      MessageBox.Show("Please select a station for the tag info");
    }
  }

Once the tag is located, it’s just a matter of creating the NDEF message using the NDEF Library NdefLaunchAppRecord and publishing the message using ProximityDevice method Publish­BinaryMessage, as shown in Figure 10. The app Id GUID is harvested from the phone’s application model API. You can also find it in the WMAppManifest.xml file.

Figure 10 Creating and Publishing an NDEF Message

private void TagLocated(ProximityDevice sender, ProximityMessage message)
{
  device.StopSubscribingForMessage(message.SubscriptionId);
  string appId = Windows.ApplicationModel.Store.CurrentApp.AppId.ToString();
  string stationArgs = "stationid=" + station.Id;
  NdefLaunchAppRecord launchAppRecord =
    new NdefLibrary.Ndef.NdefLaunchAppRecord();
  launchAppRecord.Arguments = stationArgs;
  launchAppRecord.AddPlatformAppId("WindowsPhone", "{" + appId + "}");
  NdefMessage msg = new NdefMessage { launchAppRecord };
  device.PublishBinaryMessage("NDEF:WriteTag",
    msg.ToByteArray().AsBuffer(), TagWritten);
}

Wrapping Up

Windows Phone 8 provides a great platform and API. They ease the burden of building mobile solutions that involve digital wallets and NFC technologies. This example illustrates one way of using them to improve the quality and efficiency of city services in a transit agency. You could easily adapt the same techniques to other government solutions including health care, public safety and other areas of citizen-service delivery.


Dale Michalk is a solution achitect for Microsoft Public Sector.

Joel Reyes is a startup/citizenship evangelist for Microsoft Public Sector.

Thanks to the following technical expert for reviewing this article: David Gardner (Microsoft)
David is a Program Manager on Windows Phone working to define new ways for mobile phone users to interact with retailers and merchants.