跳过内容

Getting Started

GitHub

安装

安装

您可以使用我们的 AI 助手设置来安装插件。使用以下命令将 Capgo 技能添加到您的 AI 工具中:

终端窗口
npx skills add https://github.com/Cap-go/capgo-skills --skill capacitor-plugins

然后使用以下提示:

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();
    • Android
    • 在App Store Connect中创建应用内产品和订阅。
    • 使用StoreKit Local Testing或Sandbox测试者进行QA。

购买服务示例

购买服务示例
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,
}),
});
}
}

必需购买选项

选项
平台描述iOS + Android
productIdentifier在 App Store Connect / Google Play Console 中配置的 SKU/产品 IDSKU/Product ID configured in App Store Connect / Google Play Console.
productType仅限 AndroidPURCHASE_TYPE.INAPPPURCHASE_TYPE.SUBS. 默认为 INAPP. 始终设置为 SUBS 用于订阅.
planIdentifier仅限 Android 订阅来自 Google Play Console 的基本计划 ID。 必须用于订阅,忽略 iOS 和内购。
billingPlanType仅限 iOS 订阅StoreKit billing 计划用于购买。 使用 'monthly' 进行每月付款的 12 个月承诺时 product.pricingTerms 显示该选项。
quantityiOS仅限在应用内购买, 1. Android 总是购买一个项目。
appAccountTokeniOS + AndroidUUID/字符串将购买与您的用户关联。 iOS 必须是 UUID; Android 可以接受最多 64 个字符的任何混淆字符串。
isConsumableAndroid设置为 true 自动消耗令牌后,自动消耗令牌以授予消耗性权利。 默认值为 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);
}
});

Platform behavior

iOS
  • iOSSubscriptions包含 isActive, expirationDate, willCancel, and StoreKit 2 listener support. In-app purchases require server receipt validation.
  • Android: isActive/expirationDate are not populated; call the Google Play Developer API with the purchaseToken for authoritative status. purchaseState must be PURCHASED and isAcknowledged __CAPGO_KEEP_0__快速参考 true.

API quick reference

API快速参考
  • isBillingSupported() – 检查StoreKit / Google Play的可用性。
  • getProduct() / getProducts() – 获取价格、本地化标题、描述、引导性优惠和支持的iOS定价条款。
  • purchaseProduct() – 初始化StoreKit 2或Billing客户端购买流程,包括iOS月度承诺付款计划。
  • restorePurchases() – 重放历史购买并同步到当前设备。
  • getPurchases() – 列出所有iOS交易或Play Billing购买。
  • manageSubscriptions() – 打开本机订阅管理UI。
  • addListener('transactionUpdated') – 处理启动应用程序时的待处理StoreKit 2交易(仅限iOS)。
  1. 显示商店价格 – 苹果要求显示 product.title 和; 不要硬编码。 product.priceString使用
  2. – 根据用户 ID 确定生成一个 UUID (v5),将购买与帐户关联。 appAccountToken 在服务器端验证
  3. – 发送 (iOS) / receipt (Android) 到您的后端进行验证。 purchaseToken 优雅地处理错误
  4. – 检查用户取消、网络故障和不支持的付款环境。 进行彻底的测试
  5. – 遵循 protectedTokens iOS沙盒指南Android沙盒指南.
  6. 恢复和管理 – 添加UI按钮连接到 restorePurchases()manageSubscriptions().

在购买流程正常工作后,使用 收入手册 规划您的第一笔付费渠道:产品范围、ASO、定价、付款墙位置、分析和流失反馈。

故障排除

Troubleshooting

产品未加载

  • 确保包 ID/应用 ID 与商店配置匹配。
  • 确认产品 ID 为激活状态且已通过审批(App Store)或激活(Google Play)。
  • 创建产品后等待数小时;商店更新不是即时的。

购买取消或卡顿

  • 用户可以在流程中取消;将调用包裹在 try/catch 并显示友好的错误消息。
  • 对于 Android,确保测试账户从 Play Store(内部跟踪)安装应用程序,以便Billing正常工作。
  • 在设备上运行时,请检查 logcat/Xcode 中的Billing错误。

订阅状态错误

  • 使用 getPurchases() 与您的本地认证缓存进行数据比较。
  • 在 Android 上,始终使用 Google Play Developer API 查询 purchaseToken 以获取过期日期或退款状态。
  • 在 iOS 上,检查 isActive/expirationDate 并验证收据以检测退款或撤销。

如果您正在使用 Getting Started 以规划商店批准和分发,连接它与 使用 @capgo/native-purchases 为 Using @capgo/native-purchases 中的本机能力 @capgo/capacitor-in-app-评论 为 @capgo/capacitor-in-app-评论 的实现细节 使用 @capgo/capacitor-in-app-评论 为 @capgo/capacitor-in-app-评论 的原生能力 @capgo/capacitor-native-市场 为 @capgo/capacitor-native-市场 的实现细节, 和 使用 @capgo/capacitor-native-市场 为 @capgo/capacitor-native-市场 的原生能力