快速入门
复制包含安装步骤和该插件完整 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 中创建应用内商品和订阅。
- 上传至少一个内部测试版 build 并添加许可测试人员。
- 将 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/Product ID。 |
productType | 仅限 Android | PURCHASE_TYPE.INAPP 或 PURCHASE_TYPE.SUBS。默认为 INAPP。始终设置为 SUBS 用于订阅。 |
planIdentifier | Android 订阅 | 来自 Google Play Console 的 Base Plan ID。订阅必填,在 iOS 和应用内购买中会被忽略。 |
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 sandbox 指南 以及 Android sandbox 指南.
- 提供恢复与管理功能 – 添加与以下内容关联的 UI 按钮
restorePurchases()以及manageSubscriptions().
Revenue 下一步操作
标题为 “Revenue 下一步操作” 的章节在购买流程运行正常后,请使用 营收手册 规划首个付费漏斗:确定产品范围、ASO、定价、付费墙位置、数据分析及流失反馈。
故障排除
“故障排除”章节产品无法加载
- 请确保 Bundle ID / Application ID 与商店配置一致。
- 确认 Product ID 已处于活跃且通过审核状态 (App Store) 或已激活 (Google Play)。
- 创建产品后请等待数小时;商店的数据同步并非即时完成。
购买已取消或卡住
- 用户可能会在流程中途取消;请使用 try-catch 包裹调用
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. 时的原生能力