跳过内容

开始使用

  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。
    • 无需修改清单。确保您的产品已获得批准。

购买服务示例

标题:购买服务示例
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.INAPPPURCHASE_TYPE.SUBS默认为 INAPP始终设置为 SUBS 用于订阅。
planIdentifier__CAPGO_KEEP_0__来自 Google Play Console 的基本计划 ID。对于订阅必填,忽略 iOS 和内购。
billingPlanType__CAPGO_KEEP_0__StoreKit 购买计划。使用 'monthly' 进行每月定价的 12 个月承诺时暴露该选项。 product.pricingTerms iOS
quantity仅限内购,默认为。Android 总是购买一个项目。 1iOS + Android
appAccountTokenUUID/字符串将购买与您的用户关联。iOS 需要 UUID;Android 可以接受最多 64 个字符的任何混淆字符串。Android
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);
}
});

平台行为

平台行为
  • iOS: 订阅包括 isActive, expirationDate, willCancel,并且支持StoreKit 2监听器。内购需要服务器收据验证。
  • Android: isActive/expirationDate 不被填充; 请使用 Google Play Developer API 进行调用 purchaseToken 请参阅官方文档。 purchaseState 必须是 PURCHASEDisAcknowledged 必须是 true.
  • 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. 显示商店价格 – Apple 需要显示 product.title 并且 product.priceString;永远不要硬编码。
  2. 使用 appAccountToken – 根据用户 ID 确定生成 UUID (v5) 以将购买与帐户关联。
  3. 在服务器端验证 – 发送 receipt (iOS) / purchaseToken (Android) 到您的后端进行验证。
  4. 优雅地处理错误 – 检查用户取消、网络故障和不支持的计费环境。
  5. 进行彻底的测试 – 遵循 iOS 沙盒指南Android 沙盒指南.
  6. 提供恢复和管理 – 添加 UI 按钮,连接到 restorePurchases() and manageSubscriptions().

收入下一步

收入下一步

购买流程完成后,使用 收入手册 计划您的第一个付费渠道:产品范围、ASO、定价、付费墙位置、分析和流失反馈。

故障排除

故障排除

产品未加载

  • 确保bundle ID / 应用程序ID与商店配置匹配。
  • 确认产品ID处于激活状态且已批准(App Store)或激活(Google Play)。
  • 创建产品后等待几小时;商店传播不是即时的。

购买已取消或卡住

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

订阅状态不正确

  • 使用 getPurchases() 来比较商店数据与您的本地权利缓存。
  • On Android, always query the Google Play Developer API with the purchaseToken 来获取过期日期或退款状态。
  • 在 iOS 上,检查 isActive/expirationDate 并验证收据以检测退款或撤销