跳转到正文

快速入门

GitHub

你可以使用我们的 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.

如果你更想手动设置,请运行以下命令安装插件,并按照下方各平台的说明操作:

  1. 安装软件包

    终端窗口
    bun add @capgo/native-purchases
  2. 与原生项目同步

    终端窗口
    bunx cap sync
  3. 检查账单支持

    import { NativePurchases } from '@capgo/native-purchases';
    const { isBillingSupported } = await NativePurchases.isBillingSupported();
    if (!isBillingSupported) {
    throw new Error('Billing is not available on this device');
    }
  4. 直接从商店加载商品

    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);
    });
  5. 实现购买与恢复流程

    import { NativePurchases, PURCHASE_TYPE } from '@capgo/native-purchases';
    const monthlyPlanId = 'monthly-plan'; // Base Plan ID from Google Play Console
    const transaction = await NativePurchases.purchaseProduct({
    productIdentifier: 'com.example.premium.monthly',
    planIdentifier: monthlyPlanId, // REQUIRED for Android subscriptions, ignored on iOS
    productType: PURCHASE_TYPE.SUBS,
    quantity: 1,
    });
    console.log('Transaction ID', transaction.transactionId);
    await NativePurchases.restorePurchases();
    • 在 App Store Connect 中创建应用内商品和订阅。
    • 使用 StoreKit Local Testing 或 Sandbox 测试人员进行 QA。
    • 无需修改 manifest。请确保您的产品已通过审核。
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,
}),
});
}
}
选项平台描述
productIdentifieriOS + Android在 App Store Connect / Google Play Console 中配置的 SKU/Product ID。
productType仅限 AndroidPURCHASE_TYPE.INAPP 或 PURCHASE_TYPE.SUBS。默认为 INAPP。始终设置为 SUBS 用于订阅。
planIdentifierAndroid 订阅来自 Google Play Console 的 Base Plan ID。订阅必填,在 iOS 和应用内购买中会被忽略。
billingPlanTypeiOS 订阅要购买的 StoreKit 计费方案。请使用 'monthly' 适用于签署 12 个月合约的按月计费方案,当 product.pricingTerms 显示该选项时。
quantityiOS仅限应用内购买,默认为 1。Android 始终购买单个项目。
appAccountTokeniOS + Android将购买记录与用户关联的 UUID/字符串。iOS 必须为 UUID;Android 支持最多 64 个字符的任何混淆字符串。
isConsumableAndroid设置为 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.
  • 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)。
  1. 展示商店价格 – Apple 要求展示 product.title 以及 product.priceString;切勿硬编码。
  2. 使用 appAccountToken – 根据用户 ID 确定性地生成 UUID (v5),以便将购买记录与账户关联。
  3. 服务端验证 – 将 receipt (iOS) / purchaseToken (Android) 发送到您的后端进行验证。
  4. 优雅地处理错误 – 检查用户取消、网络故障以及不支持的计费环境。
  5. 进行彻底测试 – 请遵循 iOS sandbox 指南 以及 Android sandbox 指南.
  6. 提供恢复与管理功能 – 添加与以下内容关联的 UI 按钮 restorePurchases() 以及 manageSubscriptions().

在购买流程运行正常后,请使用 营收手册 规划首个付费漏斗:确定产品范围、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. 时的原生能力