
InAppBillingPlugin 核心功能详解消费型、非消费型和订阅型商品实现指南【免费下载链接】InAppBillingPluginCross-platform In App Billing Plugin for .NET项目地址: https://gitcode.com/gh_mirrors/in/InAppBillingPlugin欢迎来到 InAppBillingPlugin 的完整功能指南 如果你正在为 .NET MAUI、Xamarin 或 Windows 应用寻找跨平台的应用内购买解决方案那么你来对地方了。InAppBillingPlugin 是一个强大的 .NET 插件它让你能够在 iOS、Android 和 Windows 平台上轻松实现应用内购买功能。本文将详细介绍消费型、非消费型和订阅型商品的核心实现方法帮助你快速掌握这个强大的工具。什么是 InAppBillingPluginInAppBillingPlugin 是一个专门为 .NET 开发者设计的跨平台应用内购买插件支持 .NET MAUI、Xamarin.Forms、Xamarin.Android、Xamarin.iOS、Windows App SDK (WinUI 3) 等平台。它提供了统一的 API 接口让你无需关心底层平台差异就能轻松实现各种类型的应用内购买功能。核心功能亮点 ✨跨平台支持iOS、Android、macOS、Windows 全平台覆盖统一 API 设计一套代码适配所有平台多种商品类型消费型、非消费型、订阅型商品全面支持简单易用简洁的 API 设计快速上手安全可靠遵循各平台最佳实践和安全规范快速开始安装与配置NuGet 包安装 首先在你的项目中安装 Plugin.InAppBilling NuGet 包Install-Package Plugin.InAppBilling确保在所有项目包括客户端项目中都安装此包。基本使用模式使用 InAppBillingPlugin 非常简单基本流程如下public async Taskbool MakePurchase() { if (!CrossInAppBilling.IsSupported) return false; var billing CrossInAppBilling.Current; try { var connected await billing.ConnectAsync(); if (!connected) return false; // 进行购买操作 return true; } finally { await billing.DisconnectAsync(); } }重要提示在进行任何应用内购买调用之前必须先调用ConnectAsync()建立连接并在操作完成后调用DisconnectAsync()断开连接。消费型商品Consumable实现指南什么是消费型商品消费型商品是指用户购买后会被消耗掉可以重复购买的商品。比如游戏中的金币、能量道具、一次性道具等。平台术语对照表平台消费型商品名称Apple iOSConsumableAndroidManaged ProductMicrosoftDeveloper-managed consumable购买消费型商品的完整流程public async Taskbool PurchaseConsumableItem(string productId) { var billing CrossInAppBilling.Current; try { var connected await billing.ConnectAsync(); if (!connected) { // 无法连接应用商店 return false; } // 发起购买请求 var purchase await billing.PurchaseAsync( productId, ItemType.InAppPurchaseConsumable ); if (purchase null) { // 用户取消了购买 return false; } else if (purchase.State PurchaseState.Purchased) { // 购买成功现在可以消费这个商品 // 重要在 Android 和 Windows 上需要消费购买 var wasConsumed await billing.ConsumePurchaseAsync( purchase.ProductId, purchase.TransactionIdentifier ); if (wasConsumed) { // 消费成功商品可以再次购买 // 这里可以更新用户的金币数量或道具库存 return true; } } } catch (InAppBillingPurchaseException purchaseEx) { // 处理购买异常 Debug.WriteLine($购买错误: {purchaseEx}); } catch (Exception ex) { // 处理其他异常 Debug.WriteLine($连接问题: {ex}); } finally { await billing.DisconnectAsync(); } return false; }平台注意事项 iOS从版本 5.x 和 6.x 开始需要手动调用ConsumePurchaseAsync来完成交易Android必须在再次购买前消费商品同时消费操作也作为交易的确认Windows必须在再次购买前消费商品消费型商品的最佳实践 ✅立即消费建议在购买成功后立即消费商品避免用户重复购买状态保存在本地保存购买状态防止应用重启后状态丢失错误处理正确处理各种购买异常情况用户体验提供清晰的购买成功/失败反馈非消费型商品Non-Consumable实现指南什么是非消费型商品非消费型商品是一次性购买后永久拥有的商品比如解锁高级功能、去除广告、购买完整版等。用户尝试重复购买时系统会自动恢复之前的购买。平台术语对照表平台非消费型商品名称Apple iOSNon-ConsumableAndroidManaged ProductMicrosoftDurable with Lifetime购买非消费型商品的完整流程public async Taskbool PurchaseNonConsumableItem(string productId) { var billing CrossInAppBilling.Current; try { var connected await billing.ConnectAsync(); if (!connected) { // 无法连接应用商店 return false; } // 发起购买请求 var purchase await billing.PurchaseAsync( productId, ItemType.InAppPurchase ); if (purchase null) { // 用户取消了购买 return false; } else if (purchase.State PurchaseState.Purchased) { // 购买成功 // 重要在 Android 上需要确认购买3天内 #if ANDROID var acknowledged await billing.FinalizePurchaseAsync( purchase.TransactionIdentifier ); if (acknowledged) { // 确认成功永久解锁功能 // 保存购买状态到本地存储 Preferences.Set($purchased_{productId}, true); return true; } #else // iOS 和 Windows 自动确认 Preferences.Set($purchased_{productId}, true); return true; #endif } } catch (InAppBillingPurchaseException purchaseEx) { // 处理购买异常 Debug.WriteLine($购买错误: {purchaseEx}); } catch (Exception ex) { // 处理其他异常 Debug.WriteLine($连接问题: {ex}); } finally { await billing.DisconnectAsync(); } return false; }检查用户是否已购买public async Taskbool IsProductPurchased(string productId) { var billing CrossInAppBilling.Current; try { var connected await billing.ConnectAsync(); if (!connected) return false; // 获取用户的购买记录 var purchases await billing.GetPurchasesAsync(ItemType.InAppPurchase); // 检查是否包含当前商品 return purchases?.Any(p p.ProductId productId p.State PurchaseState.Purchased ) ?? false; } finally { await billing.DisconnectAsync(); } }Android 平台重要提醒 ⚠️在 Android 平台上购买成功后必须在3 天内调用FinalizePurchaseAsync进行确认否则购买可能会被自动退款。这是 Google Play 商店的安全要求。订阅型商品Subscription实现指南什么是订阅型商品订阅型商品是按时间周期收费的商品比如月度会员、年度订阅等。订阅可以是自动续订的也可以是需要手动续订的。平台术语对照表平台订阅型商品名称Apple iOSAuto-Renewable / Non-Renewing SubscriptionAndroidSubscriptionMicrosoftDurable with expiration period购买订阅型商品的完整流程public async Taskbool PurchaseSubscription(string productId) { var billing CrossInAppBilling.Current; try { var connected await billing.ConnectAsync(); if (!connected) { // 无法连接应用商店 return false; } // 发起订阅购买请求 var purchase await billing.PurchaseAsync( productId, ItemType.Subscription ); if (purchase null) { // 用户取消了购买 return false; } else if (purchase.State PurchaseState.Purchased) { // 订阅购买成功 // 重要在 Android 上需要确认购买3天内 #if ANDROID var acknowledged await billing.FinalizePurchaseAsync( purchase.TransactionIdentifier ); if (acknowledged) { // 确认成功激活订阅 await ActivateSubscription(purchase); return true; } #else // iOS 和 Windows 自动确认 await ActivateSubscription(purchase); return true; #endif } } catch (InAppBillingPurchaseException purchaseEx) { // 处理购买异常 Debug.WriteLine($订阅错误: {purchaseEx}); } catch (Exception ex) { // 处理其他异常 Debug.WriteLine($连接问题: {ex}); } finally { await billing.DisconnectAsync(); } return false; } private async Task ActivateSubscription(InAppBillingPurchase purchase) { // 保存订阅信息 Preferences.Set($subscription_{purchase.ProductId}_purchased, true); Preferences.Set($subscription_{purchase.ProductId}_transaction, purchase.TransactionIdentifier); Preferences.Set($subscription_{purchase.ProductId}_expiry, purchase.ExpiryDate?.ToString()); // 激活订阅功能 await EnablePremiumFeatures(); }检查订阅状态public async TaskSubscriptionStatus CheckSubscriptionStatus(string productId) { var billing CrossInAppBilling.Current; try { var connected await billing.ConnectAsync(); if (!connected) return SubscriptionStatus.Unknown; // 获取用户的订阅记录 var purchases await billing.GetPurchasesAsync(ItemType.Subscription); var subscription purchases?.FirstOrDefault(p p.ProductId productId p.State PurchaseState.Purchased ); if (subscription null) return SubscriptionStatus.NotSubscribed; // 检查订阅是否过期 if (subscription.ExpiryDate.HasValue subscription.ExpiryDate.Value DateTime.UtcNow) { return SubscriptionStatus.Expired; } return SubscriptionStatus.Active; } finally { await billing.DisconnectAsync(); } } public enum SubscriptionStatus { Unknown, NotSubscribed, Active, Expired }订阅管理功能 自动续订管理处理自动续订的订阅订阅升级/降级支持用户变更订阅等级订阅恢复允许用户恢复之前的订阅取消订阅提供取消订阅的途径重要提示在 Android 上你必须提供取消订阅的功能可以通过以下两种方式之一如果通过应用商店销售需要深度链接到 Google Play 订阅管理页面如果在应用外销售需要链接到你的取消订阅页面高级功能与最佳实践1. 获取商品详细信息 在展示商品前先获取商品的详细信息价格、描述等public async TaskListProductInformation GetProductDetails(Liststring productIds) { var billing CrossInAppBilling.Current; try { var connected await billing.ConnectAsync(); if (!connected) return null; // 获取商品信息 var items await billing.GetProductInfoAsync( ItemType.InAppPurchase, productIds ); return items?.Select(item new ProductInformation { ProductId item.ProductId, Name item.Name, Description item.Description, LocalizedPrice item.LocalizedPrice, CurrencyCode item.CurrencyCode, MicrosPrice item.MicrosPrice }).ToList(); } finally { await billing.DisconnectAsync(); } }2. 恢复购买功能 对于非消费型商品和订阅提供恢复购买功能public async Taskbool RestorePurchases() { var billing CrossInAppBilling.Current; try { var connected await billing.ConnectAsync(); if (!connected) return false; // 获取所有已购买的商品 var purchases await billing.GetPurchasesAsync(ItemType.InAppPurchase); var subscriptions await billing.GetPurchasesAsync(ItemType.Subscription); // 处理恢复逻辑 await ProcessRestoredPurchases(purchases); await ProcessRestoredSubscriptions(subscriptions); return true; } finally { await billing.DisconnectAsync(); } }3. 错误处理策略 ️try { // 购买操作 } catch (InAppBillingPurchaseException ex) { switch (ex.PurchaseError) { case PurchaseError.AppStoreUnavailable: // 应用商店不可用 break; case PurchaseError.BillingUnavailable: // 应用内购买不可用 break; case PurchaseError.ItemAlreadyOwned: // 商品已购买 break; case PurchaseError.ItemUnavailable: // 商品不可用 break; case PurchaseError.PaymentInvalid: // 支付无效 break; case PurchaseError.PaymentNotAllowed: // 支付不被允许 break; case PurchaseError.UserCancelled: // 用户取消 break; default: // 其他错误 break; } }4. 平台特定配置 ⚙️iOS 配置在 iTunes Connect 中创建应用内购买项目配置沙盒测试账号处理自动完成交易设置Android 配置在 Google Play Console 中创建商品配置测试账号添加 billing library 版本元数据Windows 配置在 Microsoft Store 合作伙伴中心创建附加组件配置测试环境性能优化与调试技巧1. 连接管理优化 // 使用单例模式管理连接 public class BillingManager { private static BillingManager _instance; private IInAppBilling _billing; private bool _isConnected; public static BillingManager Instance _instance ?? new BillingManager(); private BillingManager() { _billing CrossInAppBilling.Current; } public async Taskbool EnsureConnected() { if (_isConnected) return true; _isConnected await _billing.ConnectAsync(); return _isConnected; } public async Task DisconnectIfNeeded() { if (_isConnected) { await _billing.DisconnectAsync(); _isConnected false; } } }2. 测试环境配置 #if DEBUG // 在开发环境中使用测试商品ID public const string TestConsumableId test_consumable; public const string TestNonConsumableId test_nonconsumable; public const string TestSubscriptionId test_subscription; #else // 在生产环境中使用真实商品ID public const string RealConsumableId real_consumable; public const string RealNonConsumableId real_nonconsumable; public const string RealSubscriptionId real_subscription; #endif3. 日志记录与监控 public class BillingLogger { public static void LogPurchaseEvent(string eventName, string productId, PurchaseState? state null) { // 记录到应用分析 Analytics.TrackEvent(eventName, new Dictionarystring, string { [product_id] productId, [state] state?.ToString() ?? unknown, [platform] DeviceInfo.Platform.ToString(), [timestamp] DateTime.UtcNow.ToString(o) }); // 本地日志 Debug.WriteLine($[BILLING] {eventName}: {productId} - {state}); } }常见问题与解决方案Q1: 购买后商品状态不正确怎么办解决方案检查是否正确调用了ConsumePurchaseAsync消费型商品检查是否正确调用了FinalizePurchaseAsyncAndroid 平台验证商品ID是否正确检查网络连接状态Q2: 订阅状态如何同步解决方案定期调用GetPurchasesAsync检查订阅状态在应用启动时验证订阅有效性使用后台任务定期同步订阅状态Q3: 如何处理退款和取消解决方案监听购买状态变化及时更新用户权益提供客户支持渠道Q4: 多平台测试需要注意什么解决方案使用各平台的沙盒测试环境配置测试账号测试网络异常情况测试支付流程中断总结与下一步InAppBillingPlugin 为 .NET 开发者提供了一个强大而简单的跨平台应用内购买解决方案。通过本文的指南你应该已经掌握了✅消费型商品的实现方法和管理策略✅非消费型商品的一次性购买和恢复机制✅订阅型商品的周期管理和状态检查✅跨平台适配的最佳实践和注意事项✅错误处理和性能优化技巧下一步行动建议 从简单开始先实现一个非消费型商品如去广告功能充分测试在各平台的测试环境中充分测试购买流程监控分析添加购买事件追踪和分析用户支持准备完善的用户支持文档和流程官方文档参考 入门指南消费型商品购买非消费型商品购买订阅型商品购买异常处理测试与故障排除记住应用内购买是实现应用盈利的重要方式但用户体验同样重要。确保购买流程顺畅、透明及时处理用户问题这样才能建立长期信任和可持续的收入模式。祝你的应用内购买功能顺利上线专业提示在生产环境上线前务必在各平台进行完整的端到端测试包括购买、恢复、退款等所有场景。【免费下载链接】InAppBillingPluginCross-platform In App Billing Plugin for .NET项目地址: https://gitcode.com/gh_mirrors/in/InAppBillingPlugin创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考