✨ UWP/WPF 应用中怎样判断用户是否已购买内购产品(IAP)

C#·技术 · 07-04 · 166 人浏览

当你的应用已经上架到 Microsoft Store,使用者可以通过内购产品(In-App Purchase,简称 IAP)来购买功能解锁、结束广告、购买虚拟物品等。

在这类场景中,最重要的一步是:怎样确认用户是否已经购买了指定的内购产品?

Microsoft 提供了两个重要方法:

  • StoreContext.GetUserCollectionAsync(...)
  • StoreContext.GetAppLicenseAsync()

本文将全面分析这两种方法的区别,应用场景,以及如何展示和封装它们。


🚀 一句话概括

方法用途概述
GetUserCollectionAsync获取当前账户实际购买的“内购产品”清单,相当于商店“购买记录”
GetAppLicenseAsync获取当前账户的应用 + 加载项的授权状态,支持离线读取,用于功能解锁

🧪 根本区别

特性GetUserCollectionAsyncGetAppLicenseAsync
目标内购产品(加载项)应用 + 加载项授权
返回值StoreProductQueryResultStoreAppLicense
内容结构包含 Products 字典(StoreProduct 对象)包含 AddOnLicenses 字典(StoreLicense)
离线支持不支持(需要网络连接商店服务器)支持(依赖本地授权缓存)
推荐场景显示是否已购买,打开购买按钮功能判断,冲刷UI控制权限
错误处理ExtendedError 返回少量异常,容错性更好

🔧 示例代码

GetUserCollectionAsync 判断是否已购买

var context = StoreContext.GetDefault();
var kinds = new[] { "Durable", "Subscription" };
var result = await context.GetUserCollectionAsync(kinds);

if (result.Products.TryGetValue("vip.lifetime", out var product))
{
    Debug.WriteLine("✅ 已购买");
}

GetAppLicenseAsync 判断授权

var context = StoreContext.GetDefault();
var license = await context.GetAppLicenseAsync();

if (license.AddOnLicenses.TryGetValue("vip.lifetime", out var addon) && addon.IsActive)
{
    Debug.WriteLine("✅ 授权正常");
}

📅 开发建议

场景推荐方案
应用启动判断授权GetAppLicenseAsync
购买后即时更新状态GetUserCollectionAsync
离线模式支持GetAppLicenseAsync
开发时控制UI状态两者组合使用

📄 封装方法建议

public async Task<bool> IsAddOnPurchasedAsync(string storeId)
{
    var context = StoreContext.GetDefault();
    var license = await context.GetAppLicenseAsync();
    return license.AddOnLicenses.TryGetValue(storeId, out var addon) && addon.IsActive;
}

如需要更强大的功能,可考虑同时加入 GetUserCollectionAsync 给予备选解析。


📂 官方文档链接


✅ 总结

如果你想判断“用户有没有真的购买了”,用 GetUserCollectionAsync
如果你想判断“这个功能是否被授权”,用 GetAppLicenseAsync

🙏 希望这篇文章能让你展示 Microsoft Store IAP 授权判断的手段更加精准。

如果你需要封装成一个 IStoreService 服务类,我可以给你直接生成线代码,包含更强验证、错误处理和缓存等功能。