-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathllms-full.txt
More file actions
688 lines (526 loc) · 18.3 KB
/
llms-full.txt
File metadata and controls
688 lines (526 loc) · 18.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
# OpenIAP Complete Reference
> OpenIAP: Unified cross-platform in-app purchase SDK
> Documentation: https://openiap.dev
> Quick Reference: https://openiap.dev/llms.txt
> GitHub: https://github.com/hyodotdev/openiap
## Table of Contents
1. Overview
2. Installation
3. Core API Reference
4. iOS-Specific APIs
5. Android-Specific APIs
6. Types & Data Structures
7. Events
8. Error Handling
9. Platform Usage Examples
10. Naming Conventions
---
# 1. Overview
OpenIAP is a standardized protocol for in-app purchases across all platforms.
One specification, consistent APIs, platform-specific optimizations.
**Supported Platforms:**
- React Native (react-native-iap) — npm
- Expo (expo-iap) — npm
- Flutter (flutter_inapp_purchase) — pub.dev
- Godot (godot-iap) — Godot Asset Library
- Kotlin Multiplatform (kmp-iap) — Maven Central
- iOS Native (openiap-apple) — SPM / CocoaPods
- Android Native (openiap-google) — Maven Central
**Current Versions:**
- react-native-iap: 14.7.20
- expo-iap: 3.4.13
- flutter_inapp_purchase: 8.2.10
- godot-iap: 1.2.9
- kmp-iap: 1.3.8
- openiap-apple: 1.3.15
- openiap-google: 1.3.28
---
# 2. Installation
## React Native
```bash
npm install react-native-iap
# or
yarn add react-native-iap
```
- iOS: StoreKit 2, requires iOS 15.0+
- Android: Google Play Billing 8.0+, compileSdkVersion 34+
- Uses Nitro Modules bridge
## Expo
```bash
npx expo install expo-iap
```
- Works with managed and bare workflows
- iOS: Set `"ios": { "deploymentTarget": "15.0" }` in app.json
- Android: Google Play Billing 8.0+
## Flutter
```bash
flutter pub add flutter_inapp_purchase
```
- iOS: Requires iOS 15.0+
- Android: minSdkVersion 21+
## Godot
- Download from Godot Asset Library or GitHub Release
- Extract to `addons/godot-iap/`
- Enable in Project Settings → Plugins
- Requires Godot 4.x
## Kotlin Multiplatform
```kotlin
// build.gradle.kts
dependencies {
implementation("io.github.hyochan.kmpiap:library:1.3.8")
}
```
## iOS Native
```swift
// Swift Package Manager
.package(url: "https://github.com/hyodotdev/openiap.git", from: "1.3.15")
```
```ruby
# CocoaPods
pod 'openiap', '~> 1.3'
```
## Android Native
```kotlin
implementation("io.github.hyochan.openiap:openiap-google:1.3.28")
```
---
# 3. Core API Reference
## Connection Management
### initConnection(config?: InitConnectionConfig): Promise<boolean>
Initialize connection to store service. Must be called before any IAP operations.
Parameters:
- config.alternativeBillingAndroid?: 'none' | 'user-choice' | 'alternative-only'
- 'none': Standard Google Play (default)
- 'user-choice': User can select billing method
- 'alternative-only': Alternative billing only
Returns: boolean indicating success
### endConnection(): Promise<boolean>
Close store service connection. Call on app close or component unmount.
---
## Product Management
### fetchProducts(params: ProductRequest): Promise<Product[]>
Retrieve product details from the store.
Parameters:
- skus: string[] — Product IDs to fetch
- type?: 'inapp' | 'subs' | 'all' (defaults to 'inapp')
Returns: Product[] with platform-specific fields
### getAvailablePurchases(options?: PurchaseOptions): Promise<Purchase[]>
Get user's unfinished purchases and active subscriptions.
Parameters (optional):
- alsoPublishToEventListenerIOS?: boolean
- onlyIncludeActiveItemsIOS?: boolean
---
## Purchase Management
### requestPurchase(props: RequestPurchaseProps): Promise<Purchase | void>
Initiate purchase flow. Event-based — results delivered via purchaseUpdatedListener.
Parameters:
- request: { apple: { sku: string }, google: { skus: string[] } }
- type: 'inapp' | 'subs'
### finishTransaction(purchase: Purchase, isConsumable?: boolean): Promise<void>
Complete purchase transaction. Must be called after receipt verification.
Parameters:
- purchase: Purchase object from event listener
- isConsumable?: boolean (default false)
- true: Coins, gems (can be repurchased)
- false: Premium unlocks, subscriptions
CRITICAL: Android purchases must be acknowledged within 3 days or are auto-refunded.
### restorePurchases(): Promise<void>
Restore completed transactions. Fires purchaseUpdatedListener for each restored purchase.
### getStorefront(): Promise<string>
Get user's storefront country code (ISO 3166-1 alpha-2, e.g., "US", "JP").
---
## Subscription Management
### getActiveSubscriptions(subscriptionIds?: string[]): Promise<ActiveSubscription[]>
Get all active subscriptions with renewal info. Optional filter by IDs.
### hasActiveSubscriptions(subscriptionIds?: string[]): Promise<boolean>
Quick check if user has any active subscriptions.
### deepLinkToSubscriptions(options: DeepLinkOptions): Promise<void>
Open native subscription management UI.
Parameters:
- skuAndroid: string (required on Android)
- packageNameAndroid: string (required on Android)
---
# 4. iOS-Specific APIs
## Transaction Management
- `clearTransactionIOS()` — Clear pending transactions from queue
- `getPendingTransactionsIOS()` — Retrieve all pending transactions
- `syncIOS()` — Force StoreKit sync (iOS 15+)
## Subscription
- `subscriptionStatusIOS(groupID: string)` — Detailed subscription status
- `showManageSubscriptionsIOS()` — In-app subscription management UI
- `isEligibleForIntroOfferIOS(groupID: string)` — Check intro offer eligibility
## Transaction Details
- `currentEntitlementIOS(sku: string)` — Current StoreKit 2 entitlement
- `latestTransactionIOS(sku: string)` — Most recent transaction
- `isTransactionVerifiedIOS(sku: string)` — Verify transaction signature
- `getTransactionJwsIOS(sku: string)` — JWS for server validation
- `getReceiptDataIOS()` — Base64-encoded receipt (legacy)
## Refunds & Redemption
- `beginRefundRequestIOS(sku: string)` — Initiate refund request
- `presentCodeRedemptionSheetIOS()` — Show promo code redemption
- `getAppTransactionIOS()` — Fetch app transaction (iOS 16+)
## External Purchase (iOS 17.4+)
- `showExternalPurchaseNoticeIOS(token: string)` — Show external purchase notice
- `getExternalPurchaseCustomLinkIOS(type: TokenType)` — Get external purchase token
---
# 5. Android-Specific APIs
## Purchase Acknowledgment
- `acknowledgePurchaseAndroid(purchaseToken: string)` — Acknowledge non-consumable/subscription
- `consumePurchaseAndroid(purchaseToken: string)` — Consume consumable purchase (auto-acknowledges)
## Alternative Billing Flow (3-step)
1. `checkAlternativeBillingAvailabilityAndroid()` — Check availability
2. `showAlternativeBillingDialogAndroid()` — Show user consent dialog
3. `createAlternativeBillingTokenAndroid()` — Create token for Google Play reporting
## Billing Programs
- `isBillingProgramAvailableAsync(program: BillingProgramAndroid)` — Check program availability
- `createBillingProgramReportingDetailsAsync(program: BillingProgramAndroid)` — Get reporting details
---
# 6. Types & Data Structures
## Purchase
### Common Fields
- id: string — Purchase identifier
- productId: string — Product SKU
- ids?: string[] — Array of SKUs for bundled purchases
- transactionDate: number — Epoch milliseconds
- purchaseToken: string — JWS (iOS) or Play token (Android)
- store: 'apple' | 'google' | 'horizon'
- quantity: number
- purchaseState: PurchaseState
- isAutoRenewing: boolean
- currentPlanId: string
### PurchaseIOS Additional Fields
- quantityIOS: number
- originalTransactionDateIOS: number
- originalTransactionIdentifierIOS: string
- appAccountToken: string
- expirationDateIOS: number
- webOrderLineItemIdIOS: string
- environmentIOS: 'Sandbox' | 'Production'
- storefrontCountryCodeIOS: string
### PurchaseAndroid Additional Fields
- orderId: string
- packageName: string
- purchaseTime: number
- purchaseState: 'pending' | 'purchased' | 'unknown'
- autoRenewingAndroid: boolean
- acknowledgementState: 'unacknowledged' | 'acknowledged'
- obfuscatedAccountIdAndroid: string
- obfuscatedProfileIdAndroid: string
## Product
### Common Fields
- id: string — SKU
- title: string — Display name
- description: string — Full description
- localizedPrice: string — Formatted price (e.g., "$9.99")
- priceAmount: number — Numeric price value
- currency: string — ISO 4217 currency code
- type: ProductType ('inapp' | 'subs')
- platform: 'ios' | 'android'
### Subscription Product (extends Product)
- subscriptionPeriod: string — Duration (e.g., "P1M" = 1 month)
- introductoryPrice?: string
- introductoryPriceAmount?: number
- introductoryPricePeriod?: string
- introductoryPriceNumberOfPeriods?: number
- introductoryPaymentMode?: PaymentMode
- freeTrialPeriod?: string
### ActiveSubscription
- productId: string
- isActive: boolean
- expirationDateIOS: number
- autoRenewingAndroid: boolean
- transactionId: string
- purchaseToken: string
- transactionDate: number
- basePlanIdAndroid: string
- currentPlanId: string
- renewalInfoIOS: { willAutoRenew, pendingUpgradeProductId, renewalDate, expirationReason }
## Enums
### ProductType
- InApp — One-time purchase
- Subs — Subscription
### ProductQueryType
- InApp — Fetch in-app products only
- Subs — Fetch subscriptions only
- All — Fetch all products
### PurchaseState
- Pending
- Purchased
- Unknown
### IapStore
- unknown, apple, google, horizon
### PaymentMode
- FreeTrial, PayAsYouGo, PayUpFront
### SubscriptionPeriodUnit
- Day, Week, Month, Year
### BillingProgramAndroid
- UserChoice, ExternalContent, ExternalOffers, ExternalPayments
---
# 7. Events
## Event Types
### purchaseUpdatedListener(callback: (purchase: Purchase) => void): Subscription
Fires when purchase succeeds or pending purchase completes.
Handle: Validate receipt → Grant entitlement → finishTransaction()
### purchaseErrorListener(callback: (error: PurchaseError) => void): Subscription
Fires on purchase failure or user cancellation.
Handle based on error code.
### promotedProductIOS(callback: (productId: string) => void): Subscription
iOS promoted product action (iOS 11+). Triggered from App Store promotions.
### userChoiceBillingAndroid(callback: (details) => void): Subscription
User selected alternative billing method (Android 7.0+).
### developerProvidedBillingAndroid(callback: (details) => void): Subscription
User selected developer-provided billing (Android 8.3.0+).
---
# 8. Error Handling
## Error Structure
```
PurchaseError {
code: ErrorCode // Enum value (kebab-case string)
message: string // Human-readable message
productId?: string // Related product
responseCode?: number // Platform-specific code
debugMessage?: string // Additional debug info
}
```
## Error Codes (ErrorCode enum)
### User Action Errors
- user-cancelled — User cancelled purchase flow
- user-error — User account error
- deferred-payment — Payment deferred (family approval)
- interrupted — Purchase flow interrupted
### Product Errors
- item-unavailable — Product not available in store
- sku-not-found — SKU not found
- sku-offer-mismatch — SKU offer ID mismatch
- query-product — Failed to query product details
- already-owned — Item already owned
- item-not-owned — Item not owned
### Network & Service Errors
- network-error — No network connection
- service-error — Store service error
- remote-error — Remote server error
- init-connection — Failed to initialize connection
- service-disconnected — Store service disconnected
- connection-closed — Connection closed
- iap-not-available — IAP service not available
- billing-unavailable — Billing service unavailable
- feature-not-supported — Feature not supported
- sync-error — Synchronization error
### Validation Errors
- purchase-verification-failed — Purchase verification failed
- purchase-verification-finished — Verification already completed
- purchase-verification-finish-failed — Failed to finish verification
- transaction-validation-failed — Transaction validation failed
- empty-sku-list — Empty SKU list provided
- duplicate-purchase — Duplicate purchase update detected (use restorePurchases to recover)
### General
- not-prepared — Store not initialized
- developer-error — Invalid API usage
- unknown — Unexpected error
## Retry Strategy (Built-in)
- NetworkError: Exponential backoff (2^n seconds)
- ServiceError: Linear backoff (n * 5 seconds)
- RemoteError: Fixed delay (10 seconds)
- ConnectionClosed: Reinitialize and retry
- UserCancelled, AlreadyOwned: No retry
## Helper Functions
- `isUserCancelledError(error)` — Check if user cancellation
- `getUserFriendlyErrorMessage(error)` — Get display-safe message
---
# 9. Platform Usage Examples
## TypeScript (React Native)
```typescript
import {
initConnection,
endConnection,
fetchProducts,
requestPurchase,
finishTransaction,
purchaseUpdatedListener,
purchaseErrorListener,
ErrorCode,
isUserCancelledError,
} from 'react-native-iap';
// Initialize
await initConnection();
// Fetch products
const products = await fetchProducts({ skus: ['premium', 'coins_100'] });
// Listen for events
const purchaseSub = purchaseUpdatedListener(async (purchase) => {
// Validate on server, then:
await finishTransaction(purchase, purchase.productId === 'coins_100');
});
const errorSub = purchaseErrorListener((error) => {
if (isUserCancelledError(error)) return;
console.error(error.code, error.message);
});
// Purchase
await requestPurchase({
request: { apple: { sku: 'premium' }, google: { skus: ['premium'] } },
type: 'inapp',
});
// Cleanup
purchaseSub.remove();
errorSub.remove();
await endConnection();
```
## TypeScript (React Native — useIAP Hook)
```typescript
import { useIAP, ErrorCode } from 'react-native-iap';
function PurchaseScreen() {
const {
products,
fetchProducts,
requestPurchase,
activeSubscriptions,
getActiveSubscriptions,
} = useIAP({
onPurchaseSuccess: (purchase) => {
// Validate and finish
},
onPurchaseError: (error) => {
if (error.code === ErrorCode.UserCancelled) return;
Alert.alert('Error', error.message);
},
});
useEffect(() => {
fetchProducts({ skus: ['premium'] });
}, []);
}
```
## TypeScript (Expo)
```typescript
import { useIAP, ErrorCode } from 'expo-iap';
// Same API as react-native-iap useIAP hook
const { products, fetchProducts, requestPurchase } = useIAP({
onPurchaseSuccess: (purchase) => { /* ... */ },
onPurchaseError: (error) => { /* ... */ },
});
```
## Dart (Flutter)
```dart
import 'package:flutter_inapp_purchase/flutter_inapp_purchase.dart';
final iap = FlutterInappPurchase.instance;
// Initialize
await iap.initConnection();
// Fetch products
final products = await iap.fetchProducts<Product>(
skus: ['premium', 'coins_100'],
type: ProductQueryType.InApp,
);
// Fetch subscriptions
final subs = await iap.fetchProducts<ProductSubscription>(
skus: ['monthly_pro'],
type: ProductQueryType.Subs,
);
// Listen for events
iap.purchaseUpdatedStream.listen((purchase) async {
await iap.finishTransaction(purchase, isConsumable: true);
});
iap.purchaseErrorStream.listen((error) {
print('${error.code}: ${error.message}');
});
// Purchase
await iap.requestPurchase(sku: 'premium');
// Cleanup
await iap.endConnection();
```
## GDScript (Godot)
```gdscript
const Types = preload("res://addons/godot-iap/types.gd")
func _ready():
GodotIapPlugin.purchase_updated.connect(_on_purchase_updated)
GodotIapPlugin.purchase_error.connect(_on_purchase_error)
GodotIapPlugin.init_connection()
func _load_products():
var request = Types.ProductRequest.new()
request.skus = ["premium", "coins_100"]
request.type = Types.ProductQueryType.InApp
var products = GodotIapPlugin.fetch_products(request)
func _purchase(sku: String):
var props = Types.RequestPurchaseProps.new()
props.sku = sku
GodotIapPlugin.request_purchase(props)
func _on_purchase_updated(purchase):
GodotIapPlugin.finish_transaction(purchase, true)
func _on_purchase_error(error):
print("Error: ", error.code, " - ", error.message)
```
## Kotlin (KMP)
```kotlin
import io.github.hyochan.kmpiap.KmpIAP
val kmpIAP = KmpIAP()
// Initialize
kmpIAP.initConnection()
// Fetch products
val products = kmpIAP.fetchProducts(skus = listOf("premium", "coins_100"))
// Listen for events
kmpIAP.purchaseUpdatedListener.collect { purchase ->
// Validate receipt on server
kmpIAP.finishTransaction(purchase = purchase, isConsumable = true)
}
kmpIAP.purchaseErrorListener.collect { error ->
println("Error: ${error.code} - ${error.message}")
}
// Purchase
kmpIAP.requestPurchase(sku = "premium")
// Cleanup
kmpIAP.endConnection()
```
## Swift (iOS Native)
```swift
import OpenIAP
let store = OpenIapStore()
// Initialize
try await store.initConnection()
// Fetch products
let products = try await store.fetchProducts(skus: ["premium"])
// Purchase
let result = try await store.requestPurchase(sku: "premium")
// Finish
try await store.finishTransaction(purchase: result)
```
## Kotlin (Android Native)
```kotlin
import dev.hyo.openiap.OpenIapStore
val store = OpenIapStore(context)
// Initialize
store.initConnection()
// Fetch products
val products = store.fetchProducts(skus = listOf("premium"))
// Purchase
store.requestPurchase(activity = this, sku = "premium")
// Listen
store.purchaseUpdatedFlow.collect { purchase ->
store.finishTransaction(purchase)
}
```
---
# 10. Naming Conventions
## Function Naming
- Cross-platform: No suffix (`initConnection`, `fetchProducts`)
- iOS-only: `IOS` suffix (`getStorefrontIOS`, `clearTransactionIOS`)
- Android-only: `Android` suffix (`acknowledgePurchaseAndroid`)
## Type Naming
- iOS types: `IOS` suffix (`PurchaseIOS`, `ProductIOS`)
- Android types: `Android` suffix (`PurchaseAndroid`, `ProductAndroid`)
- IAP prefix: Use `Iap` not `IAP` when followed by other words (`IapPurchase`)
## Field Naming
- ID fields: Always `Id` not `ID` (`productId`, `transactionId`)
- Platform fields: Suffix with `IOS` or `Android` (`quantityIOS`, `orderIdAndroid`)
## Error Codes
- Always kebab-case: `user-cancelled`, `network-error`
- Use `ErrorCode` enum, never string literals
## Commit Messages
- With tag: `feat: add new feature` (lowercase after tag)
- Without tag: `Add new feature` (uppercase first letter)
- Types: feat, fix, docs, style, refactor, perf, test, chore
---
## Links
- Documentation: https://openiap.dev
- GitHub: https://github.com/hyodotdev/openiap
- APIs: https://openiap.dev/docs/apis
- Types: https://openiap.dev/docs/types
- Events: https://openiap.dev/docs/events
- Errors: https://openiap.dev/docs/errors
- Discussions: https://github.com/hyodotdev/openiap/discussions