expo-iap 1.0.3 → 2.0.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/.eslintrc.js +9 -0
  2. package/.prettierrc.js +9 -0
  3. package/.swiftlint.yml +10 -0
  4. package/README.md +28 -21
  5. package/android/build.gradle +34 -72
  6. package/android/src/main/AndroidManifest.xml +1 -4
  7. package/android/src/main/java/expo/modules/iap/ExpoIapModule.kt +535 -0
  8. package/android/src/main/java/expo/modules/iap/MissingCurrentActivityException.kt +6 -0
  9. package/android/src/main/java/expo/modules/iap/PlayUtils.kt +124 -0
  10. package/build/ExpoIap.types.d.ts +89 -0
  11. package/build/ExpoIap.types.d.ts.map +1 -0
  12. package/build/ExpoIap.types.js +59 -0
  13. package/build/ExpoIap.types.js.map +1 -0
  14. package/build/ExpoIapModule.d.ts +3 -0
  15. package/build/ExpoIapModule.d.ts.map +1 -0
  16. package/build/ExpoIapModule.js +5 -0
  17. package/build/ExpoIapModule.js.map +1 -0
  18. package/build/index.d.ts +38 -0
  19. package/build/index.d.ts.map +1 -0
  20. package/build/index.js +202 -0
  21. package/build/index.js.map +1 -0
  22. package/build/modules/android.d.ts +40 -0
  23. package/build/modules/android.d.ts.map +1 -0
  24. package/build/modules/android.js +54 -0
  25. package/build/modules/android.js.map +1 -0
  26. package/build/modules/ios.d.ts +41 -0
  27. package/build/modules/ios.d.ts.map +1 -0
  28. package/build/modules/ios.js +44 -0
  29. package/build/modules/ios.js.map +1 -0
  30. package/build/types/ExpoIapAndroid.types.d.ts +113 -0
  31. package/build/types/ExpoIapAndroid.types.d.ts.map +1 -0
  32. package/build/types/ExpoIapAndroid.types.js +23 -0
  33. package/build/types/ExpoIapAndroid.types.js.map +1 -0
  34. package/build/types/ExpoIapIos.types.d.ts +122 -0
  35. package/build/types/ExpoIapIos.types.d.ts.map +1 -0
  36. package/build/types/ExpoIapIos.types.js +2 -0
  37. package/build/types/ExpoIapIos.types.js.map +1 -0
  38. package/bun.lockb +0 -0
  39. package/expo-module.config.json +4 -8
  40. package/ios/ExpoIap.podspec +27 -0
  41. package/ios/ExpoIapModule.swift +498 -0
  42. package/ios/ProductStore.swift +27 -0
  43. package/ios/Types.swift +54 -0
  44. package/package.json +33 -62
  45. package/src/ExpoIap.types.ts +125 -0
  46. package/src/ExpoIapModule.ts +5 -0
  47. package/src/index.ts +397 -0
  48. package/src/modules/android.ts +89 -0
  49. package/src/modules/ios.ts +81 -0
  50. package/src/types/ExpoIapAndroid.types.ts +123 -0
  51. package/src/types/ExpoIapIos.types.ts +141 -0
  52. package/tsconfig.json +9 -0
  53. package/.editorconfig +0 -10
  54. package/.flowconfig +0 -11
  55. package/.monolinterrc +0 -3
  56. package/.yarn/install-state.gz +0 -0
  57. package/.yarn/releases/yarn-3.1.1.cjs +0 -768
  58. package/.yarnrc.yml +0 -3
  59. package/LICENSE +0 -21
  60. package/RNIap.podspec +0 -18
  61. package/android/gradle/wrapper/gradle-wrapper.jar +0 -0
  62. package/android/gradle/wrapper/gradle-wrapper.properties +0 -6
  63. package/android/gradle.properties +0 -2
  64. package/android/gradlew +0 -160
  65. package/android/gradlew.bat +0 -90
  66. package/android/libs/in-app-purchasing-2.0.76.jar +0 -0
  67. package/android/src/amazon/AndroidManifest.xml +0 -12
  68. package/android/src/amazon/java/com/dooboolab/RNIap/RNIapAmazonListener.kt +0 -356
  69. package/android/src/amazon/java/com/dooboolab/RNIap/RNIapAmazonModule.kt +0 -128
  70. package/android/src/amazon/java/com/dooboolab/RNIap/RNIapPackage.kt +0 -20
  71. package/android/src/main/java/com/dooboolab/RNIap/DoobooUtils.kt +0 -180
  72. package/android/src/play/java/com/dooboolab/RNIap/PlayUtils.kt +0 -77
  73. package/android/src/play/java/com/dooboolab/RNIap/RNIapModule.kt +0 -698
  74. package/android/src/play/java/com/dooboolab/RNIap/RNIapPackage.kt +0 -20
  75. package/babel.config.js +0 -10
  76. package/index.d.ts +0 -3
  77. package/index.js +0 -3
  78. package/index.js.flow +0 -9
  79. package/ios/RNIap.xcodeproj/project.pbxproj +0 -370
  80. package/ios/RNIap.xcodeproj/xcshareddata/xcschemes/RNIap.xcscheme +0 -80
  81. package/ios/RNIapIos.m +0 -60
  82. package/ios/RNIapIos.swift +0 -932
  83. package/ios/RNIapQueue.swift +0 -35
  84. package/jest.config.js +0 -194
  85. package/src/__test__/iap.test.d.ts +0 -1
  86. package/src/__test__/iap.test.js +0 -59
  87. package/src/hooks/useIAP.d.ts +0 -21
  88. package/src/hooks/useIAP.js +0 -140
  89. package/src/hooks/withIAPContext.d.ts +0 -21
  90. package/src/hooks/withIAPContext.js +0 -142
  91. package/src/iap.d.ts +0 -197
  92. package/src/iap.js +0 -625
  93. package/src/index.d.ts +0 -4
  94. package/src/index.js +0 -4
  95. package/src/types/amazon.d.ts +0 -23
  96. package/src/types/amazon.js +0 -1
  97. package/src/types/android.d.ts +0 -47
  98. package/src/types/android.js +0 -22
  99. package/src/types/apple.d.ts +0 -424
  100. package/src/types/apple.js +0 -165
  101. package/src/types/index.d.ts +0 -117
  102. package/src/types/index.js +0 -40
  103. package/test/mocks/react-native-modules.js +0 -14
@@ -1,932 +0,0 @@
1
- //
2
- // RNIapIos.swift
3
- //
4
- //
5
- // Created by Andres Aguilar on 9/8/21.
6
- //
7
- import React
8
- import StoreKit
9
-
10
- // Based on https://stackoverflow.com/a/40135192/570612
11
- extension Date {
12
- var millisecondsSince1970:Int64 {
13
- return Int64((self.timeIntervalSince1970 * 1000.0).rounded())
14
- }
15
-
16
- var millisecondsSince1970String:String {
17
- return String((self.timeIntervalSince1970 * 1000.0).rounded())
18
- }
19
-
20
- init(milliseconds:Int64) {
21
- self = Date(timeIntervalSince1970: TimeInterval(milliseconds) / 1000)
22
- }
23
- }
24
-
25
- extension SKProductsRequest {
26
- var key:String{
27
- return String(self.hashValue)
28
- }
29
- }
30
- typealias IapPromise = (RCTPromiseResolveBlock,RCTPromiseRejectBlock)
31
- @objc(RNIapIos)
32
- class RNIapIos: RCTEventEmitter, SKRequestDelegate, SKPaymentTransactionObserver, SKProductsRequestDelegate {
33
- private var promisesByKey: [String: [IapPromise]]
34
- private var myQueue: DispatchQueue
35
- private var hasListeners = false
36
- private var pendingTransactionWithAutoFinish = false
37
- private var receiptBlock: ((Data?, Error?) -> Void)? // Block to handle request the receipt async from delegate
38
- private var validProducts: [SKProduct]
39
- private var promotedPayment: SKPayment? = nil
40
- private var promotedProduct: SKProduct? = nil
41
- private var productsRequest: SKProductsRequest? = nil
42
- private var countPendingTransaction: Int?
43
-
44
- override init() {
45
- promisesByKey = [String : [IapPromise]]()
46
- pendingTransactionWithAutoFinish = false
47
- myQueue = DispatchQueue(label: "reject")
48
- validProducts = [SKProduct]()
49
- super.init()
50
- }
51
-
52
- deinit {
53
- SKPaymentQueue.default().remove(self)
54
- }
55
-
56
- override class func requiresMainQueueSetup() -> Bool {
57
- return true
58
- }
59
-
60
- func flushUnheardEvents() {
61
- paymentQueue(SKPaymentQueue.default(), updatedTransactions: SKPaymentQueue.default().transactions)
62
- }
63
-
64
- override func startObserving() {
65
- hasListeners = true
66
- flushUnheardEvents()
67
- }
68
-
69
- override func stopObserving() {
70
- hasListeners = false
71
- }
72
-
73
- override func addListener(_ eventName: String?) {
74
- super.addListener(eventName)
75
-
76
- if (eventName == "iap-promoted-product") && promotedPayment != nil {
77
- sendEvent(withName: "iap-promoted-product", body: promotedPayment?.productIdentifier)
78
- }
79
- }
80
-
81
- func addPromise(forKey key: String, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) {
82
- var promises:[IapPromise]? = promisesByKey[key]
83
-
84
- if promises == nil {
85
- promises = []
86
- }
87
-
88
- promises?.append((resolve, reject))
89
- promisesByKey[key] = promises
90
- }
91
-
92
- func resolvePromises(forKey key: String?, value: Any?) {
93
- let promises:[IapPromise]? = promisesByKey[key ?? ""]
94
-
95
- if let promises = promises {
96
- for tuple in promises {
97
- let resolveBlck = tuple.0
98
- resolveBlck(value)
99
- }
100
- promisesByKey[key ?? ""] = nil
101
- }
102
- }
103
-
104
- func rejectPromises(forKey key: String, code: String?, message: String?, error: Error?) {
105
- let promises = promisesByKey[key]
106
-
107
- if let promises = promises {
108
- for tuple in promises {
109
- let reject = tuple.1
110
- reject(code, message, error)
111
- }
112
- promisesByKey[key]=nil
113
- }
114
- }
115
-
116
- func paymentQueue(_ queue: SKPaymentQueue, shouldAddStorePayment payment: SKPayment, for product: SKProduct) -> Bool {
117
- promotedProduct = product
118
- promotedPayment = payment
119
-
120
- if hasListeners {
121
- sendEvent(withName: "iap-promoted-product", body: product.productIdentifier)
122
- }
123
- return false
124
- }
125
-
126
- override func supportedEvents() -> [String]? {
127
- return ["iap-promoted-product", "purchase-updated", "purchase-error"]
128
- }
129
-
130
-
131
- @objc public func initConnection(
132
- _ resolve: @escaping RCTPromiseResolveBlock = { _ in },
133
- reject: @escaping RCTPromiseRejectBlock = { _, _, _ in }
134
- ) {
135
- SKPaymentQueue.default().remove(RNIapQueue.shared)
136
- if let queue = RNIapQueue.shared.queue, let payment = RNIapQueue.shared.payment, let product = RNIapQueue.shared.product {
137
- let val = paymentQueue(queue, shouldAddStorePayment: payment,for: product)
138
- print("Promoted product response \(val)")
139
- }
140
- SKPaymentQueue.default().add(self)
141
- let canMakePayments = SKPaymentQueue.canMakePayments()
142
- resolve(NSNumber(value: canMakePayments))
143
- }
144
-
145
- @objc public func endConnection(
146
- _ resolve: @escaping RCTPromiseResolveBlock = { _ in },
147
- reject: @escaping RCTPromiseRejectBlock = { _, _, _ in }
148
- ) {
149
- SKPaymentQueue.default().remove(self)
150
- resolve(nil)
151
- }
152
-
153
- @objc public func getItems(
154
- _ skus: [String],
155
- resolve: @escaping RCTPromiseResolveBlock = { _ in },
156
- reject: @escaping RCTPromiseRejectBlock = { _, _, _ in }
157
- ) {
158
- let productIdentifiers = Set<AnyHashable>(skus)
159
- if let productIdentifiers = productIdentifiers as? Set<String> {
160
- productsRequest = SKProductsRequest(productIdentifiers: productIdentifiers)
161
- if let productsRequest = productsRequest {
162
- productsRequest.delegate = self
163
- let key: String = productsRequest.key
164
- addPromise(forKey: key, resolve: resolve, reject: reject)
165
- productsRequest.start()
166
- }
167
- }
168
- }
169
-
170
- @objc public func getAvailableItems(
171
- _ resolve: @escaping RCTPromiseResolveBlock = { _ in },
172
- reject: @escaping RCTPromiseRejectBlock = { _, _, _ in }
173
- ) {
174
- addPromise(forKey: "availableItems", resolve: resolve, reject: reject)
175
- SKPaymentQueue.default().restoreCompletedTransactions()
176
- }
177
-
178
-
179
- @objc public func buyProduct(
180
- _ sku:String,
181
- andDangerouslyFinishTransactionAutomatically: Bool,
182
- resolve: @escaping RCTPromiseResolveBlock = { _ in },
183
- reject: @escaping RCTPromiseRejectBlock = { _, _, _ in }
184
- ) {
185
- pendingTransactionWithAutoFinish = andDangerouslyFinishTransactionAutomatically
186
- var product: SKProduct?
187
- let lockQueue = DispatchQueue(label: "validProducts")
188
- lockQueue.sync {
189
- for p in validProducts {
190
- if sku == p.productIdentifier {
191
- product = p
192
- break
193
- }
194
- }
195
- }
196
- if let prod = product {
197
- addPromise(forKey: prod.productIdentifier, resolve: resolve, reject: reject)
198
-
199
- let payment = SKMutablePayment(product: prod)
200
- SKPaymentQueue.default().add(payment)
201
- } else{
202
- if hasListeners {
203
- let err = [
204
- "debugMessage" : "Invalid product ID.",
205
- "code" : "E_DEVELOPER_ERROR",
206
- "message" : "Invalid product ID.",
207
- "productId" : sku
208
- ]
209
- sendEvent(withName: "purchase-error", body: err)
210
- }
211
- reject("E_DEVELOPER_ERROR", "Invalid product ID.", nil)
212
- }
213
- }
214
-
215
-
216
- @objc public func buyProductWithOffer(
217
- _ sku: String,
218
- usernameHash: String,
219
- discountOffer: Dictionary<String,String>,
220
- resolve: @escaping RCTPromiseResolveBlock = { _ in },
221
- reject: @escaping RCTPromiseRejectBlock = { _, _, _ in }
222
- ) {
223
- var product: SKProduct?
224
-
225
- let lockQueue = DispatchQueue(label: "validProducts")
226
- lockQueue.sync {
227
- for p in validProducts {
228
- if sku == p.productIdentifier {
229
- product = p
230
- break
231
- }
232
- }
233
- }
234
-
235
- if let prod = product {
236
- addPromise(forKey: prod.productIdentifier, resolve: resolve, reject: reject)
237
-
238
- let payment: SKMutablePayment = SKMutablePayment(product: prod)
239
-
240
- if #available(iOS 12.2, tvOS 12.2, *) {
241
- let discount: SKPaymentDiscount = SKPaymentDiscount(
242
- identifier: discountOffer["identifier"]!,
243
- keyIdentifier: discountOffer["keyIdentifier"]!,
244
- nonce: UUID(uuidString: discountOffer["nonce"]!)!,
245
- signature: discountOffer["signature"]!,
246
- timestamp: NSNumber(value: Int(discountOffer["timestamp"]!)!))
247
- payment.paymentDiscount = discount
248
- }
249
- payment.applicationUsername = usernameHash
250
- SKPaymentQueue.default().add(payment)
251
- }else {
252
- if hasListeners {
253
- let err = [
254
- "debugMessage" : "Invalid product ID.",
255
- "message" : "Invalid product ID.",
256
- "code" : "E_DEVELOPER_ERROR",
257
- "productId" : sku
258
- ]
259
- sendEvent(withName: "purchase-error", body: err)
260
- }
261
- reject("E_DEVELOPER_ERROR", "Invalid product ID.", nil)
262
- }
263
-
264
- }
265
-
266
-
267
-
268
- @objc public func buyProductWithQuantityIOS(
269
- _ sku: String,
270
- quantity: Int,
271
- resolve: @escaping RCTPromiseResolveBlock = { _ in },
272
- reject: @escaping RCTPromiseRejectBlock = { _, _, _ in }
273
- ) {
274
-
275
- print("\n\n\n buyProductWithQuantityIOS \n\n.")
276
- var product: SKProduct?
277
- let lockQueue = DispatchQueue(label: "validProducts")
278
- lockQueue.sync {
279
- for p in validProducts {
280
- if sku == p.productIdentifier {
281
- product = p
282
- break
283
- }
284
- }
285
- }
286
-
287
- if let prod = product {
288
- let payment = SKMutablePayment(product: prod)
289
- payment.quantity = quantity
290
- SKPaymentQueue.default().add(payment)
291
- } else {
292
- if hasListeners {
293
- let err = [
294
- "debugMessage" : "Invalid product ID.",
295
- "message" : "Invalid product ID.",
296
- "code" : "E_DEVELOPER_ERROR",
297
- "productId" : sku
298
- ]
299
- sendEvent(withName: "purchase-error", body: err)
300
- }
301
- reject("E_DEVELOPER_ERROR", "Invalid product ID.", nil)
302
- }
303
- }
304
-
305
-
306
- @objc public func clearTransaction(
307
- _ resolve: @escaping RCTPromiseResolveBlock = { _ in },
308
- reject: @escaping RCTPromiseRejectBlock = { _, _, _ in }
309
- ) {
310
-
311
- print("\n\n\n *** clear remaining Transactions. Call this before make a new transaction \n\n.")
312
-
313
- let pendingTrans = SKPaymentQueue.default().transactions
314
- let countPendingTransaction = pendingTrans.count
315
-
316
- if countPendingTransaction > 0 {
317
- addPromise(forKey: "cleaningTransactions", resolve: resolve, reject: reject)
318
- for transaction in pendingTrans {
319
- SKPaymentQueue.default().finishTransaction(transaction)
320
- }
321
- }
322
- resolve(nil)
323
-
324
- }
325
-
326
-
327
- @objc public func clearProducts(
328
- _ resolve: @escaping RCTPromiseResolveBlock = { _ in },
329
- reject: @escaping RCTPromiseRejectBlock = { _, _, _ in }
330
- ) {
331
- print("\n\n\n *** clear valid products. \n\n.")
332
- let lockQueue = DispatchQueue(label: "validProducts")
333
- lockQueue.sync {
334
- validProducts.removeAll()
335
- }
336
- resolve(nil)
337
- }
338
-
339
- @objc public func promotedProduct(
340
- _ resolve: @escaping RCTPromiseResolveBlock = { _ in },
341
- reject: @escaping RCTPromiseRejectBlock = { _, _, _ in }
342
- ) {
343
- print("\n\n\n *** get promoted product. \n\n.")
344
- resolve(promotedProduct )
345
- }
346
-
347
- @objc public func buyPromotedProduct(
348
- _ resolve: @escaping RCTPromiseResolveBlock = { _ in },
349
- reject: @escaping RCTPromiseRejectBlock = { _, _, _ in }
350
- ) {
351
- if let promoPayment = promotedPayment {
352
- print("\n\n\n *** buy promoted product. \n\n.")
353
- SKPaymentQueue.default().add(promoPayment)
354
- } else {
355
- reject("E_DEVELOPER_ERROR", "Invalid product ID.", nil)
356
- }
357
- }
358
-
359
-
360
-
361
- @objc public func requestReceipt(
362
- _ refresh: Bool,
363
- resolve: @escaping RCTPromiseResolveBlock = { _ in },
364
- reject: @escaping RCTPromiseRejectBlock = { _, _, _ in }
365
- ) {
366
- requestReceiptData(withBlock: refresh) { [self] receiptData, error in
367
- if error == nil {
368
- resolve(receiptData?.base64EncodedString(options: []))
369
- } else {
370
- reject(standardErrorCode(9), "Invalid receipt", nil)
371
- }
372
- }
373
- }
374
-
375
-
376
-
377
- @objc public func finishTransaction(
378
- _ transactionIdentifier: String,
379
- resolve: @escaping RCTPromiseResolveBlock = { _ in },
380
- reject: @escaping RCTPromiseRejectBlock = { _, _, _ in }
381
- ) {
382
- finishTransaction(withIdentifier: transactionIdentifier)
383
- resolve(nil)
384
- }
385
-
386
-
387
- @objc public func getPendingTransactions (
388
- _ resolve: @escaping RCTPromiseResolveBlock = { _ in },
389
- reject: @escaping RCTPromiseRejectBlock = { _, _, _ in }
390
- ) {
391
- requestReceiptData(withBlock: false) { receiptData, error in
392
- var output: [AnyHashable] = []
393
- if let receipt = receiptData {
394
- let transactions = SKPaymentQueue.default().transactions
395
-
396
- for item in transactions {
397
- let timestamp = item.transactionDate?.millisecondsSince1970 == nil ? nil : String(item.transactionDate!.millisecondsSince1970)
398
- let purchase = [
399
- "transactionDate" : timestamp,
400
- "transactionId" : item.transactionIdentifier,
401
- "productId" : item.payment.productIdentifier,
402
- "quantity" : "\(item.payment.quantity)",
403
- "transactionReceipt" : receipt.base64EncodedString(options: [])
404
- ]
405
- output.append(purchase)
406
-
407
- }
408
- }
409
- resolve(output)
410
- }
411
-
412
- }
413
-
414
- @objc public func presentCodeRedemptionSheet(
415
- _ resolve: @escaping RCTPromiseResolveBlock = { _ in },
416
- reject: @escaping RCTPromiseRejectBlock = { _, _, _ in }
417
- ) {
418
- #if !os(tvOS)
419
- if #available(iOS 14.0, tvOS 14.0, *) {
420
- SKPaymentQueue.default().presentCodeRedemptionSheet()
421
- resolve(nil)
422
- } else {
423
- reject(standardErrorCode(2), "This method only available above iOS 14", nil)
424
- }
425
- #else
426
- reject(standardErrorCode(2), "This method is not available on tvOS", nil)
427
- #endif
428
- }
429
-
430
-
431
- // StoreKitDelegate
432
- func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
433
- for prod in response.products {
434
- add(prod)
435
- }
436
- var items: [[String: Any?]] = [[:]]
437
-
438
-
439
- let lockQueue = DispatchQueue(label: "validProducts")
440
- lockQueue.sync {
441
- for product in validProducts {
442
- items.append(getProductObject(product))
443
- }
444
- }
445
-
446
- resolvePromises(forKey: request.key, value: items)
447
- }
448
- // Add to valid products from Apple server response. Allowing getProducts, getSubscriptions call several times.
449
- // Doesn't allow duplication. Replace new product.
450
- func add(_ aProd: SKProduct) {
451
- let lockQueue = DispatchQueue(label: "validProducts")
452
- lockQueue.sync {
453
- print("\n Add new object : \(aProd.productIdentifier)")
454
- var delTar = -1
455
- for k in 0..<validProducts.count {
456
- let cur = validProducts[k]
457
- if cur.productIdentifier == aProd.productIdentifier {
458
- delTar = k
459
- }
460
- }
461
- if delTar >= 0 {
462
- validProducts.remove(at: delTar)
463
- }
464
- validProducts.append(aProd)
465
- }
466
- }
467
-
468
- func request(_ request: SKRequest, didFailWithError error: Error) {
469
- let nsError = error as NSError
470
- if request is SKReceiptRefreshRequest {
471
- if let unwrappedReceiptBlock = receiptBlock {
472
- let standardError = NSError(domain: nsError.domain, code: 9, userInfo: nsError.userInfo)
473
- unwrappedReceiptBlock(nil, standardError)
474
- receiptBlock = nil
475
- return
476
- }else {
477
- if let key: String = productsRequest?.key{
478
- myQueue.sync(execute: { [self] in
479
- rejectPromises(
480
- forKey: key,
481
- code: standardErrorCode(nsError.code),
482
- message: error.localizedDescription,
483
- error: error)}
484
- )
485
-
486
- }
487
- }
488
- }
489
- }
490
-
491
-
492
- func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
493
- for transaction in transactions {
494
- switch transaction.transactionState {
495
- case .purchasing:
496
- print("\n\n Purchase Started !! \n\n")
497
- break
498
- case .purchased:
499
- print("\n\n\n\n\n Purchase Successful !! \n\n\n\n\n.")
500
- purchaseProcess(transaction)
501
- break
502
- case .restored:
503
- print("Restored ")
504
- SKPaymentQueue.default().finishTransaction(transaction)
505
- break
506
- case .deferred:
507
- print("Deferred (awaiting approval via parental controls, etc.)")
508
- myQueue.sync(execute: { [self] in
509
- if hasListeners {
510
- let err = [
511
- "debugMessage" : "The payment was deferred (awaiting approval via parental controls for instance)",
512
- "code" : "E_DEFERRED_PAYMENT",
513
- "message" : "The payment was deferred (awaiting approval via parental controls for instance)",
514
- "productId" : transaction.payment.productIdentifier,
515
- "quantity" : "\(transaction.payment.quantity)"
516
- ]
517
- sendEvent(withName: "purchase-error", body: err)
518
- }
519
- rejectPromises(
520
- forKey: transaction.payment.productIdentifier,
521
- code: "E_DEFERRED_PAYMENT",
522
- message: "The payment was deferred (awaiting approval via parental controls for instance)",
523
- error: nil)
524
- });
525
-
526
- case .failed:
527
- print("\n\n\n\n\n\n Purchase Failed !! \n\n\n\n\n")
528
- SKPaymentQueue.default().finishTransaction(transaction)
529
- myQueue.sync(execute: { [self] in
530
- let nsError = transaction.error as NSError?
531
- if hasListeners {
532
- let code = nsError?.code
533
- let responseCode = String(code ?? 0)
534
- let err = [
535
- "responseCode" : responseCode,
536
- "debugMessage" : transaction.error?.localizedDescription,
537
- "code" : standardErrorCode(code),
538
- "message" : transaction.error?.localizedDescription,
539
- "productId" : transaction.payment.productIdentifier
540
- ]
541
- sendEvent(withName: "purchase-error", body: err)
542
- }
543
-
544
- rejectPromises(
545
- forKey: transaction.payment.productIdentifier,
546
- code: standardErrorCode(nsError?.code),
547
- message: nsError?.localizedDescription,
548
- error: nsError)
549
-
550
- })
551
- break;
552
- }
553
-
554
- }
555
- }
556
-
557
- func finishTransaction(withIdentifier transactionIdentifier: String?) {
558
- let queue = SKPaymentQueue.default()
559
- for transaction in queue.transactions {
560
- if transaction.transactionIdentifier == transactionIdentifier {
561
- SKPaymentQueue.default().finishTransaction(transaction)
562
- }
563
- }
564
- }
565
-
566
- func paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue) {
567
- //////// RESTORE
568
- print("\n\n\n paymentQueueRestoreCompletedTransactionsFinished \n\n.")
569
- var items = [[String: Any?]]()
570
- for transaction in queue.transactions {
571
- if transaction.transactionState == .restored || transaction.transactionState == .purchased {
572
- getPurchaseData(transaction) { restored in
573
- if let restored = restored {
574
- items.append(restored)
575
- }
576
- SKPaymentQueue.default().finishTransaction(transaction)
577
- }
578
- }
579
- }
580
- resolvePromises(forKey: "availableItems", value: items)
581
- }
582
-
583
- func paymentQueue(_ queue: SKPaymentQueue, restoreCompletedTransactionsFailedWithError error: Error) {
584
- myQueue.sync(execute: { [self] in
585
- rejectPromises(
586
- forKey: "availableItems",
587
- code: standardErrorCode((error as NSError).code),
588
- message: error.localizedDescription,
589
- error: error)
590
- })
591
- print("\n\n\n restoreCompletedTransactionsFailedWithError \n\n.")
592
- }
593
-
594
- func purchaseProcess(_ transaction: SKPaymentTransaction) {
595
- if pendingTransactionWithAutoFinish {
596
- SKPaymentQueue.default().finishTransaction(transaction)
597
- pendingTransactionWithAutoFinish = false
598
- }
599
- getPurchaseData(transaction) { [self] purchase in
600
- resolvePromises(forKey: transaction.payment.productIdentifier, value: purchase)
601
-
602
- // additionally send event
603
- if hasListeners {
604
- sendEvent(withName: "purchase-updated", body: purchase)
605
- }
606
- }
607
- }
608
-
609
-
610
- func standardErrorCode(_ code: Int?) -> String? {
611
-
612
-
613
- let descriptions = [
614
- "E_UNKNOWN",
615
- "E_SERVICE_ERROR",
616
- "E_USER_CANCELLED",
617
- "E_USER_ERROR",
618
- "E_USER_ERROR",
619
- "E_ITEM_UNAVAILABLE",
620
- "E_REMOTE_ERROR",
621
- "E_NETWORK_ERROR",
622
- "E_SERVICE_ERROR",
623
- "E_RECEIPT_FAILED",
624
- "E_RECEIPT_FINISHED_FAILED"
625
- ]
626
- guard let code = code else {
627
- return descriptions[0]
628
- }
629
-
630
- if code > descriptions.count - 1 || code < 0 { // Fix crash app without internet connection
631
- return descriptions[0]
632
- }
633
- return descriptions[code]
634
- }
635
-
636
-
637
- func getProductObject(_ product: SKProduct) -> [String : Any?] {
638
- let formatter = NumberFormatter()
639
- formatter.numberStyle = .currency
640
- formatter.locale = product.priceLocale
641
-
642
- let localizedPrice = formatter.string(from: product.price)
643
- var introductoryPrice = localizedPrice
644
- var introductoryPriceAsAmountIOS = "\(product.price)"
645
-
646
- var introductoryPricePaymentMode = ""
647
- var introductoryPriceNumberOfPeriods = ""
648
-
649
- var introductoryPriceSubscriptionPeriod = ""
650
-
651
- var currencyCode: String? = ""
652
- var countryCode: String? = ""
653
- var periodNumberIOS = "0"
654
- var periodUnitIOS = ""
655
-
656
- var itemType = "iap"
657
-
658
- if #available(iOS 11.2, tvOS 11.2, *) {
659
- let numOfUnits = UInt(product.subscriptionPeriod?.numberOfUnits ?? 0)
660
- let unit = product.subscriptionPeriod?.unit
661
-
662
- if unit == .year {
663
- periodUnitIOS = "YEAR"
664
- } else if unit == .month {
665
- periodUnitIOS = "MONTH"
666
- } else if unit == .week {
667
- periodUnitIOS = "WEEK"
668
- } else if unit == .day {
669
- periodUnitIOS = "DAY"
670
- }
671
-
672
- periodNumberIOS = String(format: "%lu", numOfUnits)
673
- if numOfUnits != 0 {
674
- itemType = "subs"
675
- }
676
-
677
- // subscriptionPeriod = product.subscriptionPeriod ? [product.subscriptionPeriod stringValue] : @"";
678
- //introductoryPrice = product.introductoryPrice != nil ? [NSString stringWithFormat:@"%@", product.introductoryPrice] : @"";
679
- if product.introductoryPrice != nil {
680
- formatter.locale = product.introductoryPrice?.priceLocale
681
- if let price = product.introductoryPrice?.price {
682
- introductoryPrice = formatter.string(from: price)
683
- }
684
- introductoryPriceAsAmountIOS = product.introductoryPrice?.price.stringValue ?? ""
685
-
686
- switch product.introductoryPrice?.paymentMode {
687
- case .freeTrial:
688
- introductoryPricePaymentMode = "FREETRIAL"
689
- introductoryPriceNumberOfPeriods = NSNumber(value: product.introductoryPrice?.subscriptionPeriod.numberOfUnits ?? 0).stringValue
690
- case .payAsYouGo:
691
- introductoryPricePaymentMode = "PAYASYOUGO"
692
- introductoryPriceNumberOfPeriods = NSNumber(value: product.introductoryPrice?.numberOfPeriods ?? 0).stringValue
693
- case .payUpFront:
694
- introductoryPricePaymentMode = "PAYUPFRONT"
695
- introductoryPriceNumberOfPeriods = NSNumber(value: product.introductoryPrice?.subscriptionPeriod.numberOfUnits ?? 0).stringValue
696
- default:
697
- introductoryPricePaymentMode = ""
698
- introductoryPriceNumberOfPeriods = "0"
699
- }
700
-
701
- if product.introductoryPrice?.subscriptionPeriod.unit == .day {
702
- introductoryPriceSubscriptionPeriod = "DAY"
703
- } else if product.introductoryPrice?.subscriptionPeriod.unit == .week {
704
- introductoryPriceSubscriptionPeriod = "WEEK"
705
- } else if product.introductoryPrice?.subscriptionPeriod.unit == .month {
706
- introductoryPriceSubscriptionPeriod = "MONTH"
707
- }else if product.introductoryPrice?.subscriptionPeriod.unit == .year {
708
- introductoryPriceSubscriptionPeriod = "YEAR"
709
- } else {
710
- introductoryPriceSubscriptionPeriod = ""
711
- }
712
- }
713
- else{
714
- introductoryPrice = ""
715
- introductoryPriceAsAmountIOS = ""
716
- introductoryPricePaymentMode = ""
717
- introductoryPriceNumberOfPeriods = ""
718
- introductoryPriceSubscriptionPeriod = ""
719
- }
720
- }
721
-
722
-
723
-
724
- if #available(iOS 10.0, tvOS 10.0, *) {
725
- currencyCode = product.priceLocale.currencyCode
726
- }
727
-
728
- if #available(iOS 13.0, tvOS 13.0, *) {
729
- countryCode = SKPaymentQueue.default().storefront?.countryCode
730
- } else if #available(iOS 10.0, tvOS 10.0, *) {
731
- countryCode = product.priceLocale.regionCode
732
- }
733
-
734
- var discounts: [[String: String?]]?
735
-
736
- if #available(iOS 12.2, tvOS 12.2, *) {
737
- discounts = getDiscountData(product)
738
- }
739
-
740
-
741
- let obj: [String: Any?] = [
742
- "productId" : product.productIdentifier,
743
- "price" : "\(product.price)",
744
- "currency" : currencyCode,
745
- "countryCode" : countryCode ?? "",
746
- "type" : itemType,
747
- "title" : product.localizedTitle != "" ? product.localizedTitle : "",
748
- "description" : product.localizedDescription != "" ? product.localizedDescription : "",
749
- "localizedPrice" : localizedPrice,
750
- "subscriptionPeriodNumberIOS" : periodNumberIOS,
751
- "subscriptionPeriodUnitIOS" : periodUnitIOS,
752
- "introductoryPrice" : introductoryPrice,
753
- "introductoryPriceAsAmountIOS" : introductoryPriceAsAmountIOS,
754
- "introductoryPricePaymentModeIOS" : introductoryPricePaymentMode,
755
- "introductoryPriceNumberOfPeriodsIOS" : introductoryPriceNumberOfPeriods,
756
- "introductoryPriceSubscriptionPeriodIOS" : introductoryPriceSubscriptionPeriod,
757
- "discounts" : discounts
758
- ]
759
-
760
- return obj
761
- }
762
-
763
-
764
-
765
- func getDiscountData(_ product: SKProduct) -> [[String:String?]]? {
766
- if #available(iOS 12.2, tvOS 12.2, *) {
767
- var mappedDiscounts : [[String:String?]] = []
768
- var localizedPrice: String?
769
- var paymendMode: String?
770
- var subscriptionPeriods: String?
771
- var discountType: String?
772
-
773
- for discount in product.discounts {
774
- let formatter = NumberFormatter()
775
- formatter.numberStyle = .currency
776
- formatter.locale = discount.priceLocale
777
- localizedPrice = formatter.string(from: discount.price)
778
- var numberOfPeriods: String?
779
-
780
- switch discount.paymentMode {
781
- case .freeTrial:
782
- paymendMode = "FREETRIAL"
783
- numberOfPeriods = NSNumber(value: discount.subscriptionPeriod.numberOfUnits ).stringValue
784
- break
785
- case .payAsYouGo:
786
- paymendMode = "PAYASYOUGO"
787
- numberOfPeriods = NSNumber(value: discount.numberOfPeriods).stringValue
788
- break
789
- case .payUpFront:
790
- paymendMode = "PAYUPFRONT"
791
- numberOfPeriods = NSNumber(value: discount.subscriptionPeriod.numberOfUnits ).stringValue
792
- break
793
- default:
794
- paymendMode = ""
795
- numberOfPeriods = "0"
796
- break
797
- }
798
- switch discount.subscriptionPeriod.unit {
799
- case .day:
800
- subscriptionPeriods = "DAY"
801
- case .week:
802
- subscriptionPeriods = "WEEK"
803
- case .month:
804
- subscriptionPeriods = "MONTH"
805
- case .year:
806
- subscriptionPeriods = "YEAR"
807
- default:
808
- subscriptionPeriods = ""
809
- }
810
-
811
-
812
- let discountIdentifier = discount.identifier
813
- switch discount.type {
814
- case SKProductDiscount.Type.introductory:
815
- discountType = "INTRODUCTORY"
816
- break
817
- case SKProductDiscount.Type.subscription:
818
- discountType = "SUBSCRIPTION"
819
- break
820
- default:
821
- discountType = ""
822
- break
823
- }
824
-
825
-
826
- let discountObj = [
827
- "identifier" : discountIdentifier,
828
- "type" : discountType,
829
- "numberOfPeriods" : numberOfPeriods,
830
- "price" : "\(discount.price)",
831
- "localizedPrice" : localizedPrice,
832
- "paymentMode" : paymendMode,
833
- "subscriptionPeriod" : subscriptionPeriods
834
- ]
835
- mappedDiscounts.append(discountObj)
836
- }
837
- return mappedDiscounts
838
- }
839
- return nil
840
- }
841
-
842
-
843
- func getPurchaseData(_ transaction: SKPaymentTransaction, withBlock block: @escaping (_ transactionDict: [String : Any]?) -> Void) {
844
- requestReceiptData(withBlock: false) { receiptData, error in
845
- if receiptData == nil {
846
- block(nil)
847
- } else {
848
- var purchase = [
849
- "transactionDate" : transaction.transactionDate?.millisecondsSince1970String,
850
- "transactionId" : transaction.transactionIdentifier,
851
- "productId" : transaction.payment.productIdentifier,
852
- "transactionReceipt" : receiptData?.base64EncodedString(options: [])
853
- ]
854
- // originalTransaction is available for restore purchase and purchase of cancelled/expired subscriptions
855
- if let originalTransaction = transaction.original {
856
- purchase["originalTransactionDateIOS"] = originalTransaction.transactionDate?.millisecondsSince1970String
857
- purchase["originalTransactionIdentifierIOS"] = originalTransaction.transactionIdentifier
858
- }
859
-
860
- block(purchase as [String : Any])
861
- }
862
- }
863
- }
864
-
865
- func requestReceiptData(withBlock forceRefresh: Bool, withBlock block: @escaping (_ data: Data?, _ error: Error?) -> Void) {
866
- print("\n\n\n requestReceiptDataWithBlock with force refresh: \(forceRefresh ? "YES" : "NO") \n\n.")
867
- if forceRefresh || isReceiptPresent() == false {
868
- let refreshRequest = SKReceiptRefreshRequest()
869
- refreshRequest.delegate = self
870
- refreshRequest.start()
871
- receiptBlock = block
872
- } else {
873
- receiptBlock = nil
874
- block(receiptData(), nil)
875
- }
876
- }
877
-
878
- func isReceiptPresent() -> Bool {
879
- let receiptURL = Bundle.main.appStoreReceiptURL
880
- var canReachError: Error? = nil
881
- do {
882
- try _ = receiptURL?.checkResourceIsReachable()
883
- } catch let error {
884
- canReachError = error
885
- }
886
- return canReachError == nil
887
- }
888
-
889
- func receiptData() -> Data? {
890
- let receiptURL = Bundle.main.appStoreReceiptURL
891
- var receiptData: Data? = nil
892
- if let receiptURL = receiptURL {
893
- do{
894
- try receiptData = Data(contentsOf: receiptURL)
895
- }catch _{
896
-
897
- }
898
- }
899
- return receiptData
900
- }
901
-
902
- func requestDidFinish(_ request: SKRequest) {
903
- if request is SKReceiptRefreshRequest {
904
- if isReceiptPresent() == true {
905
- print("Receipt refreshed success.")
906
- if let receiptBlock = receiptBlock {
907
- receiptBlock(receiptData(), nil)
908
- }
909
- } else if let receiptBlock = receiptBlock {
910
- print("Finished but receipt refreshed failed!")
911
- let error = NSError(domain: "Receipt request finished but it failed!", code: 10, userInfo: nil)
912
- receiptBlock(nil, error)
913
- }
914
- receiptBlock = nil
915
- }
916
- }
917
-
918
-
919
- func paymentQueue(_ queue: SKPaymentQueue, removedTransactions transactions: [SKPaymentTransaction]) {
920
- print("removedTransactions")
921
- guard var unwrappedCount = countPendingTransaction else {
922
- return
923
- }
924
- if unwrappedCount > 0 {
925
- unwrappedCount -= transactions.count
926
- if unwrappedCount == 0 {
927
- resolvePromises(forKey: "cleaningTransactions", value: nil)
928
- countPendingTransaction = nil
929
- }
930
- }
931
- }
932
- }