Windows phone app example code

Implementing In-App Purchase on Windows Phone 8

In-app purchases are an excellent way to increase revenue for your Windows Phone app. In this tutorial, I’ll be showing you how to implement in-app purchases in a Windows Phone 8 Silverlight application.

To test your application, you’ll need to create a product to test with. This means that you’ll need an active Windows Phone developer account if you want to follow along.

Introduction

Windows Phone 8 provides a convenient purchase experience, reliable payouts, geo-distributed services, and product management tools to achieve meaningful commerce in your app. You can choose between in-app purchases and other payment options (for example PayPal), but in-app purchases give you more flexibility as they provide:

  • management of products using the Windows Phone developer portal
  • geo-distributed services and payouts in more than 190 countries
  • consistent purchase experience for users across all apps on the phone and proof of authenticity through secure receipts

1. Get an App ID

In the Windows Phone developer portal’s dashboard, browse to the Details tab of your app and make a note of the App ID. Also grab your Publisher GUID from the developer portal. You’re going to need these details later to update the application manifest file.

If you are developing a new app, then go to the dashboard and click on Submit App to start the submission process and reserve a name for your app. Save these details and you can skip submitting the XAP file for now. Just note the App ID from the App properties section.

2. Add a Product to Your App

Under application details, there is a Products tab where you can add and manage in-app products for your app. For the purpose of this demonstration, we have created a product named Premium App.

In the Windows Phone developer portal, you need to add your in-app product’s properties and description. You can optionally set custom pricing in different markets for your product.

You need to fill in the properties of your in-app product as shown in the following screenshot. Remember the Product Identifier as you will need it for listing in-app products in your app.

Here are a few things worth remembering while adding an in-app product:

  • You can have multiple products for an app. Each product can be consumable or durable. Durable products can only be bought once.
  • Universal apps can share in-app products, letting users buy once and use anywhere. Your in-app product category can differ, but the product name and identity should match for this to work.
  • You can define custom pricing for your products in different countries.

The description section requires you to add a product title, description, and image for the in-app product as shown in the screenshot below.

Note that it may take one or two hours to process your submission before the product is published.

3. Update Application Manifest

It’s time to update the application manifest by adding the App ID and Publisher GUID, which you copied from the Windows Phone developer portal. Using the Solution Explorer of your project, browse to Properties and locate WMAppManifest.xml.

Visual Studio assigns a random Product ID and Publisher ID when you create a new project, which you need to change by going to the Packaging tab. If you are targeting only Windows Phone 8.1, then you need to update Package.appmanifest in addition to WMAppManifest.xml.

4. List In-App Products in Your App

The app uses the in-app purchase API available in the Windows Phone SDK to fetch products and list them. The user now has an option to purchase these products from within the app. Depending on the application you are building, you may want to list specific products in different places, but for the purpose of the demonstration let’s display all the products associated with the app and handle the purchase flow.

We need an ItemsControl to hold the products. The following code snippet shows how you can define the data template of your ItemsControl and bind the products to it. Notice that the buy button is visible only if the user hasn’t purchased the product. Feel free to play with the data template to make it more attractive.

The public class ProductItem stores all the information related to a particular product. There is an ObservableCollection of type ProductItem named picItems , which stores all the products.

The next step is to add a function RenderStoreItems in the code behind to list all the products for the application. This function makes an asynchronous call to LoadListingInformationAsync to render the products for the current application. The function then iterates through every product, checking its license information and adding it to the list. We bind the name, purchase status, and price to the list box, and display it to the user.

Note that you need to enter a correct App ID, Publisher ID, and Product ID before you can deploy the sample project with this tutorial.

Next, you need to add the click event handler for the buy button. The function ButtonBuyNow_Clicked initiates the purchase. The user is presented with a purchase experience that’s part of the Windows Phone 8 platform. When the purchase is complete, you can enable a locked feature or let the user download additional content. This is entirely up to you.

Читайте также:  Ошибка 110 астра линукс

5. After the Purchase

You can use the in-app purchase API to enumerate the licenses the user has for the products in your app when the app is launched or resumed, or after a purchase. This lets you determine whether the user already owns the product he or she licensed, or whether its fulfillment is still pending. You can also retrieve receipts for the products purchased by the user to verify if the transaction took place using the GetProductReceiptAsync function.

Check whether LicenseInformation.IsActive returns true for a product before fulfilling a purchase. However, the call to this function is resource intensive so it is advisable not to call it at app launch or resume.

When you think a product purchase has completed, first verify that a license exists for that product ID and then check to see whether IsActive is true on that license. If the license is active then the purchase should be fulfilled immediately.

A possible scenario where in-app purchases can be useful is when you want to distribute your app for free with ads and allow the user to remove them through an in-app purchase. Here’s an article on implementing a «block ads» feature using the in-app purchase API. The same technique can be used to implement a trial. The advantage is that your app is listed in the free category in the store and will as a result get you more downloads.

In the case of consumable products, it’s the responsibility of the app to track consumption. The CurrentApp.LicenseInformation only provides information about the license, not the state.

6. Testing In-App Purchases

If you test your app in the emulator, in-app purchases are free and no financial transactions take place. Each time you reinstall the app in the emulator, previously stored license information is cleared.

There are three main techniques for testing in-app purchases:

  • create a Dev Center beta app and add beta in-app products
  • add the mock in-app purchase mock library to your solution
  • set up an in-app purchase mock service using Microsoft Internet Information Services (IIS)

Conclusion

In this tutorial, you have learned how to list in-app products and enable an app feature when the user purchases a product. There are lots of customizations possible with in-app purchases and they can be used in a variety of scenarios.

I encourage you to go through the In-AppPurchase API overview on MSDN. It’s also worth taking a look at options to test in-app purchase capabilities in your app before publishing it on the marketplace. Feel free to download the tutorial’s source files to use as a reference.

Вызов веб-API из приложения Windows Phone 8 (C#) Calling Web API from a Windows Phone 8 Application (C#)

В этом учебнике вы узнаете, как создать комплексный сценарий, состоящий из веб-API ASP.NET приложения, которое предоставляет каталог книг для приложения Windows Phone 8. In this tutorial, you will learn how to create a complete end-to-end scenario consisting of an ASP.NET Web API application that provides a catalog of books to a Windows Phone 8 application.

Обзор Overview

Службы RESTFUL, такие как веб-API ASP.NET упрощают создание приложений на основе HTTP для разработчиков путем абстракции архитектуры для приложений на стороне сервера и на стороне клиента. RESTful services like ASP.NET Web API simplify the creation of HTTP-based applications for developers by abstracting the architecture for server-side and client-side applications. Вместо создания собственного протокола на основе сокетов для обмена данными разработчики веб-API просто должны опубликовать необходимые методы HTTP для своего приложения (например, GET, POST, WHERE, DELETE) и разработчикам клиентских приложений требуется только использовать методы HTTP, необходимые для своего приложения. Instead of creating a proprietary socket-based protocol for communication, Web API developers simply need to publish the requisite HTTP methods for their application, (for example: GET, POST, PUT, DELETE), and client application developers only need to consume the HTTP methods that are necessary for their application.

В этом комплексном руководстве вы узнаете, как использовать веб-API для создания следующих проектов: In this end-to-end tutorial, you will learn how to use Web API to create the following projects:

  • В первой части этого руководствавы создадите веб-API ASP.NET приложение, которое поддерживает все операции создания, чтения, обновления и удаления (CRUD) для управления каталогом книг. In the first part of this tutorial, you will create an ASP.NET Web API application that supports all of the Create, Read, Update, and Delete (CRUD) operations to manage a book catalog. Это приложение будет использовать Образец XML-файла (Books. XML) из MSDN. This application will use the Sample XML File (books.xml) from MSDN.
  • Во второй части этого руководствавы создадите интерактивное приложение Windows Phone 8, которое получает данные из приложения веб-API. In the second part of this tutorial, you will create an interactive Windows Phone 8 application that retrieves the data from your Web API application.

предварительные требования Prerequisites

  • Visual Studio 2013 с установленным пакетом SDK для Windows Phone 8 Visual Studio 2013 with the Windows Phone 8 SDK installed
  • Windows 8 или более поздняя версия в 64-разрядной системе с установленным Hyper-V Windows 8 or later on a 64-bit system with Hyper-V installed
  • Список дополнительных требований см. в разделе требования к системе на странице скачивания Windows Phone SDK 8,0 . For a list of additional requirements, see the System Requirements section on the Windows Phone SDK 8.0 download page.

Если вы собираетесь проверить подключение между веб-API и Windows Phone 8 проектами в локальной системе, необходимо выполнить инструкции из статьи Подключение эмулятора Windows Phone 8 к приложениям веб-API на локальном компьютере , чтобы настроить среду тестирования. If you are going to test the connectivity between Web API and Windows Phone 8 projects on your local system, you will need to follow the instructions in the Connecting the Windows Phone 8 Emulator to Web API Applications on a Local Computer article to set up your testing environment.

Шаг 1. Создание проекта веб-API в книжном магазине Step 1: Creating the Web API Bookstore Project

Первым этапом этого комплексного руководства является создание проекта веб-API, поддерживающего все операции CRUD. Обратите внимание, что вы добавите проект Windows Phone приложения в это решение на шаге 2 этого руководства. The first step of this end-to-end tutorial is to create a Web API project that supports all of the CRUD operations; note that you will add the Windows Phone application project to this solution in Step 2 of this tutorial.

Читайте также:  Почему не открывается windows player

Откройте Visual Studio 2013. Open Visual Studio 2013.

Последовательно выберите пункты файл, создатьи проект. Click File, then New, and then Project.

Когда откроется диалоговое окно Новый проект , разверните узел установленные, затем шаблоны, визуальный C# элемент и веб-узел. When the New Project dialog box is displayed, expand Installed, then Templates, then Visual C#, and then Web.

Щелкните изображение, чтобы развернуть Click image to expand

Выделите веб-приложение ASP.NET, введите Bookstore в поле имя проекта и нажмите кнопку ОК. Highlight ASP.NET Web Application, enter BookStore for the project name, and then click OK.

Когда откроется диалоговое окно Новый проект ASP.NET , выберите шаблон веб-API и нажмите кнопку ОК. When the New ASP.NET Project dialog box is displayed, select the Web API template, and then click OK.

Щелкните изображение, чтобы развернуть Click image to expand

После открытия проекта веб-API удалите пример контроллера из проекта: When the Web API project opens, remove the sample controller from the project:

  1. Разверните папку контроллеры в обозревателе решений. Expand the Controllers folder in the solution explorer.
  2. Щелкните правой кнопкой мыши файл ValuesController.CS и выберите пункт Удалить. Right-click the ValuesController.cs file, and then click Delete.
  3. При появлении запроса на подтверждение удаления нажмите кнопку ОК . Click OK when prompted to confirm the deletion.

Добавьте файл данных XML в проект веб-API. Этот файл содержит содержимое каталога книжного магазина: Add an XML data file to the Web API project; this file contains the contents of the bookstore catalog:

Щелкните правой кнопкой мыши папку данных приложения_ в обозревателе решений, выберите пункт Добавить, а затем щелкните новый элемент. Right-click the App_Data folder in the solution explorer, then click Add, and then click New Item.

При отображении диалогового окна Добавление нового элемента выделите шаблон XML-файла . When the Add New Item dialog box is displayed, highlight the XML File template.

Присвойте файлу имя Books. XML, а затем нажмите кнопку Добавить. Name the file Books.xml, and then click Add.

При открытии файла Books. XML замените код в файле XML-кодом из образца файла Books. XML на сайте MSDN: When the Books.xml file is opened, replace the code in the file with the XML from the sample books.xml file on MSDN:

Сохраните и закройте XML-файл. Save and close the XML file.

Добавьте модель книжного магазина в проект веб-API. Эта модель содержит логику создания, чтения, обновления и удаления (CRUD) для приложения Bookstore: Add the bookstore model to the Web API project; this model contains the Create, Read, Update, and Delete (CRUD) logic for the bookstore application:

Щелкните правой кнопкой мыши папку модели в обозревателе решений, выберите Добавить, а затем — класс. Right-click the Models folder in the solution explorer, then click Add, and then click Class.

Когда откроется диалоговое окно Добавление нового элемента , назовите файл класса BookDetails.CSи нажмите кнопку добавить. When the Add New Item dialog box is displayed, name the class file BookDetails.cs, and then click Add.

При открытии файла BookDetails.CS замените код в файле следующим кодом: When the BookDetails.cs file is opened, replace the code in the file with the following:

Сохраните и закройте файл BookDetails.CS . Save and close the BookDetails.cs file.

Добавьте контроллер Bookstore в проект веб-API: Add the bookstore controller to the Web API project:

Щелкните правой кнопкой мыши папку Controllers в обозревателе решений, выберите Добавить, а затем щелкните контроллер. Right-click the Controllers folder in the solution explorer, then click Add, and then click Controller.

Когда откроется диалоговое окно Добавление шаблона , выделите контроллер Web API 2 — пустойи нажмите кнопку добавить. When the Add Scaffold dialog box is displayed, highlight Web API 2 Controller — Empty, and then click Add.

Когда откроется диалоговое окно Добавление контроллера , назовите контроллер буксконтроллери нажмите кнопку добавить. When the Add Controller dialog box is displayed, name the controller BooksController, and then click Add.

При открытии файла BooksController.CS замените код в файле следующим кодом: When the BooksController.cs file is opened, replace the code in the file with the following:

Сохраните и закройте файл BooksController.CS . Save and close the BooksController.cs file.

Создайте приложение веб-API для проверки на наличие ошибок. Build the Web API application to check for errors.

Шаг 2. Добавление проекта каталога Windows Phone 8 в книжном магазине Step 2: Adding the Windows Phone 8 Bookstore Catalog Project

Следующим этапом этого сквозного сценария является создание приложения каталога для Windows Phone 8. The next step of this end-to-end scenario is to create the catalog application for Windows Phone 8. Это приложение будет использовать шаблон приложения Windows Phone с привязкой к данным для пользовательского интерфейса по умолчанию и будет использовать приложение веб-API, созданное на шаге 1 этого учебника в качестве источника данных. This application will use the Windows Phone Databound App template for the default user interface, and it will use the Web API application that you created in Step 1 of this tutorial as the data source.

Щелкните правой кнопкой мыши решение Bookstore в в обозревателе решений, затем щелкните Добавить, а затем — Новый проект. Right-click the BookStore solution in the in the solution explorer, then click Add, and then New Project.

Когда откроется диалоговое окно Создание проекта , разверните узел установленные, а затем C#Visual и затем Windows Phone. When the New Project dialog box is displayed, expand Installed, then Visual C#, and then Windows Phone.

Выделите Windows Phone приложение с привязкой к данным, введите буккаталог в поле имя и нажмите кнопку ОК. Highlight Windows Phone Databound App, enter BookCatalog for the name, and then click OK.

Добавьте пакет NuGet Json.NET в проект буккаталог : Add the Json.NET NuGet package to the BookCatalog project:

  1. Щелкните правой кнопкой мыши ссылки на проект буккаталог в обозревателе решений и выберите пункт Управление пакетами NuGet. Right-click References for the BookCatalog project in the solution explorer, and then click Manage NuGet Packages.
  2. Когда откроется диалоговое окно Управление пакетами NuGet , разверните раздел Online и выделите NuGet.org. When the Manage NuGet Packages dialog box is displayed, expand the Online section, and highlight nuget.org.
  3. Введите JSON.NET в поле поиска и щелкните значок поиска. Enter Json.NET in the search field and click the search icon.
  4. Выделите JSON.NET в результатах поиска и нажмите кнопку установить. Highlight Json.NET in the search results, and then click Install.
  5. После завершения установки нажмите кнопку Закрыть. When the installation has completed, click Close.

Добавьте модель букдетаилс в проект буккаталог . Он содержит универсальную модель класса Bookstore: Add the BookDetails model to the BookCatalog project; this contains a generic model of the bookstore class:

Щелкните правой кнопкой мыши проект буккаталог в обозревателе решений, нажмите кнопку Добавить, а затем выберите пункт создать папку. Right-click the BookCatalog project in the solution explorer, then click Add, and then click New Folder.

Назовите новые моделипапок. Name the new folder Models.

Щелкните правой кнопкой мыши папку модели в обозревателе решений, выберите Добавить, а затем — класс. Right-click the Models folder in the solution explorer, then click Add, and then click Class.

Когда откроется диалоговое окно Добавление нового элемента , назовите файл класса BookDetails.CSи нажмите кнопку добавить. When the Add New Item dialog box is displayed, name the class file BookDetails.cs, and then click Add.

При открытии файла BookDetails.CS замените код в файле следующим кодом: When the BookDetails.cs file is opened, replace the code in the file with the following:

Сохраните и закройте файл BookDetails.CS . Save and close the BookDetails.cs file.

Обновите класс MainViewModel.CS , чтобы включить функции для взаимодействия с приложением веб-API книжного магазина: Update the MainViewModel.cs class to include the functionality to communicate with the BookStore Web API application:

Разверните папку ViewModels в обозревателе решений, а затем дважды щелкните файл MainViewModel.CS . Expand the ViewModels folder in the solution explorer, and then double-click the MainViewModel.cs file.

При открытии файла MainViewModel.CS замените код в файле следующим кодом. Обратите внимание, что необходимо обновить значение apiUrl ной константы с помощью фактического URL-адреса вашего Web API: When the MainViewModel.cs file is opened, replace the code in the file with the following; note that you will need to update the value of the apiUrl constant with the actual URL of your Web API:

Сохраните и закройте файл MainViewModel.CS . Save and close the MainViewModel.cs file.

Обновите файл MainPage. XAML , чтобы настроить имя приложения: Update the MainPage.xaml file to customize the application name:

Дважды щелкните файл MainPage. XAML в обозревателе решений. Double-click the MainPage.xaml file in the solution explorer.

При открытии файла MainPage. XAML нахождение следующих строк кода: When the MainPage.xaml file is opened, locate the following lines of code:

Замените эти строки следующим: Replace those lines with the following:

Сохраните и закройте файл MainPage. XAML . Save and close the MainPage.xaml file.

Обновите файл детаилспаже. XAML , чтобы настроить отображаемые элементы: Update the DetailsPage.xaml file to customize the displayed items:

Дважды щелкните файл детаилспаже. XAML в обозревателе решений. Double-click the DetailsPage.xaml file in the solution explorer.

При открытии файла детаилспаже. XAML нахождение следующих строк кода: When the DetailsPage.xaml file is opened, locate the following lines of code:

Замените эти строки следующим: Replace those lines with the following:

Сохраните и закройте файл детаилспаже. XAML . Save and close the DetailsPage.xaml file.

Создайте приложение Windows Phone для проверки на наличие ошибок. Build the Windows Phone application to check for errors.

Шаг 3. Тестирование комплексного решения Step 3: Testing the End-to-End Solution

Как упоминалось в разделе » Предварительные требования » этого руководства, при тестировании подключения между проектами веб-api и Windows Phone 8 в локальной системе необходимо выполнить инструкции из статьи подключение эмулятора Windows Phone 8 к ПРИЛОЖЕНИЯМ веб-API на локальном компьютере , чтобы настроить среду тестирования. As mentioned in the Prerequisites section of this tutorial, when you are testing the connectivity between Web API and Windows Phone 8 projects on your local system, you will need to follow the instructions in the Connecting the Windows Phone 8 Emulator to Web API Applications on a Local Computer article to set up your testing environment.

После настройки тестовой среды необходимо задать приложение Windows Phone в качестве запускаемого проекта. Once you have the testing environment configured, you will need to set the Windows Phone application as the startup project. Для этого выделите приложение буккаталог в обозревателе решений и нажмите кнопку Назначить запускаемым проектом. To do so, highlight the BookCatalog application in the solution explorer, and then click Set as StartUp Project:

Щелкните изображение, чтобы развернуть Click image to expand

При нажатии клавиши F5 Visual Studio запустит эмулятор Windows Phone, в котором будет отображаться «подождите» сообщение, пока данные приложения будут получены из веб-API: When you press F5, Visual Studio will start both the Windows Phone Emulator, which will display a «Please Wait» message while the application data is retrieved from your Web API:

Щелкните изображение, чтобы развернуть Click image to expand

Если все прошло успешно, должен отобразиться каталог: If everything is successful, you should see the catalog displayed:

Щелкните изображение, чтобы развернуть Click image to expand

Если коснуться любого названия книги, в приложении отобразится описание книги: If you tap on any book title, the application will display the book description:

Щелкните изображение, чтобы развернуть Click image to expand

Если приложение не может взаимодействовать с веб-API, отобразится сообщение об ошибке: If the application cannot communicate with your Web API, an error message will be displayed:

Щелкните изображение, чтобы развернуть Click image to expand

Если коснуться сообщения об ошибке, будут отображаться дополнительные сведения об ошибке: If you tap on the error message, any additional details about the error will be displayed:

Читайте также:  Linux как перезагрузить командой
Оцените статью