Erste Schritte
Kopiere einen Setup-Prompt mit den Installationsschritten und dem vollständigen Markdown-Guide für dieses Plugin.
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.
Installation
Abschnitt mit dem Titel „Installation“Du kannst unser KI-gestütztes Setup nutzen, um das Plugin zu installieren. Füge deinem KI-Tool die Capgo Skills mit folgendem Befehl hinzu:
npx skills add https://github.com/Cap-go/capgo-skills --skill capacitor-pluginsNutze anschließend diesen Prompt:
Use the `capacitor-plugins` skill from `Cap-go/capgo-skills` to install the `@capgo/native-purchases` plugin in my project.Wenn du ein manuelles Setup bevorziehst, installiere das Plugin mit den folgenden Befehlen und befolge die plattformspezifischen Anweisungen unten:
-
Paket installieren
Terminalfenster bun add @capgo/native-purchases -
Mit nativen Projekten synchronisieren
Terminalfenster bunx cap sync -
Abrechnungsunterstützung prüfen
import { NativePurchases } from '@capgo/native-purchases';const { isBillingSupported } = await NativePurchases.isBillingSupported();if (!isBillingSupported) {throw new Error('Billing is not available on this device');} -
Produkte direkt aus den Stores laden
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);}); -
Kauf- & Wiederherstellungs-Flows implementieren
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();- Erstelle In-App-Produkte und Abonnements in App Store Connect.
- Nutze StoreKit Local Testing oder Sandbox-Tester für die QA.
- Keine Manifest-Änderungen nötig. Stelle sicher, dass deine Produkte genehmigt sind.
- Erstelle In-App-Produkte und Abonnements in der Google Play Console.
- Lade mindestens einen internen Test-Build hoch und füge Lizenztester hinzu.
- Füge die Billing-Permission zu
AndroidManifest.xml:
<uses-permission android:name="com.android.vending.BILLING" /> - Erstelle In-App-Produkte und Abonnements in App Store Connect.
Beispiel für Purchase-Service
Abschnitt mit dem Titel „Purchase service example“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, }), }); }}Erforderliche Kaufoptionen
Abschnitt mit dem Titel „Required purchase options“| Option | Plattform | Beschreibung |
|---|---|---|
productIdentifier | iOS + Android | In App Store Connect / Google Play Console konfigurierte SKU/Produkt-ID. |
productType | Nur Android | PURCHASE_TYPE.INAPP oder PURCHASE_TYPE.SUBS. Standardmäßig INAPP. Always set to SUBS für Abonnements. |
planIdentifier | Android-Abonnements | Base Plan ID aus der Google Play Console. Erforderlich für Abonnements, wird bei iOS und In-App-Käufen ignoriert. |
billingPlanType | iOS-Abonnements | StoreKit-Abrechnungsplan zum Kauf. Nutze 'monthly' für monatliche Abrechnung bei 12-monatiger Bindung, wenn product.pricingTerms diese Option anbietet. |
quantity | iOS | Nur für In-App-Käufe, Standard ist 1. Android kauft immer ein Element. |
appAccountToken | iOS + Android | UUID/String zur Verknüpfung des Kaufs mit deinem User. Auf iOS muss es eine UUID sein; Android akzeptiert jeden verschleierten String bis zu 64 Zeichen. |
isConsumable | Android | Auf true setzen, um Tokens nach Gewährung des Entitlements bei Consumables automatisch zu verbrauchen. Standard ist false. |
Prüfen des Entitlement-Status
Abschnitt mit dem Titel „Prüfen des Entitlement-Status“Nutze getPurchases() für eine plattformübergreifende Übersicht aller von den Stores gemeldeten Transaktionen:
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); }});Plattformverhalten
Abschnitt mit dem Titel „Plattformverhalten“- iOS: Abonnements beinhalten
isActive,expirationDate,willCancel, sowie StoreKit 2 Listener-Support. In-App-Käufe erfordern eine Server-Validierung des Belegs. - Android:
isActive/expirationDatesind nicht ausgefüllt; rufen Sie die Google Play Developer API mit dempurchaseTokenfür den verbindlichen Status auf.purchaseStatemussPURCHASEDundisAcknowledgedmuss seintrue.
API Kurzübersicht
Abschnitt mit dem Titel „API Kurzübersicht“isBillingSupported()– Verfügbarkeit von StoreKit / Google Play prüfen.getProduct()/getProducts()– Preis, lokalisierter Titel, Beschreibung, Intro-Angebote und unterstützte iOS-Preiskonditionen abrufen.purchaseProduct()– startet den StoreKit 2 oder Billing-Client-Kaufprozess, einschließlich monatlicher Abonnements für iOS.restorePurchases()– Historische Käufe wiederherstellen und mit dem aktuellen Gerät synchronisieren.getPurchases()– Alle iOS-Transaktionen oder Play Billing-Käufe auflisten.manageSubscriptions()– Die native UI zur Abo-Verwaltung öffnen.addListener('transactionUpdated')– Ausstehende StoreKit 2-Transaktionen beim App-Start verarbeiten (nur iOS).
Best Practices
Abschnitt „Best Practices“- Store-Preise anzeigen – Apple schreibt die Anzeige vor
product.titleundproduct.priceString; niemals hardcoden. - Nutze
appAccountToken– generiere deterministisch eine UUID (v5) aus deiner User-ID, um Käufe mit Accounts zu verknüpfen. - Serverseitige Validierung – sende
receipt(iOS) /purchaseToken(Android) zur Verifizierung an dein Backend. - Fehler sauber abfangen – Prüfe auf Nutzerabbrüche, Netzwerkfehler und nicht unterstützte Abrechnungsumgebungen.
- Gründlich testen – Folge dem iOS Sandbox-Guide und Android Sandbox-Guide.
- Offer-Wiederherstellung & Management – Füge UI-Buttons hinzu, die mit
restorePurchases()undmanageSubscriptions().
Revenue-Nächste-Schritte
Abschnitt mit dem Titel „Revenue next steps“Sobald der Purchase-Flow funktioniert, nutze den Umsatz-Playbook Um deinen ersten Paid Funnel zu planen: Produktumfang, ASO, Pricing, Paywall-Platzierung, Analytics und Churn-Feedback.
Fehlerbehebung
Abschnitt mit dem Titel „Troubleshooting“Produkte werden nicht geladen
- Stelle sicher, dass die Bundle ID / Application ID mit der Store-Konfiguration übereinstimmt.
- Prüfe, ob die Product IDs aktiv und genehmigt (App Store) oder aktiviert (Google Play) sind.
- Warte nach dem Erstellen der Produkte einige Stunden; die Store-Propagation erfolgt nicht sofort.
Kauf abgebrochen oder hängt
- User können den Flow abbrechen; umschließe die Aufrufe mit
try/catchund zeige benutzerfreundliche Fehlermeldungen an. - Bei Android müssen Test-Accounts die App aus dem Play Store (Internal Track) installieren, damit Billing funktioniert.
- Prüfe logcat/Xcode auf Abrechnungsfehler, wenn du auf einem Gerät testest.
Abonnement-Status ist fehlerhaft
- Nutze
getPurchases()um Store-Daten mit deinem lokalen Entitlement-Cache zu vergleichen. - Frage unter Android immer die Google Play Developer API mit der
purchaseTokenab, um Ablaufdaten oder den Erstattungsstatus zu erhalten. - Prüfe unter iOS
isActive/expirationDateund validiere Receipts, um Erstattungen oder Widerrufe zu erkennen.
Weiter mit Getting Started
Abschnitt „Weiter mit Getting Started“Wenn Sie ... verwenden Erste Schritte um die Store-Freigabe und Distribution zu planen, verknüpfe es mit Mit @capgo/native-purchases für die native Funktion bei der Nutzung von @capgo/native-purchases, @capgo/capacitor-in-app-review für die Implementierungsdetails in @capgo/capacitor-in-app-review, @capgo/capacitor-in-app-review verwenden für die native Funktion beim Verwenden von @capgo/capacitor-in-app-review, @capgo/capacitor-native-market für die Implementierungsdetails in @capgo/capacitor-native-market, und Mit @capgo/capacitor-native-market für die native Funktionalität in der Verwendung von @capgo/capacitor-native-market.