入门指南
复制一个包含安装步骤和完整 Markdown 指南的配置提示。
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.
-
安装包
系统计操作安全 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。
- 无需编辑清单。确保您的产品已获得批准。
- 在 Google Play Console 中创建应用内产品和订阅。
- 上传至少一个内部测试版本并添加许可测试者。
- 添加
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, }), }); }}必填购买选项
Section titled “必需购买选项”| 选项 | 平台 | 描述 |
|---|---|---|
productIdentifier | iOS + Android | 在 App Store Connect / Google Play Console 中配置的 SKU/产品 ID。 |
productType | 仅 Android | PURCHASE_TYPE.INAPP 或 PURCHASE_TYPE.SUBS。默认为 INAPP。始终设置为 SUBS 用于订阅。 |
planIdentifier | 仅 Android 订阅 | 来自 Google Play Console 的基本计划 ID。对于订阅必填,忽略 iOS 和内购。 |
quantity | iOS | 仅用于内购,缺省为 1Android 总是购买一个项目。 |
appAccountToken | iOS + Android | UUID/字符串将购买与您的用户关联。对于 iOS 必须是 UUID;Android 可以接受最多 64 个字符的混淆字符串。 |
isConsumable | Android | 设置为 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开发者APIpurchaseToken以获取权威状态。purchaseState必须PURCHASED和isAcknowledged必须true.
API 快速参考
标题:API 快速参考isBillingSupported()– 检查 StoreKit / Google Play 可用性。getProduct()/getProducts()– 获取价格、本地化标题、描述和介绍优惠。purchaseProduct()– 初始化 StoreKit 2 或 Billing 客户端购买流程。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沙盒指南 和 Android沙盒指南.
- 提供恢复和管理 – 添加UI按钮
restorePurchases()和manageSubscriptions().
收入下一步
标题为“收入下一步”购买流程工作后,使用 收入手册 为您的第一笔付费漏斗做好准备:产品范围、ASO、定价、付费墙位置、分析和流失反馈。
故障排除
标题:故障排除产品未加载
- 确保 bundle ID / 应用程序 ID 与商店配置匹配。
- 确认产品 ID 为活动状态且已批准(App Store)或激活(Google Play)。
- 创建产品后等待几小时;商店的传播不是即刻的。
购买取消或卡住
- 用户可以在流程中取消;将调用包裹在
try/catch并显示友好的错误消息。 - 对于 Android,请确保测试帐户从 Play Store(内部跟踪)安装应用程序,以便Billing正常工作。
- 在设备上运行时,检查 logcat/Xcode 中的Billing错误。
订阅状态不正确
- 使用
getPurchases()将商店数据与本地许可证缓存进行比较。 - 在 Android 上,始终使用 Google Play 开发者API
purchaseToken以获取过期日期或退款状态。 - 在 iOS 上,检查
isActive/expirationDate并验证收据以检测退款或撤销。