Communitygithub.com

unity-technologies/implement-in-app-purchases

实现、配置和调试 Unity 应用内购(IAP),包括商店连接、产品目录、消耗品/非消耗品/订阅购买、两步待确认流程、收据验证、权限检查、恢复交易、苹果扩展(促销购买、Ask-to-Buy、代码兑换)和 Google Play 扩展(订阅升级/降级),以及通过 Unity IAP/Unity Cloud 实现的 D2C 功能(直达客户)和第三方支付提供商(Stripe/Coda)。当用户需要添加、修改、调试或从原生 Android/iOS 计费、第三方包(RevenueCat/Adapty/Essential Kit/Unipay)迁移到 IAP 时使用。触发了微交易、变现、真实货币购买、商店购买、购买物品、支持 D2C、通过 Stripe/Coda 购买、从原生计费(Google 的 BillingClient 或 Apple 的 StoreKit/SKPaymentQueue/SKProduct)/RevenueCat/Adapty/EssentialKit/Unipay 迁移。

implement-in-app-purchases 是什么?

Unity In-App Purchasing (IAP) 技能为 Unity 开发者提供了完整的应用内购实现方案,涵盖从商店连接到收据验证的完整流程。它支持消耗品、非消耗品和订阅三种产品类型,并采用强制性的两步流程(待确认→确认)来确保交易安全。该技能支持 Apple 和 Google Play 平台扩展,包括 Ask-to-Buy、促销购买、代码兑换以及订阅升级/降级等功能。在 Unity IAP v5 中,初始化通过 `UnityIAPServices.StoreController()` 方法独立完成,无需依赖 `UnityServices.InitializeAsync()`。该技能还提供详细的参考文件,指导从 RevenueCat、Adapty、Essential Kit、UniPay 等第三方包以及原生 Google BillingClient 和 iOS StoreKit 插件向 Unity IAP 迁移。此外,它还支持 D2C(直达客户)能力,允许通过 Stripe 或 Coda 等第三方支付提供商处理购买,这需要 Unity IAP v5.4 或更高版本。收据验证方面,Google Play 支持本地验证,而 Apple(StoreKit 2)仅支持服务器端验证。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/unity-technologies/skills/tree/main/skills/implement-in-app-purchases

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

Unity 应用内购

命名空间:UnityEngine.Purchasing | 安全:UnityEngine.Purchasing.Security 包:com.unity.purchasing

Unity IAP 有自己的初始化路径:UnityIAPServices.StoreController() → store.Connect()。它不需要 UnityServices.InitializeAsync(),但如果您的项目使用了其他 UGS 服务,它们可以共存。如果存在 Analytics 并且调用了 InitializeAsync(),IAP 将自动发送交易事件。

开始之前

始终首先阅读 references/pre-check.md。 它会扫描项目中的第三方 IAP 包、原生 Google Billing 和现有的 Unity IAP 版本,然后路由到正确的路径。在路由解决之前,不要读取任何其他参考文件或进行任何更改。

详细参考

根据需要读取参考文件——仅当您需要特定的 API 签名、平台扩展详细信息或迁移映射时。

初始化流程

  1. 通过 UnityIAPServices.StoreController() 获取 StoreController(或通过 DefaultStore()、DefaultProduct()、DefaultPurchase() 获取单个服务)
  2. 在调用 Connect() 之前,订阅所有必需的事件(参见下方必需的事件订阅)
  3. await store.Connect() 连接到平台商店
  4. 在 OnStoreConnected 上,调用 store.FetchProducts(List<ProductDefinition>) 加载目录
  5. 在 OnProductsFetched 上,产品准备好显示和购买

使用 Awake() 进行初始化——确保 IAP 在其他 Start() 方法之前准备就绪。

产品类型:ProductType.Consumable、ProductType.NonConsumable、ProductType.Subscription。

获取产品

将产品定义为 List<ProductDefinition> 并传递给 store.FetchProducts()。当产品 ID 在 Apple/Google 商店之间不同时,使用 StoreSpecificIds。对于复杂目录,使用 CatalogProvider 管理产品集和特定于商店的 ID。

方法行为
GetProducts()返回缓存的产品列表(同步,如果未调用 FetchProducts 则为过时)
FetchProducts()向商店查询最新的定价/可用性并更新缓存
GetProductById(id)按 ID 返回单个缓存产品

这些方法不可互换。在依赖 GetProducts() 之前,始终首先调用 FetchProducts()。

两步购买流程

IAP v5 使用强制性的两步流程:待确认 → 确认。

  1. store.PurchaseProduct(product) — 启动平台购买对话框
  2. OnPurchasePending 触发 — 您收到一个 PendingOrder
  3. 验证收据,向玩家授予内容
  4. store.ConfirmPurchase(pendingOrder) — 最终确定交易
  5. OnPurchaseConfirmed 触发 — 接收 Order 基类型;模式匹配 ConfirmedOrder(成功)与 FailedOrder(确认失败)

授予内容后,您必须调用 ConfirmPurchase(pendingOrder)。 未确认的购买将在下次应用启动时重新交付,以防止购买丢失。

去重: 同一购买可能多次触发 OnPurchasePending(例如,在确认前重启应用)。始终检查内容是否已被授予。

消耗品: 已确认的消耗品购买不会由 FetchPurchases 返回。自行跟踪消耗品的授予(例如,在 Cloud Save 或 Economy 中)。

延迟购买: 对于 Ask-to-Buy (iOS) 和 Google Play 延迟购买,OnPurchaseDeferred 会触发。不要授予内容——等待批准后的 OnPurchasePending。

恢复交易

store.RestoreTransactions(callback) 重新交付非消耗品和订阅购买。每个恢复的购买都会触发 OnPurchasePending。

iOS 上需要此功能以符合 Apple App Store 要求——添加一个“恢复购买”按钮。

Apple 非续期订阅无法通过 RestoreTransactions 恢复。请通过服务器端跟踪这些订阅。

收据验证

平台方法
Google PlayCrossPlatformValidator 与 GooglePlayTangle.Data() — 支持本地验证
Apple (StoreKit 2)本地验证是空操作。使用 order.Info.Apple?.jwsRepresentation 进行服务器端验证

通过 Unity 编辑器中的 Services > In-App Purchasing > Receipt Validation Obfuscator 生成 tangle 数据。

权限检查

当您没有 Order 但想知道特定产品的状态时使用(替代 v4 的 product.hasReceipt)。如果您已经有 Order,请检查其类型:PendingOrder 映射到 EntitledUntilConsumed(消耗品)或 EntitledButNotFinished(非消耗品/订阅),ConfirmedOrder 映射到 FullyEntitled。

调用 store.CheckEntitlement(product) 并处理 store.OnCheckEntitlement。检查 entitlement.Status == EntitlementStatus.FullyEntitled。

EntitlementStatus 值:FullyEntitled、EntitledUntilConsumed、EntitledButNotFinished、NotEntitled、Unknown。

获取现有购买

store.FetchPurchases() 从商店检索所有当前购买。在应用启动时使用。

方法行为
GetPurchases()返回缓存的购买列表
FetchPurchases()向商店查询当前购买并覆盖缓存的列表

FetchPurchases() 每次调用都会替换整个缓存的列表。只有非消耗品和订阅才会被返回。

Individual skills in this repo

This repo contains 9 individual skills — each has its own dedicated page.

unity-technologies/2d-pixel-perfect

Sets up, diagnoses, and fixes pixel perfect 2D rendering in Unity projects. Use when working on any retro-style or pixel art 2D game.

unity-technologies/audio-setup-mixers

Scans the scene and audio assets to appropriately route Audio Sources into existing Audio Mixer Groups, classifying each source by what it plays. Use when the user asks about cleaning up mixer assignments, routing audio through a mixer, or which group a sound belongs in. Creating mixers and groups, and setting volumes, are not automated — the skill inventories what exists and asks the user to add anything missing.

unity-technologies/build-live-game

Build and operate a live game using Unity Services. Use when the user needs to implement, connect, or debug backend-driven features — battle passes, achievements, player progression, cloud saves, leaderboards, matchmaking, virtual economies, server-authoritative logic, anti-cheat, player accounts and authentication, remote configuration, feature flags, A/B testing, analytics, or cloud resource deployment. Triggers on live-ops, live service, backend, server authority, cloud code, cloud save, remote config, player data, retention, monetization loop, season pass, ranking, multiplayer sessions, lobbies, or any Unity Services integration.

unity-technologies/generate-editor-search-query

Generates Unity Search / Quick Search queries and opens the Unity Search window for read-only Unity Editor asset or scene-object lookup requests. Always use when the user asks to find, search, show, locate, filter, look up, query, or list concrete assets or scene objects in the current project or scene, even if Unity Search is not named. Covers materials, textures, prefabs, scenes, scripts, shaders, GameObjects, components, Lights, Cameras, UI objects, labels, paths, references, selected or named assets, and asset types. Also use when the user explicitly mentions Unity Search, Quick Search, Search window, open Search, or asks what Unity Search query to use. Do not use for general project overview, project structure, folder-purpose summaries, gameplay/system explanations, how-to programming questions, web search, repository text search, build logs, package installation, menu or settings search, modifying results, or non-Unity filesystem search unless the user explicitly asks to use Unity Search.

unity-technologies/initialize-ai-navigation

Sets up and configures the Unity AI Navigation system — NavMesh surfaces, NavMesh agents, obstacles, links, modifiers, areas and costs. Use when creating walkable navigation meshes, adding pathfinding agents, setting up patrol routes, configuring obstacle avoidance and carving, connecting separate NavMeshes with links, coupling navigation with animation, or troubleshooting navigation issues.

unity-technologies/levelplay-unity-integration

Integrates the LevelPlay Mediation SDK via the Ads Mediation UPM package. Use when a developer asks about adding ads to a Unity game, implementing rewarded, interstitial, or banner ads, setting up ad mediation, configuring ad networks, installing or updating the Ads Mediation package, troubleshooting LevelPlay namespace errors, resolving Android gradle or iOS CocoaPods dependency issues for ads, configuring ATT or privacy settings for ad compliance, tracking impression-level revenue (ILRD), initializing the LevelPlay SDK, or setting up ad unit IDs. Also use when a developer wants to monetize their Unity game with ads, asks how to get started with LevelPlay, ads, or mediation, or needs help with any part of the LevelPlay integration workflow including platform-specific setup for iOS or Android. Also use when upgrading the LevelPlay or IronSource SDK version, migrating from deprecated IronSource.Agent APIs, or migrating a game from Unity Ads to LevelPlay.

unity-technologies/localization

Sets up and configures Unity Localization, including locales, String/Asset Tables, CJK font support, and Addressables workflows. Use when the user wants to add languages to a project, translate UI text, support Asian (CJK) languages with TMP fonts, or mentions i18n, l10n, multilingual support, or making a game support multiple languages.

unity-technologies/manage-sprite-atlas

Manage SpriteAtlas using prebuild pipeline with IPreprocessBuildWithReport (DEFAULT approach). Use it to configure master atlases, variant atlases, texture settings, packing settings, and platform-specific configurations. Use when the user asks about creating sprite atlases, optimizing sprites, configuring atlas settings, adding sprites to atlases, creating variant atlases, implementing automated atlas generation, or runtime sprite atlas access. Always use prebuild approach unless user explicitly requests manual authoring.

unity-technologies/migrate-birp-to-urp

Plans, executes, and troubleshoots Unity projects moving from the Built-in Render Pipeline (BiRP/BIRP/Built-in RP) to the Universal Render Pipeline (URP). Use when the user asks to upgrade, convert, switch, or migrate a project, scene, material, or shader to URP/Universal Render Pipeline; fix pink or magenta materials after URP; convert Built-in materials/shaders; move a 2D project to URP 2D; review lighting, quality, post-processing, baked lightmaps, or reflection probes after URP; or diagnose visual problems after a render-pipeline migration.

相关技能