开始
复制一个可复制的设置提示,包含安装步骤和此插件的完整 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.
安装
标题为“安装”您可以使用我们的 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.如果您更喜欢手动设置,请运行以下命令安装插件,并按照以下平台特定的说明进行操作:
-
安装包
终端窗口 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();- Android
- 使用 StoreKit 本地测试或 Sandbox 测试者进行 QA。
- 无需修改清单。确保您的产品已获得批准。
- 在 Google Play 控制台中创建应用内产品和订阅。
- 上传至少一个内部测试版本并添加许可测试者。
- 添加以下权限到
AndroidManifest.xml:
<uses-permission android:name="com.android.vending.BILLING" /> - Android
购买服务示例
标题:购买服务示例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, }), }); }}必需的购买选项
标题:必需的购买选项| 选项 | 平台 | 描述 |
|---|---|---|
productIdentifier | iOS + Android | SKU/Product ID |
productType | 仅限 Android | PURCHASE_TYPE.INAPP 或 PURCHASE_TYPE.SUBS或 INAPP或 SUBS 或 |
planIdentifier | 仅限 Android 订阅 | 仅限 iOS 订阅 |
billingPlanType | 仅限 Android 订阅 | StoreKit billing plan to purchase. Use 'monthly' for monthly billing with a 12-month commitment when product.pricingTerms exposes that option. |
quantity | iOS | Only for in-app purchases, defaults to 1. Android always purchases one item. |
appAccountToken | iOS + Android | 移动平台 |
isConsumable | UUID/string linking the purchase to your user. Required to be UUID on iOS; Android accepts any obfuscated string up to 64 chars. | Android true 设置为 false. |
to auto-consume tokens after granting entitlement for consumables. Defaults to
Section titled “检查资格状态”Use 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调用以获取权威状态。purchaseTokenSection titled “检查资格状态”purchaseState必须是PURCHASED和isAcknowledged必须是true.
API 快速参考
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)。
最佳实践
最佳实践- 显示商店价格 – Apple要求显示
product.title并且product.priceString; 不要硬编码 - 使用
appAccountToken– 从用户ID中确定生成一个UUID(v5)来将购买与帐户关联。 - 验证服务器端 – 发送
receipt(iOS) /purchaseToken(Android) 到您的后端进行验证。 - 处理错误 – 检查用户取消、网络故障和不支持的计费环境。
- 进行彻底的测试 – 遵循 iOS沙盒指南 和 Android沙盒指南.
- 提供恢复和管理 – 添加UI按钮,连接到
restorePurchases()和manageSubscriptions().
收入下一步
收入下一步购买流程正常后,使用 营收手册 来规划您的第一个付费渠道:产品范围、ASO、定价、付费墙位置、分析和流失反馈。
标题为“故障排除”的小节
- 产品未加载
- 确保包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
标题为“继续从 Getting Started”如果您正在使用 开始使用 为商店批准和分发做好准备,连接它 使用@capgo/native-purchases 为native能力在使用@capgo/native-purchases中 @capgo/capacitor-in-app-review 为@capgo/capacitor-in-app-review的实现细节 使用@capgo/capacitor-in-app-review 为native能力在使用@capgo/capacitor-in-app-review中 @capgo/capacitor-native-market 为@capgo/capacitor-native-market的实现细节, 使用@capgo/capacitor-native-market 为native能力在使用@capgo/capacitor-native-market中