本文演示如何使用 Windows.Services.Store 命名空间中的成员为用户请求购买当前应用或其加载项之一。 例如,如果用户当前具有应用的试用版,则可以使用此过程为用户购买完整许可证。 或者,可以使用此过程购买加载项,例如为用户新增的游戏关卡。
若要请求购买应用或加载项, Windows.Services.Store 命名空间提供了几种不同的方法:
- 如果您知道应用或加载项的应用商店 ID ,您可以使用 StoreContext 类的 RequestPurchaseAsync 方法。
- 如果您已经拥有代表应用程序或附加功能的 StoreProduct、StoreSku或 StoreAvailability 对象,则可以使用这些对象的 RequestPurchaseAsync 方法。 有关在代码中检索 StoreProduct 的不同方法的示例,请参阅 获取应用和加载项的产品信息。
每种方法向用户提供标准购买 UI,然后在交易完成后异步完成。 该方法返回一个对象,该对象指示事务是否成功。
注释
Windows.Services.Store 命名空间是在 Windows 10 版本 1607 中引入的,并且只能在面向 Windows 10 周年版(10.0; 版本 14393) 或更高版本的项目中使用,需在 Visual Studio 中构建。 如果你的应用面向早期版本的 Windows 10,则必须使用 Windows.ApplicationModel.Store 命名空间而不是 Windows.Services.Store 命名空间。 有关详细信息,请参阅 本文。
先决条件
此示例具有以下先决条件:
- 适用于面向 Windows 10 周年纪念版(10.0;版本 14393)或更高版本的通用 Windows 平台 (UWP) 应用的 Visual Studio 项目。
- 在合作伙伴中心创建应用提交,此应用在应用商店中发布。 可以选择配置应用,以便在测试应用时无法在应用商店中发现它。 有关详细信息,请参阅我们的 测试指南。
- 如果要为应用的加载项启用应用内购买,还必须 在合作伙伴中心创建加载项。
此示例中的代码假定:
- 代码在 Page 上下文中运行,其中包含名为 的
workingProgressRing
,以及名为 的textBlock
。 这些对象分别用于指示异步操作的发生和显示输出消息。 - 代码文件中有一个 ,该文件使用 语句用于 Windows.Services.Store 命名空间.
- 该应用是一个单用户应用,仅在启动应用的用户的上下文中运行。 有关详细信息,请参阅 应用内购买和试用版。
注释
如果你有使用 Desktop Bridge的桌面应用程序,则可能需要添加本示例中未显示的其他代码来配置 StoreContext 对象。 有关详细信息,请参阅在使用桌面桥的桌面应用程序中使用的 StoreContext 类 。
代码示例
此示例演示如何使用 StoreContext 类的 RequestPurchaseAsync 方法购买具有已知应用商店 ID 的应用或加载项。 有关完整的示例应用程序,请参阅 Store 示例。
private StoreContext context = null;
public async void PurchaseAddOn(string storeId)
{
if (context == null)
{
context = StoreContext.GetDefault();
// If your app is a desktop app that uses the Desktop Bridge, you
// may need additional code to configure the StoreContext object.
// For more info, see https://aka.ms/storecontext-for-desktop.
}
workingProgressRing.IsActive = true;
StorePurchaseResult result = await context.RequestPurchaseAsync(storeId);
workingProgressRing.IsActive = false;
// Capture the error message for the operation, if any.
string extendedError = string.Empty;
if (result.ExtendedError != null)
{
extendedError = result.ExtendedError.Message;
}
switch (result.Status)
{
case StorePurchaseStatus.AlreadyPurchased:
textBlock.Text = "The user has already purchased the product.";
break;
case StorePurchaseStatus.Succeeded:
textBlock.Text = "The purchase was successful.";
break;
case StorePurchaseStatus.NotPurchased:
textBlock.Text = "The purchase did not complete. " +
"The user may have cancelled the purchase. ExtendedError: " + extendedError;
break;
case StorePurchaseStatus.NetworkError:
textBlock.Text = "The purchase was unsuccessful due to a network error. " +
"ExtendedError: " + extendedError;
break;
case StorePurchaseStatus.ServerError:
textBlock.Text = "The purchase was unsuccessful due to a server error. " +
"ExtendedError: " + extendedError;
break;
default:
textBlock.Text = "The purchase was unsuccessful due to an unknown error. " +
"ExtendedError: " + extendedError;
break;
}
}