跳转到正文

快速入门

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/产品 ID。
productType仅限 AndroidPURCHASE_TYPE.INAPP 或 PURCHASE_TYPE.SUBS。默认为 INAPP。始终设置为 SUBS 用于订阅。
planIdentifierAndroid 订阅来自 Google Play Console 的基础计划 ID。订阅必需,iOS 和 IAP 中忽略。
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 沙盒指南 以及 Android 沙盒指南.
  6. 提供恢复与管理功能 – 添加 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. 时的原生能力