AppStoreProvider.swift 9.38 KB
Newer Older
Davide De Rosa's avatar
Davide De Rosa committed
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
//
//  AppStoreProvider.swift
//  PIALibrary
//
//  Created by Davide De Rosa on 10/21/17.
//  Copyright © 2017 London Trust Media. All rights reserved.
//

import Foundation
import StoreKit
import SwiftyBeaver

private let log = SwiftyBeaver.self

class AppStoreProvider: NSObject, InAppProvider {
    private(set) var uncreditedTransactions: [InAppTransaction]
    
    private var productsRequest: SKProductsRequest?

    private var receiptRefreshRequest: SKReceiptRefreshRequest?

    private var productsCallback: LibraryCallback<[InAppProduct]>?

    private var purchaseCallback: LibraryCallback<InAppTransaction>?

    private var receiptCallback: SuccessLibraryCallback?

    override init() {
        uncreditedTransactions = []
        super.init()
    }

    deinit {
        SKPaymentQueue.default().remove(self)
    }

    // MARK: InAppProvider

    private(set) var availableProducts: [InAppProduct]?

    var paymentReceipt: Data? {
        guard let url = Bundle.main.appStoreReceiptURL else {
            return nil
        }
        return try? Data(contentsOf: url)
    }
    
    var hasUncreditedTransactions: Bool {
        return !uncreditedTransactions.isEmpty
    }

    func startObservingTransactions() {
        log.debug("Start observing transactions")
        
        SKPaymentQueue.default().add(self)
    }
    
    func stopObservingTransactions() {
        log.debug("Stop observing transactions")
        
        SKPaymentQueue.default().remove(self)
    }
    
    func fetchProducts(identifiers: [String], _ callback: (([InAppProduct]?, Error?) -> Void)?) {
        guard !identifiers.isEmpty else {
            callback?([], nil)
            return
        }

        log.debug("Requesting products: \(identifiers)")

        productsCallback = callback
        productsRequest?.cancel()
        productsRequest = SKProductsRequest(productIdentifiers: Set(identifiers))
        productsRequest?.delegate = self
        productsRequest?.start()
    }

    func purchaseProduct(_ product: InAppProduct, _ callback: ((InAppTransaction?, Error?) -> Void)?) {
        guard product is AppStoreProduct else {
            fatalError("Product must be AppStoreProduct")
        }
        guard (purchaseCallback == nil) else {
            log.warning("Purchase in progress")
            return
        }
87
88
89
90
91
        if !Client.configuration.arePurchasesAvailable() {
            log.warning("Purchases not available in sandbox")
            callback?(nil, ClientError.sandboxPurchase)
            return
        }
Davide De Rosa's avatar
Davide De Rosa committed
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
        let payment = SKPayment(product: product.native as! SKProduct)
        log.debug("Purchasing product with identifier: \(payment.productIdentifier)")

        purchaseCallback = callback
        SKPaymentQueue.default().add(payment)
    }
    
    func uncreditedTransaction(for product: InAppProduct) -> InAppTransaction? {
        guard product is AppStoreProduct else {
            fatalError("Product must be AppStoreProduct")
        }
        for uncredited in uncreditedTransactions {
            let nativeTransaction = uncredited.native as! SKPaymentTransaction
            let nativeProduct = product.native as! SKProduct
            if (nativeTransaction.payment.productIdentifier == nativeProduct.productIdentifier) {
                return uncredited
            }
        }
        return nil
    }

    func finishTransaction(_ transaction: InAppTransaction, success: Bool) {
        guard transaction is AppStoreTransaction else {
            fatalError("Transaction must be AppStoreTransaction")
        }
        finishAndRemoveTransaction(transaction.native as! SKPaymentTransaction, success: success)
    }

    func refreshPaymentReceipt(_ callback: SuccessLibraryCallback?) {
        log.debug("Refreshing local copy of payment receipt...")

        receiptCallback = callback
        receiptRefreshRequest = SKReceiptRefreshRequest(receiptProperties: nil)
        receiptRefreshRequest?.delegate = self
        receiptRefreshRequest?.start()
    }
    
    // MARK: Helpers

    private func addUncreditedTransaction(_ transaction: SKPaymentTransaction) {
        log.debug("Adding uncredited transaction: \(transaction)")
Jose Blaya's avatar
Jose Blaya committed
133
134
135
136
137
        
        if let _ = Client.configuration.plan(forProductIdentifier: transaction.payment.productIdentifier) {
            //Only add the uncredited transaction if the plan is available
            uncreditedTransactions.append(AppStoreTransaction(native: transaction))
        }
Davide De Rosa's avatar
Davide De Rosa committed
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
        
        log.debug("Uncredited transactions now: \(uncreditedTransactions)")

        Macros.postNotification(.__InAppDidAddUncredited)
    }
    
    private func removeUncreditedTransaction(_ transactionToRemove: SKPaymentTransaction) {
        log.debug("Removing uncredited transaction: \(transactionToRemove)")
        
        for (i, transaction) in uncreditedTransactions.enumerated() {
            if (transaction.native as? SKPaymentTransaction == transactionToRemove) {
                uncreditedTransactions.remove(at: i)
                break
            }
        }
        
        log.debug("Uncredited transactions now: \(uncreditedTransactions)")
    }

    private func finishAndRemoveTransaction(_ transaction: SKPaymentTransaction, success: Bool) {
        if success {
            log.debug("Finishing successful transaction: \(transaction)")
        } else {
            log.debug("Finishing failed/cancelled transaction: \(transaction)")
        }
        
        SKPaymentQueue.default().finishTransaction(transaction)
        removeUncreditedTransaction(transaction)
    }
}

extension AppStoreProvider: SKProductsRequestDelegate {
    func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
        guard (request == productsRequest) else {
            return
        }
        productsRequest = nil
        log.debug("Retrieved products: \(response.products)")

        var availableProducts = [InAppProduct]()
        for product in response.products {
            log.debug("  -> \(product.localizedTitle) @ \(product.price)")
            availableProducts.append(AppStoreProduct(native: product))
        }
        self.availableProducts = availableProducts

        productsCallback?(availableProducts, nil)
        productsCallback = nil
    }
}

extension AppStoreProvider: SKPaymentTransactionObserver {
    func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
        log.debug("Transactions updated: \(transactions)")

        for transaction in transactions {
            switch transaction.transactionState {
            case .purchasing:
                break

            case .purchased:
                log.debug("  -> Purchased: \(transaction)")

                addUncreditedTransaction(transaction)
                purchaseCallback?(AppStoreTransaction(native: transaction), nil)
                purchaseCallback = nil

            case .deferred:
                log.debug("  -> Deferred: \(transaction)")

//                #warning TODO: Amir, implement and test Ask to Buy
//                NSError *error = [[NSError alloc] initWithDomain:ErrorDomain
//                code:ErrorCodeAskToBuy
//                userInfo:@{NSLocalizedDescriptionKey: NSLocalizedXXXXString(@"Your payment requires approval.", @"payment transaction deferred message (Ask to Buy enabled)")}];
//
//                Macros.postNotification(.StoreDidFailToPurchase, error)

            case .restored:
                // not applicable for non-renewable subscriptions
                break

            case .failed:
                if let error = transaction.error {
                    log.error("Failed transaction: \(transaction) (error: \(error))")
                } else {
                    log.warning("Transaction was cancelled")
                }

                finishAndRemoveTransaction(transaction, success: false)

                if let error = transaction.error as? SKError, (error.code == .paymentCancelled) {
                    purchaseCallback?(nil, nil)
                } else {
                    purchaseCallback?(nil, transaction.error)
                }
                purchaseCallback = nil
            }
        }
    }
237
238
239
240
241
    
    /// This delegate is called when the user clicks the subscription in the AppStore. We are currently not handling the purchase from there, so we will return false until we implement a way to handle it.
    func paymentQueue(_ queue: SKPaymentQueue, shouldAddStorePayment payment: SKPayment, for product: SKProduct) -> Bool {
        return false
    }
Davide De Rosa's avatar
Davide De Rosa committed
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
}

extension AppStoreProvider: SKRequestDelegate {
    func requestDidFinish(_ request: SKRequest) {
        guard (request == receiptRefreshRequest) else {
            return
        }
        receiptRefreshRequest = nil
        log.debug("Finished refreshing payment receipt")
        receiptCallback?(nil)
        receiptCallback = nil
    }

    func request(_ request: SKRequest, didFailWithError error: Error) {
        guard (request == receiptRefreshRequest) else {
            return
        }
        receiptRefreshRequest = nil
        log.error("Failed to refresh payment receipt (error: \(error))")
        receiptCallback?(error)
        receiptCallback = nil
    }
}

/// :nodoc:
extension SKProduct {
    open override var description: String {
        return productIdentifier
    }
}

/// :nodoc:
extension SKPaymentTransaction {
    open override var description: String {
        return "{'\(transactionIdentifier ?? "")' -> \(payment.productIdentifier)}" 
    }
}