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 die Capgo Skills mit dem folgenden Befehl deinem KI-Tool hinzu:
npx skills add https://github.com/Cap-go/capgo-skills --skill capacitor-pluginsNutze dann 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 bevorzugst, 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 -
Billing-Support 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);}); -
Purchase- & Restore-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 Abos in App Store Connect.
- Nutze StoreKit Local Testing oder Sandbox-Tester für 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 Abos 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. Immer gesetzt auf 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 verfügbar ist. |
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 Ihrem User. Auf iOS muss es eine UUID sein; Android akzeptiert jeden obfuskatierten String bis zu 64 Zeichen. |
isConsumable | Android | Aufsetzen auf true um nach Gewährung des Entitlements bei Consumables Tokens automatisch zu verbrauchen. Standard ist false. |
Entitlement-Status prüfen
Abschnitt „Prüfen des Entitlement-Status“Nutzt 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 serverseitige Belegvalidierung. - Android:
isActive/expirationDatesind nicht befüllt; rufen Sie die Google Play Developer API mit dempurchaseTokenfür den verbindlichen Status auf.purchaseStatemussPURCHASEDundisAcknowledgedmusstrue.
API Kurzübersicht
Abschnitt „API Quick Reference“isBillingSupported()– Verfügbarkeit von StoreKit / Google Play prüfen.getProduct()/getProducts()– Preise, lokalisierte Titel, Beschreibungen, Intro-Angebote und unterstützte iOS-Preisbedingungen abrufen.purchaseProduct()– StoreKit 2 oder Billing-Client-Kaufprozess starten (inkl. iOS Monthly Commitment Billing Plans).restorePurchases()– Historische Käufe wiederherstellen und mit dem aktuellen Gerät synchronisieren.getPurchases()– Alle iOS-Transaktionen oder Play Billing-Käufe auflisten.manageSubscriptions()– Native UI zur Abonnementverwaltung öffnen.addListener('transactionUpdated')– Ausstehende StoreKit 2 Transaktionen beim App-Start verarbeiten (nur iOS).
Best Practices
Abschnitt mit dem Titel „Best Practices“- Store-Preise anzeigen – Apple schreibt die Anzeige vor
product.titleundproduct.priceString; niemals hardcoden. - Nutzt
appAccountToken– generiere deterministisch eine UUID (v5) aus deiner User-ID, um Käufe mit Accounts zu verknüpfen. - Serverseitig validieren – 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.
- Restore & Verwaltung anbieten – füge UI-Buttons hinzu, die mit
restorePurchases()undmanageSubscriptions().
Nächste Schritte mit Revenue
Abschnitt „Revenue next steps“Sobald der Kaufprozess 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 freigegeben (App Store) oder aktiviert (Google Play) sind.
- Warte nach dem Anlegen der Produkte einige Stunden; die Stores übernehmen sie 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 über den Play Store (interner Test-Track) installieren, damit Billing funktioniert.
- Prüfe logcat/Xcode auf Abrechnungsfehler bei der Ausführung auf dem Gerät.
Abonnementstatus ist fehlerhaft
- Nutzt
getPurchases()um Store-Daten mit deinem lokalen Entitlement-Cache zu vergleichen. - Frage unter Android immer den Google Play Developer API mit dem
purchaseTokenab, um Ablaufdaten oder den Erstattungsstatus zu erhalten. - Prüfe unter iOS
isActive/expirationDateund validiere Receipts, um Erstattungen oder Widerrufe zu erkennen.
Weiter geht's nach Getting Started
Abschnitt: „Weiter geht’s mit Getting Started“Wenn du es nutzt Erste Schritte um Store-Zulassung und Distribution zu planen, verknüpfen Sie es mit @capgo/native-purchases verwenden für die native Funktionalität 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 nutzen für die native Funktion bei der Nutzung von @capgo/capacitor-in-app-review, @capgo/capacitor-native-market für das Implementierungsdetail in @capgo/capacitor-native-market, und @capgo/capacitor-native-market nutzen für die native Funktionalität bei der Nutzung von @capgo/capacitor-native-market.