快速入门
复制包含安装步骤和该插件完整 Markdown 指南的配置 prompt。
Set up this Capacitor plugin in the project.
Use the package manager already used by the project.
Install these package(s): `@capgo/native-purchases`
Run the required Capacitor sync/update step after installation.
Read this markdown guide for the full setup steps: https://raw.githubusercontent.com/Cap-go/website/refs/heads/main/apps/docs/src/content/docs/docs/plugins/native-purchases/getting-started.mdx
Use that guide for platform-specific steps, native file edits, permissions, config changes, imports, and usage setup.
If that guide references other docs pages, read them too.
你可以使用我们的 AI 辅助设置来安装插件。使用以下命令将 Capgo skills 添加到你的 AI 工具中:
npx skills add https://github.com/Cap-go/capgo-skills --skill capacitor-plugins然后使用以下 prompt:
Use the `capacitor-plugins` skill from `Cap-go/capgo-skills` to install the `@capgo/native-purchases` plugin in my project.如果你更想手动设置,请运行以下命令安装插件,并按照下方各平台的说明操作:
-
安装软件包
终端窗口 bun add @capgo/native-purchases -
与原生项目同步
终端窗口 bunx cap sync -
检查计费支持
import { NativePurchases } from '@capgo/native-purchases';const { isBillingSupported } = await NativePurchases.isBillingSupported();if (!isBillingSupported) {throw new Error('Billing is not available on this device');} -
直接从商店加载产品
import { NativePurchases, PURCHASE_TYPE } from '@capgo/native-purchases';const { products } = await NativePurchases.getProducts({productIdentifiers: ['com.example.premium.monthly','com.example.premium.yearly','com.example.one_time_unlock'],productType: PURCHASE_TYPE.SUBS, // Use PURCHASE_TYPE.INAPP for one‑time products});products.forEach((product) => {console.log(product.title, product.priceString);}); -
实现购买与恢复流程
import { NativePurchases, PURCHASE_TYPE } from '@capgo/native-purchases';const monthlyPlanId = 'monthly-plan'; // Base Plan ID from Google Play Consoleconst transaction = await NativePurchases.purchaseProduct({productIdentifier: 'com.example.premium.monthly',planIdentifier: monthlyPlanId, // REQUIRED for Android subscriptions, ignored on iOSproductType: PURCHASE_TYPE.SUBS,quantity: 1,});console.log('Transaction ID', transaction.transactionId);await NativePurchases.restorePurchases();- 在 App Store Connect 中创建应用内商品和订阅。
- 使用 StoreKit Local Testing 或 Sandbox 测试人员进行 QA。
- 无需修改 manifest。请确保您的产品已通过审核。
- 在 Google Play Console 中创建应用内产品和订阅。
- 上传至少一个内部测试构建,并添加许可测试人员。
- 将 billing 权限添加到
AndroidManifest.xml:
<uses-permission android:name="com.android.vending.BILLING" /> - 在 App Store Connect 中创建应用内商品和订阅。
内购服务示例
标题为“购买服务示例”的章节import { NativePurchases, PURCHASE_TYPE, Transaction } from '@capgo/native-purchases';import { Capacitor } from '@capacitor/core';
class PurchaseService { private premiumProduct = 'com.example.premium.unlock'; private monthlySubId = 'com.example.premium.monthly'; private monthlyPlanId = 'monthly-plan'; // Base Plan ID (Android only)
async initialize() { const { isBillingSupported } = await NativePurchases.isBillingSupported(); if (!isBillingSupported) throw new Error('Billing unavailable');
const { products } = await NativePurchases.getProducts({ productIdentifiers: [this.premiumProduct, this.monthlySubId], productType: PURCHASE_TYPE.SUBS, });
console.log('Loaded products', products);
if (Capacitor.getPlatform() === 'ios') { NativePurchases.addListener('transactionUpdated', (transaction) => { this.handleTransaction(transaction); }); } }
async buyPremium(appAccountToken?: string) { const transaction = await NativePurchases.purchaseProduct({ productIdentifier: this.premiumProduct, productType: PURCHASE_TYPE.INAPP, appAccountToken, });
await this.processTransaction(transaction); }
async buyMonthly(appAccountToken?: string) { const transaction = await NativePurchases.purchaseProduct({ productIdentifier: this.monthlySubId, planIdentifier: this.monthlyPlanId, // REQUIRED for Android subscriptions productType: PURCHASE_TYPE.SUBS, appAccountToken, });
await this.processTransaction(transaction); }
async restore() { await NativePurchases.restorePurchases(); await this.refreshEntitlements(); }
async openManageSubscriptions() { await NativePurchases.manageSubscriptions(); }
private async processTransaction(transaction: Transaction) { this.unlockContent(transaction.productIdentifier); this.validateOnServer(transaction).catch(console.error); }
private unlockContent(productIdentifier: string) { // persist entitlement locally console.log('Unlocked', productIdentifier); }
private async refreshEntitlements() { const { purchases } = await NativePurchases.getPurchases({ productType: PURCHASE_TYPE.SUBS, }); console.log('Current purchases', purchases); }
private async handleTransaction(transaction: Transaction) { console.log('StoreKit transaction update:', transaction); await this.processTransaction(transaction); }
private async validateOnServer(transaction: Transaction) { await fetch('/api/validate-purchase', { method: 'POST', body: JSON.stringify({ transactionId: transaction.transactionId, receipt: transaction.receipt, purchaseToken: transaction.purchaseToken, }), }); }}必选购买选项
标题为“必需的购买选项”的章节| 选项 | 平台 | 描述 |
|---|---|---|
productIdentifier | iOS + Android | 在 App Store Connect / Google Play Console 中配置的 SKU/产品 ID。 |
productType | 仅限 Android | PURCHASE_TYPE.INAPP 或 PURCHASE_TYPE.SUBS。默认为 INAPP。始终设置为 SUBS 用于订阅。 |
planIdentifier | Android 订阅 | 来自 Google Play Console 的基础计划 ID。订阅必需,iOS 和 IAP 中忽略。 |
billingPlanType | iOS 订阅 | 要购买的 StoreKit 计费方案。使用 'monthly' 进行按月计费并承诺 12 个月,当 product.pricingTerms 提供该选项时。 |
quantity | iOS | 仅适用于应用内购买,默认为 1。Android 始终购买一个商品。 |
appAccountToken | iOS + Android | 用于将购买与你的用户关联的 UUID/字符串。iOS 上必须为 UUID;Android 接受任意不超过 64 个字符的混淆字符串。 |
isConsumable | Android | 设置为 true 以在授予消耗型商品权益后自动消费 token。默认为 false. |
检查权益状态
“检查授权状态”部分使用 getPurchases() 若要跨平台查看各应用商店上报的每笔交易:
import { NativePurchases, PURCHASE_TYPE } from '@capgo/native-purchases';
const { purchases } = await NativePurchases.getPurchases({ productType: PURCHASE_TYPE.SUBS,});
purchases.forEach((purchase) => { if (purchase.isActive && purchase.expirationDate) { console.log('iOS sub active until', purchase.expirationDate); }
const isAndroidIapValid = ['PURCHASED', '1'].includes(purchase.purchaseState ?? '') && purchase.isAcknowledged;
if (isAndroidIapValid) { console.log('Grant in-app entitlement for', purchase.productIdentifier); }});平台行为
标题为“平台行为”的章节- iOS:订阅包括
isActive,expirationDate,willCancel,并支持 StoreKit 2 监听器。应用内购买需要服务端收据验证。 - Android:
isActive/expirationDate不会填充;请调用 Google Play Developer API,并带上purchaseToken以获取权威状态。purchaseState必须为PURCHASED以及isAcknowledged必须为true.
API 快速参考
标题为“API 快速参考”的章节isBillingSupported()– 检查 StoreKit / Google Play 是否可用。getProduct()/getProducts()– 获取价格、本地化标题、描述、入门优惠以及支持的 iOS 定价条款。purchaseProduct()– 发起 StoreKit 2 或 Billing client 购买流程,包括 iOS 月度承诺计费方案。restorePurchases()– 重放历史购买记录并同步到当前设备。getPurchases()– 列出所有 iOS 交易或 Play Billing 购买记录。manageSubscriptions()– 打开原生订阅管理 UI。addListener('transactionUpdated')– 在应用启动时处理待处理的 StoreKit 2 交易(仅限 iOS)。
最佳实践
标题为“最佳实践”的章节- 显示商店价格 – Apple 要求显示
product.title以及product.priceString;切勿硬编码。 - 使用
appAccountToken– 从用户 ID 确定性生成 UUID (v5),以将购买关联到账户。 - 服务端验证 – 发送
receipt(iOS)/purchaseToken(Android)发送到您的后端进行验证。 - 优雅地处理错误 – 检查用户取消、网络故障以及不支持的计费环境。
- 充分测试 – 请遵循 iOS 沙盒指南 以及 Android 沙盒指南.
- 提供恢复与管理功能 – 添加 UI 按钮并绑定到
restorePurchases()以及manageSubscriptions().
营收后续步骤
“收入后续步骤”部分购买流程跑通后,使用 营收手册 来规划你的首个付费漏斗:产品范围、ASO、定价、付费墙位置、数据分析以及流失反馈。
故障排除
“故障排除”章节产品未加载
- 确保 bundle ID / application ID 与应用商店配置一致。
- 确认产品 ID 已激活并获批(App Store)或已启用(Google Play)。
- 创建产品后请等待数小时;应用商店的同步并非即时完成。
购买被取消或卡住
- 用户可能在流程中途取消;请将调用包裹在
try/catch并显示友好的错误信息。 - 对于 Android,请确保测试账户从 Play Store(内部轨道)安装应用,以便 Billing 正常工作。
- 在真机上运行时,请检查 logcat/Xcode 中的计费错误。
订阅状态不正确
- 使用
getPurchases()用于对比商店数据与本地权益缓存。 - 在 Android 上,务必使用 ... 查询 Google Play Developer API
purchaseToken以获取到期日期或退款状态。 - 在 iOS 上,请检查
isActive/expirationDate并验证收据以检测退款或撤销。
从入门指南继续
“从入门指南继续”章节如果你正在使用 快速入门 要规划商店审核与分发,请将其与 使用 @capgo/native-purchases 关于“使用 @capgo/native-purchases”中的原生能力, @capgo/capacitor-in-app-review 有关 @capgo/capacitor-in-app-review 中的实现细节, 使用 @capgo/capacitor-in-app-review 有关《使用 @capgo/capacitor-in-app-review》中的原生能力, @capgo/capacitor-native-market 有关 @capgo/capacitor-native-market 的实现细节,以及 使用 @capgo/capacitor-native-market 有关使用 @capgo/capacitor-native-market. 时的原生能力