implement-in-app-purchases
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseUnity In-App Purchasing
Unity 应用内购买
Namespace: | Security:
Package:
UnityEngine.PurchasingUnityEngine.Purchasing.Securitycom.unity.purchasingUnity IAP has its own initialization path via → . It does not require , but they can coexist if your project uses other UGS services. If Analytics is present and is called, IAP will automatically send transaction events.
UnityIAPServices.StoreController()store.Connect()UnityServices.InitializeAsync()InitializeAsync()命名空间: | 安全模块:
包:
UnityEngine.PurchasingUnityEngine.Purchasing.Securitycom.unity.purchasingUnity IAP 拥有独立的初始化路径,通过 → 完成。它不需要调用 ,但如果你的项目使用其他UGS服务,两者可以共存。如果项目中包含Analytics且调用了,IAP会自动发送交易事件。
UnityIAPServices.StoreController()store.Connect()UnityServices.InitializeAsync()InitializeAsync()Before You Start
开始之前
Always read references/pre-check.md first. It scans the project for third-party IAP packages, native Google Billing, and existing Unity IAP versions, then routes to the correct path. Do not read any other reference file or make any changes until routing is resolved.
请务必先阅读 references/pre-check.md。该文档会扫描项目中的第三方IAP包、原生Google计费系统以及现有Unity IAP版本,然后引导至正确的操作路径。在确定路径之前,请勿阅读其他参考文档或进行任何修改。
Detailed References
详细参考文档
- Project scan and path routing (read first): See references/pre-check.md
- API signatures & code examples: See references/api-notes.md
- Platform extensions (Apple, Google): See references/platform-notes.md
- Editing (schema, decimal serialization, refresh): See references/codeless-catalog.md
IAPProductCatalog.json - v4 → v5 migration: See references/migration-v4-to-v5.md
- Convert native Google BillingClient to Unity IAP 5: See references/path-convert-native-google-billing.md
- Convert native iOS StoreKit plugin to Unity IAP 5: See references/path-convert-native-storekit.md
- Convert Essential Kit billing to Unity IAP 5: See references/convert-essentialkit.md
- UniPay (FLOBUK) — assessment and guidance: See references/convert-unipay.md
- RevenueCat — conversion assessment and guidance: See references/convert-revenuecat.md
- Adapty — conversion assessment and guidance: See references/convert-adapty.md
- Add Unity IAP 5 to a project with no existing IAP: See references/path-add-iap-to-new-project.md
- Implement IAP D2C Capabilities (third-party payment provider — Stripe/Coda, requires v5.4+): See references/path-implement-iap-d2c.md
Read reference files on demand — only when you need specific API signatures, platform extension details, or migration mappings.
- 项目扫描与路径引导(优先阅读): 查看 references/pre-check.md
- API签名与代码示例: 查看 references/api-notes.md
- 平台扩展(Apple、Google): 查看 references/platform-notes.md
- 编辑(schema、十进制序列化、刷新): 查看 references/codeless-catalog.md
IAPProductCatalog.json - v4 → v5迁移: 查看 references/migration-v4-to-v5.md
- 将原生Google BillingClient转换为Unity IAP 5: 查看 references/path-convert-native-google-billing.md
- 将原生iOS StoreKit插件转换为Unity IAP 5: 查看 references/path-convert-native-storekit.md
- 将Essential Kit计费转换为Unity IAP 5: 查看 references/convert-essentialkit.md
- UniPay(FLOBUK)——评估与指导: 查看 references/convert-unipay.md
- RevenueCat——转换评估与指导: 查看 references/convert-revenuecat.md
- Adapty——转换评估与指导: 查看 references/convert-adapty.md
- 向无现有IAP的项目添加Unity IAP 5: 查看 references/path-add-iap-to-new-project.md
- 实现IAP D2C能力(第三方支付提供商——Stripe/Coda,需要v5.4+): 查看 references/path-implement-iap-d2c.md
按需阅读参考文档——仅当你需要特定API签名、平台扩展细节或迁移映射时再查看。
Initialization Flow
初始化流程
- Obtain via
StoreController(or individual services viaUnityIAPServices.StoreController(),DefaultStore(),DefaultProduct())DefaultPurchase() - Subscribe to all required events (see Required Event Subscriptions below) before calling
Connect() - to connect to the platform store
await store.Connect() - On , call
OnStoreConnectedto load the catalogstore.FetchProducts(List<ProductDefinition>) - On , products are ready for display and purchase
OnProductsFetched
Use for initialization — ensures IAP is ready before other methods.
Awake()Start()Product types: , , .
ProductType.ConsumableProductType.NonConsumableProductType.Subscription- 通过获取
UnityIAPServices.StoreController()(或通过StoreController、DefaultStore()、DefaultProduct()获取独立服务)DefaultPurchase() - 在调用之前,订阅所有必需的事件(见下方“必需事件订阅”)
Connect() - 调用连接至平台商店
await store.Connect() - 在触发时,调用
OnStoreConnected加载产品目录store.FetchProducts(List<ProductDefinition>) - 在触发时,产品即可用于展示和购买
OnProductsFetched
使用进行初始化——确保IAP在其他方法执行前准备就绪。
Awake()Start()产品类型:、、。
ProductType.ConsumableProductType.NonConsumableProductType.SubscriptionFetching Products
获取产品
Define products as and pass to . Use when product IDs differ across Apple/Google stores. For complex catalogs, use to manage product sets and store-specific IDs.
List<ProductDefinition>store.FetchProducts()StoreSpecificIdsCatalogProvider| Method | Behavior |
|---|---|
| Returns the cached product list (synchronous, stale if |
| Queries the store for fresh pricing/availability and updates the cache |
| Returns a single cached product by ID |
These are NOT interchangeable. Always call first before relying on .
FetchProducts()GetProducts()将产品定义为并传入。当产品ID在Apple/Google商店中不同时,使用。对于复杂目录,使用管理产品集和商店特定ID。
List<ProductDefinition>store.FetchProducts()StoreSpecificIdsCatalogProvider| 方法 | 行为 |
|---|---|
| 返回缓存的产品列表(同步操作,若未调用 |
| 向商店查询最新定价/可用性并更新缓存 |
| 通过ID返回单个缓存产品 |
这些方法不可互换。在依赖之前,务必先调用。
GetProducts()FetchProducts()Two-Step Purchase Flow
两步购买流程
IAP v5 uses a mandatory two-step flow: Pending → Confirm.
- — initiates the platform purchase dialog
store.PurchaseProduct(product) - fires — you receive a
OnPurchasePendingPendingOrder - Validate the receipt, grant content to the player
- — finalizes the transaction
store.ConfirmPurchase(pendingOrder) - fires — receives
OnPurchaseConfirmedbase type; pattern-matchOrder(success) vsConfirmedOrder(confirmation failed)FailedOrder
You MUST call after granting content. Unconfirmed purchases are re-delivered on next app launch to prevent lost purchases.
ConfirmPurchase(pendingOrder)De-duplication: may fire multiple times for the same purchase (e.g., app restart before confirmation). Always check if content was already granted.
OnPurchasePendingConsumables: Confirmed consumable purchases are NOT returned by . Track consumable grants yourself (e.g., in Cloud Save or Economy).
FetchPurchasesDeferred purchases: fires for Ask-to-Buy (iOS) and Google Play deferred purchases. Do NOT grant content — wait for when approved.
OnPurchaseDeferredOnPurchasePendingIAP v5使用强制的两步流程:待处理 → 确认。
- —— 启动平台购买对话框
store.PurchaseProduct(product) - 触发 —— 你会收到一个
OnPurchasePendingPendingOrder - 验证收据,向玩家发放内容
- —— 完成交易
store.ConfirmPurchase(pendingOrder) - 触发 —— 接收
OnPurchaseConfirmed基类;通过模式匹配区分Order(成功)与ConfirmedOrder(确认失败)FailedOrder
在发放内容后必须调用。未确认的购买会在下次应用启动时重新推送,以避免购买丢失。
ConfirmPurchase(pendingOrder)去重处理: 可能针对同一购买多次触发(例如,确认前重启应用)。务必检查内容是否已发放。
OnPurchasePending消耗型产品: 已确认的消耗型购买不会通过返回。请自行跟踪消耗型产品的发放记录(例如,在Cloud Save或Economy中)。
FetchPurchases延迟购买: 会在iOS的Ask-to-Buy和Google Play延迟购买时触发。此时请勿发放内容——等待批准后触发时再处理。
OnPurchaseDeferredOnPurchasePendingRestore Transactions
恢复交易
store.RestoreTransactions(callback)OnPurchasePendingRequired on iOS for Apple App Store compliance — add a "Restore Purchases" button.
Apple non-renewable subscriptions cannot be restored via . Track these server-side.
RestoreTransactionsstore.RestoreTransactions(callback)OnPurchasePending根据Apple App Store合规要求,iOS平台必须添加“恢复购买”按钮。
Apple非续订订阅无法通过恢复。请在服务器端跟踪这些订阅。
RestoreTransactionsReceipt Validation
收据验证
| Platform | Approach |
|---|---|
| Google Play | |
| Apple (StoreKit 2) | Local validation is a no-op. Use |
Generate tangle data via Services > In-App Purchasing > Receipt Validation Obfuscator in the Unity Editor.
| 平台 | 实现方式 |
|---|---|
| Google Play | 使用 |
| Apple(StoreKit 2) | 本地验证无效。使用 |
在Unity编辑器中,通过Services > In-App Purchasing > Receipt Validation Obfuscator生成tangle数据。
Entitlement Checking
权限检查
Use when you don't have the and want to know the status of a specific product (replaces v4's ). If you already have the , check its type instead: maps to (consumables) or (non-consumables/subscriptions), maps to .
Orderproduct.hasReceiptOrderPendingOrderEntitledUntilConsumedEntitledButNotFinishedConfirmedOrderFullyEntitledCall and handle . Check .
store.CheckEntitlement(product)store.OnCheckEntitlemententitlement.Status == EntitlementStatus.FullyEntitledEntitlementStatusFullyEntitledEntitledUntilConsumedEntitledButNotFinishedNotEntitledUnknown当你没有但想了解特定产品的状态时使用此功能(替代v4中的)。如果已有,则直接检查其类型:对应(消耗型)或(非消耗型/订阅),对应。
Orderproduct.hasReceiptOrderPendingOrderEntitledUntilConsumedEntitledButNotFinishedConfirmedOrderFullyEntitled调用并处理。检查。
store.CheckEntitlement(product)store.OnCheckEntitlemententitlement.Status == EntitlementStatus.FullyEntitledEntitlementStatusFullyEntitledEntitledUntilConsumedEntitledButNotFinishedNotEntitledUnknownFetch Existing Purchases
获取现有购买记录
store.FetchPurchases()| Method | Behavior |
|---|---|
| Returns the cached purchase list |
| Queries the store for current purchases and overwrites the cached list |
FetchPurchases()store.FetchPurchases()| 方法 | 行为 |
|---|---|
| 返回缓存的购买记录列表 |
| 向商店查询当前购买记录并覆盖缓存列表 |
FetchPurchases()Subscription Info
订阅信息
Subscription info is on , accessed via — NOT on ( only has and ).
IPurchasedProductInfoorder.Info.PurchasedProductInfoCartItemCartItemProductQuantityIsSubscribed()ResultTrueFalseUnsupportedbool== Result.True订阅信息位于,可通过访问——不在上(仅包含和)。
IPurchasedProductInfoorder.Info.PurchasedProductInfoCartItemCartItemProductQuantityIsSubscribed()ResultTrueFalseUnsupportedbool== Result.TrueRequired Event Subscriptions
必需事件订阅
Always subscribe to BOTH success and failure events. Not subscribing to failure events generates runtime warnings.
| Call | Success Event | Failure Event (REQUIRED) |
|---|---|---|
| | |
| | |
| | |
| | |
| | — |
Always subscribe to — fires for Ask-to-Buy (iOS) and Google Play deferred purchases. Not subscribing silently drops deferred purchases.
OnPurchaseDeferredSubscribe to events BEFORE calling — pending purchases from a previous session may fire immediately.
Connect()务必同时订阅成功和失败事件。未订阅失败事件会生成运行时警告。
| 调用 | 成功事件 | 失败事件(必需) |
|---|---|---|
| | |
| | |
| | |
| | |
| | — |
务必订阅——在iOS的Ask-to-Buy和Google Play延迟购买时触发。未订阅此事件会导致延迟购买被静默丢弃。
OnPurchaseDeferred在调用之前订阅事件——上一会话的待处理购买可能会立即触发。
Connect()Failure Description Property Names
失败描述属性名称
These property names are NOT interchangeable — using the wrong one causes CS1061:
| Type | Field | Property | NOT |
|---|---|---|---|
| | | |
| — | | |
| — | | — |
| | | — |
这些属性名称不可互换——使用错误名称会导致CS1061错误:
| 类型 | 字段 | 属性 | 请勿使用 |
|---|---|---|---|
| | | |
| — | | |
| — | | — |
| | | — |
Validation
验证
After writing code that uses this package:
- Verify the project compiles without errors.
- Confirm all API calls match the v5 signatures in api-notes.md — do NOT use v4 legacy patterns (,
IStoreListener,UnityPurchasing.Initialize).ConfigurationBuilder - Check the "Anti-Hallucination: Common v5 Mistakes" table in api-notes.md — do NOT use (use
OnStoreConnectionFailed), do NOT pass callbacks toOnStoreDisconnected/FetchProducts(use events), do NOT useFetchPurchases(useproduct.receipt).order.Info.Receipt - Check that all required events are subscribed before calling (see Required Event Subscriptions table above).
Connect() - Verify the two-step purchase flow: → grant content →
OnPurchasePending.ConfirmPurchase(pendingOrder) - Confirm both success and failure events are subscribed for every async operation (/
OnProductsFetched,OnProductsFetchFailed/OnStoreConnected, etc.).OnStoreDisconnected - If handling subscriptions, verify is compared with
IsSubscribed(), not cast to== Result.True.bool - If updated files coexist with legacy versions in the same project, use a unique namespace (e.g., add suffix) to avoid CS0101/CS0111 compilation errors.
.Updated - If the project subscribes to (v5.4+): verify the handler re-fetches products and purchases from scratch — Unity IAP clears both caches before raising this event. Do not read
OnAuthAccountChangedorGetProducts()inside the handler.GetPurchases()
在编写使用此包的代码后:
- 验证项目编译无错误。
- 确认所有API调用与api-notes.md中的v5签名匹配——请勿使用v4遗留模式(、
IStoreListener、UnityPurchasing.Initialize)。ConfigurationBuilder - 查看api-notes.md中的“防误解:常见v5错误”表格——请勿使用(使用
OnStoreConnectionFailed),请勿向OnStoreDisconnected/FetchProducts传递回调(使用事件),请勿使用FetchPurchases(使用product.receipt)。order.Info.Receipt - 确认所有必需事件在调用之前已订阅(见上方“必需事件订阅”表格)。
Connect() - 验证两步购买流程:→ 发放内容 →
OnPurchasePending。ConfirmPurchase(pendingOrder) - 确认每个异步操作都同时订阅了成功和失败事件(/
OnProductsFetched、OnProductsFetchFailed/OnStoreConnected等)。OnStoreDisconnected - 如果处理订阅,请验证是与
IsSubscribed()比较,而非转换为== Result.True。bool - 如果项目中更新后的文件与遗留版本共存,请使用唯一命名空间(例如添加后缀)以避免CS0101/CS0111编译错误。
.Updated - 如果项目订阅了(v5.4+):验证处理程序会重新从头获取产品和购买记录——Unity IAP在触发此事件前会清除两者的缓存。请勿在处理程序中读取
OnAuthAccountChanged或GetProducts()。GetPurchases()