Communitygithub.com

unity-technologies/implement-in-app-purchases

實作、設定與偵錯 Unity 應用程式內購買 (IAP) — 包含商店連線、商品目錄、消耗品/非消耗品/訂閱購買、兩步驟待確認流程、收據驗證、資格檢查、還原交易、Apple 擴充功能 (促銷購買、Ask-to-Buy、兌換代碼) 與 Google Play 擴充功能 (訂閱升級/降級),以及透過 Unity IAP/Unity Cloud 實現 D2C 功能 (直接對客戶) 與第三方支付提供商 (Stripe/Coda)。

implement-in-app-purchases 是什麼?

此技能提供完整的 Unity IAP v5 實作指南,包含從專案掃描、路徑路由到最終實作的完整流程。它支援多種平台 (iOS/Android) 與第三方支付整合 (Stripe/Coda),並涵蓋從原生計費 (Google BillingClient、Apple StoreKit)、RevenueCat、Adapty、Essential Kit、UniPay 等遷移至 Unity IAP 的所有情境。其核心是全新的兩步驟購買流程 (待確認→確認),強制要求開發者在授予內容後呼叫 `store.ConfirmPurchase()`,確保交易不會遺失。此外,它也詳細說明了收據驗證 (Google Play 本地驗證、Apple StoreKit 2 伺服器端驗證)、資格檢查 (`CheckEntitlement`) 與交易還原 (`RestoreTransactions`),特別針對 iOS 的 App Store 規範。該技能適用於所有使用 Unity IAP 進行微交易、貨幣化或真實貨幣購買的專案。

相容平台~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()。當 Apple/Google 商店的商品 ID 不同時,請使用 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 中)。

延遲購買: OnPurchaseDeferred 會針對 Ask-to-Buy (iOS) 和 Google Play 延遲購買觸發。請勿授予內容 — 請等待核准後觸發的 OnPurchasePending。

還原交易

store.RestoreTransactions(callback) 會重新傳遞非消耗品與訂閱購買。每次還原的購買都會觸發 OnPurchasePending。

iOS 上需要遵守 Apple App Store 規範 — 請新增一個「還原購買」按鈕。

Apple 的非續訂訂閱無法透過 RestoreTransactions 還原。請在伺服器端追蹤這些訂閱。

收據驗證

平台方法
Google Play使用 CrossPlatformValidator 搭配 GooglePlayTangle.Data() — 支援本地驗證
Apple (StoreKit 2)本地驗證是無效操作。請使用 order.Info.Apple?.jwsRepresentation 進行伺服器端驗證

在 Unity 編輯器中透過 Services > In-App Purchasing > Receipt Validation Obfuscator 產生纏結資料。

資格檢查

當您沒有 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.

相關技能